babylon.viewer.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194
  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. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * 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.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. this.x = x;
  2299. this.y = y;
  2300. }
  2301. /**
  2302. * Gets a string with the Vector2 coordinates
  2303. * @returns a string with the Vector2 coordinates
  2304. */
  2305. Vector2.prototype.toString = function () {
  2306. return "{X: " + this.x + " Y:" + this.y + "}";
  2307. };
  2308. /**
  2309. * Gets class name
  2310. * @returns the string "Vector2"
  2311. */
  2312. Vector2.prototype.getClassName = function () {
  2313. return "Vector2";
  2314. };
  2315. /**
  2316. * Gets current vector hash code
  2317. * @returns the Vector2 hash code as a number
  2318. */
  2319. Vector2.prototype.getHashCode = function () {
  2320. var hash = this.x || 0;
  2321. hash = (hash * 397) ^ (this.y || 0);
  2322. return hash;
  2323. };
  2324. // Operators
  2325. /**
  2326. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2327. * @param array defines the source array
  2328. * @param index defines the offset in source array
  2329. * @returns the current Vector2
  2330. */
  2331. Vector2.prototype.toArray = function (array, index) {
  2332. if (index === void 0) { index = 0; }
  2333. array[index] = this.x;
  2334. array[index + 1] = this.y;
  2335. return this;
  2336. };
  2337. /**
  2338. * Copy the current vector to an array
  2339. * @returns a new array with 2 elements: the Vector2 coordinates.
  2340. */
  2341. Vector2.prototype.asArray = function () {
  2342. var result = new Array();
  2343. this.toArray(result, 0);
  2344. return result;
  2345. };
  2346. /**
  2347. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2348. * @param source defines the source Vector2
  2349. * @returns the current updated Vector2
  2350. */
  2351. Vector2.prototype.copyFrom = function (source) {
  2352. this.x = source.x;
  2353. this.y = source.y;
  2354. return this;
  2355. };
  2356. /**
  2357. * Sets the Vector2 coordinates with the given floats
  2358. * @param x defines the first coordinate
  2359. * @param y defines the second coordinate
  2360. * @returns the current updated Vector2
  2361. */
  2362. Vector2.prototype.copyFromFloats = function (x, y) {
  2363. this.x = x;
  2364. this.y = y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Sets the Vector2 coordinates with the given floats
  2369. * @param x defines the first coordinate
  2370. * @param y defines the second coordinate
  2371. * @returns the current updated Vector2
  2372. */
  2373. Vector2.prototype.set = function (x, y) {
  2374. return this.copyFromFloats(x, y);
  2375. };
  2376. /**
  2377. * Add another vector with the current one
  2378. * @param otherVector defines the other vector
  2379. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2380. */
  2381. Vector2.prototype.add = function (otherVector) {
  2382. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2383. };
  2384. /**
  2385. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @param result defines the target vector
  2388. * @returns the unmodified current Vector2
  2389. */
  2390. Vector2.prototype.addToRef = function (otherVector, result) {
  2391. result.x = this.x + otherVector.x;
  2392. result.y = this.y + otherVector.y;
  2393. return this;
  2394. };
  2395. /**
  2396. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2397. * @param otherVector defines the other vector
  2398. * @returns the current updated Vector2
  2399. */
  2400. Vector2.prototype.addInPlace = function (otherVector) {
  2401. this.x += otherVector.x;
  2402. this.y += otherVector.y;
  2403. return this;
  2404. };
  2405. /**
  2406. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2407. * @param otherVector defines the other vector
  2408. * @returns a new Vector2
  2409. */
  2410. Vector2.prototype.addVector3 = function (otherVector) {
  2411. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2412. };
  2413. /**
  2414. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2415. * @param otherVector defines the other vector
  2416. * @returns a new Vector2
  2417. */
  2418. Vector2.prototype.subtract = function (otherVector) {
  2419. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2420. };
  2421. /**
  2422. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2423. * @param otherVector defines the other vector
  2424. * @param result defines the target vector
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2428. result.x = this.x - otherVector.x;
  2429. result.y = this.y - otherVector.y;
  2430. return this;
  2431. };
  2432. /**
  2433. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns the current updated Vector2
  2436. */
  2437. Vector2.prototype.subtractInPlace = function (otherVector) {
  2438. this.x -= otherVector.x;
  2439. this.y -= otherVector.y;
  2440. return this;
  2441. };
  2442. /**
  2443. * Multiplies in place the current Vector2 coordinates by the given ones
  2444. * @param otherVector defines the other vector
  2445. * @returns the current updated Vector2
  2446. */
  2447. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2448. this.x *= otherVector.x;
  2449. this.y *= otherVector.y;
  2450. return this;
  2451. };
  2452. /**
  2453. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2454. * @param otherVector defines the other vector
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.multiply = function (otherVector) {
  2458. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2459. };
  2460. /**
  2461. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2462. * @param otherVector defines the other vector
  2463. * @param result defines the target vector
  2464. * @returns the unmodified current Vector2
  2465. */
  2466. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2467. result.x = this.x * otherVector.x;
  2468. result.y = this.y * otherVector.y;
  2469. return this;
  2470. };
  2471. /**
  2472. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2473. * @param x defines the first coordinate
  2474. * @param y defines the second coordinate
  2475. * @returns a new Vector2
  2476. */
  2477. Vector2.prototype.multiplyByFloats = function (x, y) {
  2478. return new Vector2(this.x * x, this.y * y);
  2479. };
  2480. /**
  2481. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2482. * @param otherVector defines the other vector
  2483. * @returns a new Vector2
  2484. */
  2485. Vector2.prototype.divide = function (otherVector) {
  2486. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2487. };
  2488. /**
  2489. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2490. * @param otherVector defines the other vector
  2491. * @param result defines the target vector
  2492. * @returns the unmodified current Vector2
  2493. */
  2494. Vector2.prototype.divideToRef = function (otherVector, result) {
  2495. result.x = this.x / otherVector.x;
  2496. result.y = this.y / otherVector.y;
  2497. return this;
  2498. };
  2499. /**
  2500. * Divides the current Vector3 coordinates by the given ones
  2501. * @param otherVector defines the other vector
  2502. * @returns the current updated Vector2
  2503. */
  2504. Vector2.prototype.divideInPlace = function (otherVector) {
  2505. return this.divideToRef(otherVector, this);
  2506. };
  2507. /**
  2508. * Gets a new Vector2 with current Vector2 negated coordinates
  2509. * @returns a new Vector2
  2510. */
  2511. Vector2.prototype.negate = function () {
  2512. return new Vector2(-this.x, -this.y);
  2513. };
  2514. /**
  2515. * Multiply the Vector2 coordinates by scale
  2516. * @param scale defines the scaling factor
  2517. * @returns the current updated Vector2
  2518. */
  2519. Vector2.prototype.scaleInPlace = function (scale) {
  2520. this.x *= scale;
  2521. this.y *= scale;
  2522. return this;
  2523. };
  2524. /**
  2525. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2526. * @param scale defines the scaling factor
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.prototype.scale = function (scale) {
  2530. var result = new Vector2(0, 0);
  2531. this.scaleToRef(scale, result);
  2532. return result;
  2533. };
  2534. /**
  2535. * Scale the current Vector2 values by a factor to a given Vector2
  2536. * @param scale defines the scale factor
  2537. * @param result defines the Vector2 object where to store the result
  2538. * @returns the unmodified current Vector2
  2539. */
  2540. Vector2.prototype.scaleToRef = function (scale, result) {
  2541. result.x = this.x * scale;
  2542. result.y = this.y * scale;
  2543. return this;
  2544. };
  2545. /**
  2546. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2547. * @param scale defines the scale factor
  2548. * @param result defines the Vector2 object where to store the result
  2549. * @returns the unmodified current Vector2
  2550. */
  2551. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2552. result.x += this.x * scale;
  2553. result.y += this.y * scale;
  2554. return this;
  2555. };
  2556. /**
  2557. * Gets a boolean if two vectors are equals
  2558. * @param otherVector defines the other vector
  2559. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2560. */
  2561. Vector2.prototype.equals = function (otherVector) {
  2562. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2563. };
  2564. /**
  2565. * Gets a boolean if two vectors are equals (using an epsilon value)
  2566. * @param otherVector defines the other vector
  2567. * @param epsilon defines the minimal distance to consider equality
  2568. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2569. */
  2570. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2571. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2572. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2573. };
  2574. // Properties
  2575. /**
  2576. * Gets the length of the vector
  2577. * @returns the vector length (float)
  2578. */
  2579. Vector2.prototype.length = function () {
  2580. return Math.sqrt(this.x * this.x + this.y * this.y);
  2581. };
  2582. /**
  2583. * Gets the vector squared length
  2584. * @returns the vector squared length (float)
  2585. */
  2586. Vector2.prototype.lengthSquared = function () {
  2587. return (this.x * this.x + this.y * this.y);
  2588. };
  2589. // Methods
  2590. /**
  2591. * Normalize the vector
  2592. * @returns the current updated Vector2
  2593. */
  2594. Vector2.prototype.normalize = function () {
  2595. var len = this.length();
  2596. if (len === 0)
  2597. return this;
  2598. var num = 1.0 / len;
  2599. this.x *= num;
  2600. this.y *= num;
  2601. return this;
  2602. };
  2603. /**
  2604. * Gets a new Vector2 copied from the Vector2
  2605. * @returns a new Vector2
  2606. */
  2607. Vector2.prototype.clone = function () {
  2608. return new Vector2(this.x, this.y);
  2609. };
  2610. // Statics
  2611. /**
  2612. * Gets a new Vector2(0, 0)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.Zero = function () {
  2616. return new Vector2(0, 0);
  2617. };
  2618. /**
  2619. * Gets a new Vector2(1, 1)
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.One = function () {
  2623. return new Vector2(1, 1);
  2624. };
  2625. /**
  2626. * Gets a new Vector2 set from the given index element of the given array
  2627. * @param array defines the data source
  2628. * @param offset defines the offset in the data source
  2629. * @returns a new Vector2
  2630. */
  2631. Vector2.FromArray = function (array, offset) {
  2632. if (offset === void 0) { offset = 0; }
  2633. return new Vector2(array[offset], array[offset + 1]);
  2634. };
  2635. /**
  2636. * Sets "result" from the given index element of the given array
  2637. * @param array defines the data source
  2638. * @param offset defines the offset in the data source
  2639. * @param result defines the target vector
  2640. */
  2641. Vector2.FromArrayToRef = function (array, offset, result) {
  2642. result.x = array[offset];
  2643. result.y = array[offset + 1];
  2644. };
  2645. /**
  2646. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2647. * @param value1 defines 1st point of control
  2648. * @param value2 defines 2nd point of control
  2649. * @param value3 defines 3rd point of control
  2650. * @param value4 defines 4th point of control
  2651. * @param amount defines the interpolation factor
  2652. * @returns a new Vector2
  2653. */
  2654. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2655. var squared = amount * amount;
  2656. var cubed = amount * squared;
  2657. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2658. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2659. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2660. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2661. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2662. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2663. return new Vector2(x, y);
  2664. };
  2665. /**
  2666. * 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".
  2667. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2668. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2669. * @param value defines the value to clamp
  2670. * @param min defines the lower limit
  2671. * @param max defines the upper limit
  2672. * @returns a new Vector2
  2673. */
  2674. Vector2.Clamp = function (value, min, max) {
  2675. var x = value.x;
  2676. x = (x > max.x) ? max.x : x;
  2677. x = (x < min.x) ? min.x : x;
  2678. var y = value.y;
  2679. y = (y > max.y) ? max.y : y;
  2680. y = (y < min.y) ? min.y : y;
  2681. return new Vector2(x, y);
  2682. };
  2683. /**
  2684. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2685. * @param value1 defines the 1st control point
  2686. * @param tangent1 defines the outgoing tangent
  2687. * @param value2 defines the 2nd control point
  2688. * @param tangent2 defines the incoming tangent
  2689. * @param amount defines the interpolation factor
  2690. * @returns a new Vector2
  2691. */
  2692. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2693. var squared = amount * amount;
  2694. var cubed = amount * squared;
  2695. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2696. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2697. var part3 = (cubed - (2.0 * squared)) + amount;
  2698. var part4 = cubed - squared;
  2699. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2700. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2701. return new Vector2(x, y);
  2702. };
  2703. /**
  2704. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2705. * @param start defines the start vector
  2706. * @param end defines the end vector
  2707. * @param amount defines the interpolation factor
  2708. * @returns a new Vector2
  2709. */
  2710. Vector2.Lerp = function (start, end, amount) {
  2711. var x = start.x + ((end.x - start.x) * amount);
  2712. var y = start.y + ((end.y - start.y) * amount);
  2713. return new Vector2(x, y);
  2714. };
  2715. /**
  2716. * Gets the dot product of the vector "left" and the vector "right"
  2717. * @param left defines first vector
  2718. * @param right defines second vector
  2719. * @returns the dot product (float)
  2720. */
  2721. Vector2.Dot = function (left, right) {
  2722. return left.x * right.x + left.y * right.y;
  2723. };
  2724. /**
  2725. * Returns a new Vector2 equal to the normalized given vector
  2726. * @param vector defines the vector to normalize
  2727. * @returns a new Vector2
  2728. */
  2729. Vector2.Normalize = function (vector) {
  2730. var newVector = vector.clone();
  2731. newVector.normalize();
  2732. return newVector;
  2733. };
  2734. /**
  2735. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2736. * @param left defines 1st vector
  2737. * @param right defines 2nd vector
  2738. * @returns a new Vector2
  2739. */
  2740. Vector2.Minimize = function (left, right) {
  2741. var x = (left.x < right.x) ? left.x : right.x;
  2742. var y = (left.y < right.y) ? left.y : right.y;
  2743. return new Vector2(x, y);
  2744. };
  2745. /**
  2746. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2747. * @param left defines 1st vector
  2748. * @param right defines 2nd vector
  2749. * @returns a new Vector2
  2750. */
  2751. Vector2.Maximize = function (left, right) {
  2752. var x = (left.x > right.x) ? left.x : right.x;
  2753. var y = (left.y > right.y) ? left.y : right.y;
  2754. return new Vector2(x, y);
  2755. };
  2756. /**
  2757. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2758. * @param vector defines the vector to transform
  2759. * @param transformation defines the matrix to apply
  2760. * @returns a new Vector2
  2761. */
  2762. Vector2.Transform = function (vector, transformation) {
  2763. var r = Vector2.Zero();
  2764. Vector2.TransformToRef(vector, transformation, r);
  2765. return r;
  2766. };
  2767. /**
  2768. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2769. * @param vector defines the vector to transform
  2770. * @param transformation defines the matrix to apply
  2771. * @param result defines the target vector
  2772. */
  2773. Vector2.TransformToRef = function (vector, transformation, result) {
  2774. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2775. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2776. result.x = x;
  2777. result.y = y;
  2778. };
  2779. /**
  2780. * Determines if a given vector is included in a triangle
  2781. * @param p defines the vector to test
  2782. * @param p0 defines 1st triangle point
  2783. * @param p1 defines 2nd triangle point
  2784. * @param p2 defines 3rd triangle point
  2785. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2786. */
  2787. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2788. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2789. var sign = a < 0 ? -1 : 1;
  2790. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2791. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2792. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2793. };
  2794. /**
  2795. * Gets the distance between the vectors "value1" and "value2"
  2796. * @param value1 defines first vector
  2797. * @param value2 defines second vector
  2798. * @returns the distance between vectors
  2799. */
  2800. Vector2.Distance = function (value1, value2) {
  2801. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2802. };
  2803. /**
  2804. * Returns the squared distance between the vectors "value1" and "value2"
  2805. * @param value1 defines first vector
  2806. * @param value2 defines second vector
  2807. * @returns the squared distance between vectors
  2808. */
  2809. Vector2.DistanceSquared = function (value1, value2) {
  2810. var x = value1.x - value2.x;
  2811. var y = value1.y - value2.y;
  2812. return (x * x) + (y * y);
  2813. };
  2814. /**
  2815. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2816. * @param value1 defines first vector
  2817. * @param value2 defines second vector
  2818. * @returns a new Vector2
  2819. */
  2820. Vector2.Center = function (value1, value2) {
  2821. var center = value1.add(value2);
  2822. center.scaleInPlace(0.5);
  2823. return center;
  2824. };
  2825. /**
  2826. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2827. * @param p defines the middle point
  2828. * @param segA defines one point of the segment
  2829. * @param segB defines the other point of the segment
  2830. * @returns the shortest distance
  2831. */
  2832. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2833. var l2 = Vector2.DistanceSquared(segA, segB);
  2834. if (l2 === 0.0) {
  2835. return Vector2.Distance(p, segA);
  2836. }
  2837. var v = segB.subtract(segA);
  2838. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2839. var proj = segA.add(v.multiplyByFloats(t, t));
  2840. return Vector2.Distance(p, proj);
  2841. };
  2842. return Vector2;
  2843. }());
  2844. BABYLON.Vector2 = Vector2;
  2845. /**
  2846. * Classed used to store (x,y,z) vector representation
  2847. * A Vector3 is the main object used in 3D geometry
  2848. * It can represent etiher the coordinates of a point the space, either a direction
  2849. * Reminder: Babylon.js uses a left handed forward facing system
  2850. */
  2851. var Vector3 = /** @class */ (function () {
  2852. /**
  2853. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2854. * @param x defines the first coordinates (on X axis)
  2855. * @param y defines the second coordinates (on Y axis)
  2856. * @param z defines the third coordinates (on Z axis)
  2857. */
  2858. function Vector3(
  2859. /**
  2860. * Defines the first coordinates (on X axis)
  2861. */
  2862. x,
  2863. /**
  2864. * Defines the second coordinates (on Y axis)
  2865. */
  2866. y,
  2867. /**
  2868. * Defines the third coordinates (on Z axis)
  2869. */
  2870. z) {
  2871. this.x = x;
  2872. this.y = y;
  2873. this.z = z;
  2874. }
  2875. /**
  2876. * Creates a string representation of the Vector3
  2877. * @returns a string with the Vector3 coordinates.
  2878. */
  2879. Vector3.prototype.toString = function () {
  2880. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2881. };
  2882. /**
  2883. * Gets the class name
  2884. * @returns the string "Vector3"
  2885. */
  2886. Vector3.prototype.getClassName = function () {
  2887. return "Vector3";
  2888. };
  2889. /**
  2890. * Creates the Vector3 hash code
  2891. * @returns a number which tends to be unique between Vector3 instances
  2892. */
  2893. Vector3.prototype.getHashCode = function () {
  2894. var hash = this.x || 0;
  2895. hash = (hash * 397) ^ (this.y || 0);
  2896. hash = (hash * 397) ^ (this.z || 0);
  2897. return hash;
  2898. };
  2899. // Operators
  2900. /**
  2901. * Creates an array containing three elements : the coordinates of the Vector3
  2902. * @returns a new array of numbers
  2903. */
  2904. Vector3.prototype.asArray = function () {
  2905. var result = [];
  2906. this.toArray(result, 0);
  2907. return result;
  2908. };
  2909. /**
  2910. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2911. * @param array defines the destination array
  2912. * @param index defines the offset in the destination array
  2913. * @returns the current Vector3
  2914. */
  2915. Vector3.prototype.toArray = function (array, index) {
  2916. if (index === void 0) { index = 0; }
  2917. array[index] = this.x;
  2918. array[index + 1] = this.y;
  2919. array[index + 2] = this.z;
  2920. return this;
  2921. };
  2922. /**
  2923. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2924. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2925. */
  2926. Vector3.prototype.toQuaternion = function () {
  2927. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2928. };
  2929. /**
  2930. * Adds the given vector to the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.addInPlace = function (otherVector) {
  2935. this.x += otherVector.x;
  2936. this.y += otherVector.y;
  2937. this.z += otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.add = function (otherVector) {
  2946. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2947. };
  2948. /**
  2949. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.addToRef = function (otherVector, result) {
  2955. result.x = this.x + otherVector.x;
  2956. result.y = this.y + otherVector.y;
  2957. result.z = this.z + otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Subtract the given vector from the current Vector3
  2962. * @param otherVector defines the second operand
  2963. * @returns the current updated Vector3
  2964. */
  2965. Vector3.prototype.subtractInPlace = function (otherVector) {
  2966. this.x -= otherVector.x;
  2967. this.y -= otherVector.y;
  2968. this.z -= otherVector.z;
  2969. return this;
  2970. };
  2971. /**
  2972. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2973. * @param otherVector defines the second operand
  2974. * @returns the resulting Vector3
  2975. */
  2976. Vector3.prototype.subtract = function (otherVector) {
  2977. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2978. };
  2979. /**
  2980. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2981. * @param otherVector defines the second operand
  2982. * @param result defines the Vector3 object where to store the result
  2983. * @returns the current Vector3
  2984. */
  2985. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2986. result.x = this.x - otherVector.x;
  2987. result.y = this.y - otherVector.y;
  2988. result.z = this.z - otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2993. * @param x defines the x coordinate of the operand
  2994. * @param y defines the y coordinate of the operand
  2995. * @param z defines the z coordinate of the operand
  2996. * @returns the resulting Vector3
  2997. */
  2998. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2999. return new Vector3(this.x - x, this.y - y, this.z - z);
  3000. };
  3001. /**
  3002. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3003. * @param x defines the x coordinate of the operand
  3004. * @param y defines the y coordinate of the operand
  3005. * @param z defines the z coordinate of the operand
  3006. * @param result defines the Vector3 object where to store the result
  3007. * @returns the current Vector3
  3008. */
  3009. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3010. result.x = this.x - x;
  3011. result.y = this.y - y;
  3012. result.z = this.z - z;
  3013. return this;
  3014. };
  3015. /**
  3016. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3017. * @returns a new Vector3
  3018. */
  3019. Vector3.prototype.negate = function () {
  3020. return new Vector3(-this.x, -this.y, -this.z);
  3021. };
  3022. /**
  3023. * Multiplies the Vector3 coordinates by the float "scale"
  3024. * @param scale defines the multiplier factor
  3025. * @returns the current updated Vector3
  3026. */
  3027. Vector3.prototype.scaleInPlace = function (scale) {
  3028. this.x *= scale;
  3029. this.y *= scale;
  3030. this.z *= scale;
  3031. return this;
  3032. };
  3033. /**
  3034. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3035. * @param scale defines the multiplier factor
  3036. * @returns a new Vector3
  3037. */
  3038. Vector3.prototype.scale = function (scale) {
  3039. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3040. };
  3041. /**
  3042. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3043. * @param scale defines the multiplier factor
  3044. * @param result defines the Vector3 object where to store the result
  3045. * @returns the current Vector3
  3046. */
  3047. Vector3.prototype.scaleToRef = function (scale, result) {
  3048. result.x = this.x * scale;
  3049. result.y = this.y * scale;
  3050. result.z = this.z * scale;
  3051. return this;
  3052. };
  3053. /**
  3054. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3055. * @param scale defines the scale factor
  3056. * @param result defines the Vector3 object where to store the result
  3057. * @returns the unmodified current Vector3
  3058. */
  3059. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3060. result.x += this.x * scale;
  3061. result.y += this.y * scale;
  3062. result.z += this.z * scale;
  3063. return this;
  3064. };
  3065. /**
  3066. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3067. * @param otherVector defines the second operand
  3068. * @returns true if both vectors are equals
  3069. */
  3070. Vector3.prototype.equals = function (otherVector) {
  3071. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3072. };
  3073. /**
  3074. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3075. * @param otherVector defines the second operand
  3076. * @param epsilon defines the minimal distance to define values as equals
  3077. * @returns true if both vectors are distant less than epsilon
  3078. */
  3079. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3080. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3081. 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);
  3082. };
  3083. /**
  3084. * Returns true if the current Vector3 coordinates equals the given floats
  3085. * @param x defines the x coordinate of the operand
  3086. * @param y defines the y coordinate of the operand
  3087. * @param z defines the z coordinate of the operand
  3088. * @returns true if both vectors are equals
  3089. */
  3090. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3091. return this.x === x && this.y === y && this.z === z;
  3092. };
  3093. /**
  3094. * Multiplies the current Vector3 coordinates by the given ones
  3095. * @param otherVector defines the second operand
  3096. * @returns the current updated Vector3
  3097. */
  3098. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3099. this.x *= otherVector.x;
  3100. this.y *= otherVector.y;
  3101. this.z *= otherVector.z;
  3102. return this;
  3103. };
  3104. /**
  3105. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3106. * @param otherVector defines the second operand
  3107. * @returns the new Vector3
  3108. */
  3109. Vector3.prototype.multiply = function (otherVector) {
  3110. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3111. };
  3112. /**
  3113. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3114. * @param otherVector defines the second operand
  3115. * @param result defines the Vector3 object where to store the result
  3116. * @returns the current Vector3
  3117. */
  3118. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3119. result.x = this.x * otherVector.x;
  3120. result.y = this.y * otherVector.y;
  3121. result.z = this.z * otherVector.z;
  3122. return this;
  3123. };
  3124. /**
  3125. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3126. * @param x defines the x coordinate of the operand
  3127. * @param y defines the y coordinate of the operand
  3128. * @param z defines the z coordinate of the operand
  3129. * @returns the new Vector3
  3130. */
  3131. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3132. return new Vector3(this.x * x, this.y * y, this.z * z);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3136. * @param otherVector defines the second operand
  3137. * @returns the new Vector3
  3138. */
  3139. Vector3.prototype.divide = function (otherVector) {
  3140. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3141. };
  3142. /**
  3143. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3144. * @param otherVector defines the second operand
  3145. * @param result defines the Vector3 object where to store the result
  3146. * @returns the current Vector3
  3147. */
  3148. Vector3.prototype.divideToRef = function (otherVector, result) {
  3149. result.x = this.x / otherVector.x;
  3150. result.y = this.y / otherVector.y;
  3151. result.z = this.z / otherVector.z;
  3152. return this;
  3153. };
  3154. /**
  3155. * Divides the current Vector3 coordinates by the given ones.
  3156. * @param otherVector defines the second operand
  3157. * @returns the current updated Vector3
  3158. */
  3159. Vector3.prototype.divideInPlace = function (otherVector) {
  3160. return this.divideToRef(otherVector, this);
  3161. };
  3162. /**
  3163. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3164. * @param other defines the second operand
  3165. * @returns the current updated Vector3
  3166. */
  3167. Vector3.prototype.minimizeInPlace = function (other) {
  3168. if (other.x < this.x)
  3169. this.x = other.x;
  3170. if (other.y < this.y)
  3171. this.y = other.y;
  3172. if (other.z < this.z)
  3173. this.z = other.z;
  3174. return this;
  3175. };
  3176. /**
  3177. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3178. * @param other defines the second operand
  3179. * @returns the current updated Vector3
  3180. */
  3181. Vector3.prototype.maximizeInPlace = function (other) {
  3182. if (other.x > this.x)
  3183. this.x = other.x;
  3184. if (other.y > this.y)
  3185. this.y = other.y;
  3186. if (other.z > this.z)
  3187. this.z = other.z;
  3188. return this;
  3189. };
  3190. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3191. /**
  3192. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3193. */
  3194. get: function () {
  3195. var absX = Math.abs(this.x);
  3196. var absY = Math.abs(this.y);
  3197. if (absX !== absY) {
  3198. return true;
  3199. }
  3200. var absZ = Math.abs(this.z);
  3201. if (absX !== absZ) {
  3202. return true;
  3203. }
  3204. if (absY !== absZ) {
  3205. return true;
  3206. }
  3207. return false;
  3208. },
  3209. enumerable: true,
  3210. configurable: true
  3211. });
  3212. // Properties
  3213. /**
  3214. * Gets the length of the Vector3
  3215. * @returns the length of the Vecto3
  3216. */
  3217. Vector3.prototype.length = function () {
  3218. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Gets the squared length of the Vector3
  3222. * @returns squared length of the Vector3
  3223. */
  3224. Vector3.prototype.lengthSquared = function () {
  3225. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3226. };
  3227. /**
  3228. * Normalize the current Vector3.
  3229. * Please note that this is an in place operation.
  3230. * @returns the current updated Vector3
  3231. */
  3232. Vector3.prototype.normalize = function () {
  3233. var len = this.length();
  3234. if (len === 0 || len === 1.0)
  3235. return this;
  3236. var num = 1.0 / len;
  3237. this.x *= num;
  3238. this.y *= num;
  3239. this.z *= num;
  3240. return this;
  3241. };
  3242. /**
  3243. * Normalize the current Vector3 to a new vector
  3244. * @returns the new Vector3
  3245. */
  3246. Vector3.prototype.normalizeToNew = function () {
  3247. var normalized = new Vector3(0, 0, 0);
  3248. this.normalizeToRef(normalized);
  3249. return normalized;
  3250. };
  3251. /**
  3252. * Normalize the current Vector3 to the reference
  3253. * @param reference define the Vector3 to update
  3254. * @returns the updated Vector3
  3255. */
  3256. Vector3.prototype.normalizeToRef = function (reference) {
  3257. var len = this.length();
  3258. if (len === 0 || len === 1.0) {
  3259. reference.set(this.x, this.y, this.z);
  3260. return reference;
  3261. }
  3262. var scale = 1.0 / len;
  3263. this.scaleToRef(scale, reference);
  3264. return reference;
  3265. };
  3266. /**
  3267. * Creates a new Vector3 copied from the current Vector3
  3268. * @returns the new Vector3
  3269. */
  3270. Vector3.prototype.clone = function () {
  3271. return new Vector3(this.x, this.y, this.z);
  3272. };
  3273. /**
  3274. * Copies the given vector coordinates to the current Vector3 ones
  3275. * @param source defines the source Vector3
  3276. * @returns the current updated Vector3
  3277. */
  3278. Vector3.prototype.copyFrom = function (source) {
  3279. this.x = source.x;
  3280. this.y = source.y;
  3281. this.z = source.z;
  3282. return this;
  3283. };
  3284. /**
  3285. * Copies the given floats to the current Vector3 coordinates
  3286. * @param x defines the x coordinate of the operand
  3287. * @param y defines the y coordinate of the operand
  3288. * @param z defines the z coordinate of the operand
  3289. * @returns the current updated Vector3
  3290. */
  3291. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3292. this.x = x;
  3293. this.y = y;
  3294. this.z = z;
  3295. return this;
  3296. };
  3297. /**
  3298. * Copies the given floats to the current Vector3 coordinates
  3299. * @param x defines the x coordinate of the operand
  3300. * @param y defines the y coordinate of the operand
  3301. * @param z defines the z coordinate of the operand
  3302. * @returns the current updated Vector3
  3303. */
  3304. Vector3.prototype.set = function (x, y, z) {
  3305. return this.copyFromFloats(x, y, z);
  3306. };
  3307. // Statics
  3308. /**
  3309. * Get the clip factor between two vectors
  3310. * @param vector0 defines the first operand
  3311. * @param vector1 defines the second operand
  3312. * @param axis defines the axis to use
  3313. * @param size defines the size along the axis
  3314. * @returns the clip factor
  3315. */
  3316. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3317. var d0 = Vector3.Dot(vector0, axis) - size;
  3318. var d1 = Vector3.Dot(vector1, axis) - size;
  3319. var s = d0 / (d0 - d1);
  3320. return s;
  3321. };
  3322. /**
  3323. * Get angle between two vectors
  3324. * @param vector0 angle between vector0 and vector1
  3325. * @param vector1 angle between vector0 and vector1
  3326. * @param normal direction of the normal
  3327. * @return the angle between vector0 and vector1
  3328. */
  3329. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3330. var v0 = vector0.clone().normalize();
  3331. var v1 = vector1.clone().normalize();
  3332. var dot = Vector3.Dot(v0, v1);
  3333. var n = Vector3.Cross(v0, v1);
  3334. if (Vector3.Dot(n, normal) > 0) {
  3335. return Math.acos(dot);
  3336. }
  3337. return -Math.acos(dot);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set from the index "offset" of the given array
  3341. * @param array defines the source array
  3342. * @param offset defines the offset in the source array
  3343. * @returns the new Vector3
  3344. */
  3345. Vector3.FromArray = function (array, offset) {
  3346. if (!offset) {
  3347. offset = 0;
  3348. }
  3349. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3350. };
  3351. /**
  3352. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3353. * This function is deprecated. Use FromArray instead
  3354. * @param array defines the source array
  3355. * @param offset defines the offset in the source array
  3356. * @returns the new Vector3
  3357. */
  3358. Vector3.FromFloatArray = function (array, offset) {
  3359. return Vector3.FromArray(array, offset);
  3360. };
  3361. /**
  3362. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3363. * @param array defines the source array
  3364. * @param offset defines the offset in the source array
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.FromArrayToRef = function (array, offset, result) {
  3368. result.x = array[offset];
  3369. result.y = array[offset + 1];
  3370. result.z = array[offset + 2];
  3371. };
  3372. /**
  3373. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3374. * This function is deprecated. Use FromArrayToRef instead.
  3375. * @param array defines the source array
  3376. * @param offset defines the offset in the source array
  3377. * @param result defines the Vector3 where to store the result
  3378. */
  3379. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3380. return Vector3.FromArrayToRef(array, offset, result);
  3381. };
  3382. /**
  3383. * Sets the given vector "result" with the given floats.
  3384. * @param x defines the x coordinate of the source
  3385. * @param y defines the y coordinate of the source
  3386. * @param z defines the z coordinate of the source
  3387. * @param result defines the Vector3 where to store the result
  3388. */
  3389. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3390. result.x = x;
  3391. result.y = y;
  3392. result.z = z;
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3396. * @returns a new empty Vector3
  3397. */
  3398. Vector3.Zero = function () {
  3399. return new Vector3(0.0, 0.0, 0.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3403. * @returns a new unit Vector3
  3404. */
  3405. Vector3.One = function () {
  3406. return new Vector3(1.0, 1.0, 1.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3410. * @returns a new up Vector3
  3411. */
  3412. Vector3.Up = function () {
  3413. return new Vector3(0.0, 1.0, 0.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3417. * @returns a new forward Vector3
  3418. */
  3419. Vector3.Forward = function () {
  3420. return new Vector3(0.0, 0.0, 1.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3424. * @returns a new right Vector3
  3425. */
  3426. Vector3.Right = function () {
  3427. return new Vector3(1.0, 0.0, 0.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3431. * @returns a new left Vector3
  3432. */
  3433. Vector3.Left = function () {
  3434. return new Vector3(-1.0, 0.0, 0.0);
  3435. };
  3436. /**
  3437. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3438. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3439. * @param vector defines the Vector3 to transform
  3440. * @param transformation defines the transformation matrix
  3441. * @returns the transformed Vector3
  3442. */
  3443. Vector3.TransformCoordinates = function (vector, transformation) {
  3444. var result = Vector3.Zero();
  3445. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @param result defines the Vector3 where to store the result
  3454. */
  3455. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3456. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3457. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3458. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3459. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3460. result.x = x / w;
  3461. result.y = y / w;
  3462. result.z = z / w;
  3463. };
  3464. /**
  3465. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3466. * This method computes tranformed coordinates only, not transformed direction vectors
  3467. * @param x define the x coordinate of the source vector
  3468. * @param y define the y coordinate of the source vector
  3469. * @param z define the z coordinate of the source vector
  3470. * @param transformation defines the transformation matrix
  3471. * @param result defines the Vector3 where to store the result
  3472. */
  3473. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3474. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3475. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3476. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3477. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3478. result.x = rx / rw;
  3479. result.y = ry / rw;
  3480. result.z = rz / rw;
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3484. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3485. * @param vector defines the Vector3 to transform
  3486. * @param transformation defines the transformation matrix
  3487. * @returns the new Vector3
  3488. */
  3489. Vector3.TransformNormal = function (vector, transformation) {
  3490. var result = Vector3.Zero();
  3491. Vector3.TransformNormalToRef(vector, transformation, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @param result defines the Vector3 where to store the result
  3500. */
  3501. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3502. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3503. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3504. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3505. result.x = x;
  3506. result.y = y;
  3507. result.z = z;
  3508. };
  3509. /**
  3510. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3511. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3512. * @param x define the x coordinate of the source vector
  3513. * @param y define the y coordinate of the source vector
  3514. * @param z define the z coordinate of the source vector
  3515. * @param transformation defines the transformation matrix
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3519. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3520. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3521. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3522. };
  3523. /**
  3524. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3525. * @param value1 defines the first control point
  3526. * @param value2 defines the second control point
  3527. * @param value3 defines the third control point
  3528. * @param value4 defines the fourth control point
  3529. * @param amount defines the amount on the spline to use
  3530. * @returns the new Vector3
  3531. */
  3532. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3533. var squared = amount * amount;
  3534. var cubed = amount * squared;
  3535. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3536. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3537. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3538. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3539. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3540. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3541. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3542. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3543. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3544. return new Vector3(x, y, z);
  3545. };
  3546. /**
  3547. * 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"
  3548. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3549. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3550. * @param value defines the current value
  3551. * @param min defines the lower range value
  3552. * @param max defines the upper range value
  3553. * @returns the new Vector3
  3554. */
  3555. Vector3.Clamp = function (value, min, max) {
  3556. var x = value.x;
  3557. x = (x > max.x) ? max.x : x;
  3558. x = (x < min.x) ? min.x : x;
  3559. var y = value.y;
  3560. y = (y > max.y) ? max.y : y;
  3561. y = (y < min.y) ? min.y : y;
  3562. var z = value.z;
  3563. z = (z > max.z) ? max.z : z;
  3564. z = (z < min.z) ? min.z : z;
  3565. return new Vector3(x, y, z);
  3566. };
  3567. /**
  3568. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3569. * @param value1 defines the first control point
  3570. * @param tangent1 defines the first tangent vector
  3571. * @param value2 defines the second control point
  3572. * @param tangent2 defines the second tangent vector
  3573. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3577. var squared = amount * amount;
  3578. var cubed = amount * squared;
  3579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3581. var part3 = (cubed - (2.0 * squared)) + amount;
  3582. var part4 = cubed - squared;
  3583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3585. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3586. return new Vector3(x, y, z);
  3587. };
  3588. /**
  3589. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3590. * @param start defines the start value
  3591. * @param end defines the end value
  3592. * @param amount max defines amount between both (between 0 and 1)
  3593. * @returns the new Vector3
  3594. */
  3595. Vector3.Lerp = function (start, end, amount) {
  3596. var result = new Vector3(0, 0, 0);
  3597. Vector3.LerpToRef(start, end, amount, result);
  3598. return result;
  3599. };
  3600. /**
  3601. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @param result defines the Vector3 where to store the result
  3606. */
  3607. Vector3.LerpToRef = function (start, end, amount, result) {
  3608. result.x = start.x + ((end.x - start.x) * amount);
  3609. result.y = start.y + ((end.y - start.y) * amount);
  3610. result.z = start.z + ((end.z - start.z) * amount);
  3611. };
  3612. /**
  3613. * Returns the dot product (float) between the vectors "left" and "right"
  3614. * @param left defines the left operand
  3615. * @param right defines the right operand
  3616. * @returns the dot product
  3617. */
  3618. Vector3.Dot = function (left, right) {
  3619. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3623. * The cross product is then orthogonal to both "left" and "right"
  3624. * @param left defines the left operand
  3625. * @param right defines the right operand
  3626. * @returns the cross product
  3627. */
  3628. Vector3.Cross = function (left, right) {
  3629. var result = Vector3.Zero();
  3630. Vector3.CrossToRef(left, right, result);
  3631. return result;
  3632. };
  3633. /**
  3634. * Sets the given vector "result" with the cross product of "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @param result defines the Vector3 where to store the result
  3639. */
  3640. Vector3.CrossToRef = function (left, right, result) {
  3641. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3642. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3643. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3644. result.copyFrom(MathTmp.Vector3[0]);
  3645. };
  3646. /**
  3647. * Returns a new Vector3 as the normalization of the given vector
  3648. * @param vector defines the Vector3 to normalize
  3649. * @returns the new Vector3
  3650. */
  3651. Vector3.Normalize = function (vector) {
  3652. var result = Vector3.Zero();
  3653. Vector3.NormalizeToRef(vector, result);
  3654. return result;
  3655. };
  3656. /**
  3657. * Sets the given vector "result" with the normalization of the given first vector
  3658. * @param vector defines the Vector3 to normalize
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.NormalizeToRef = function (vector, result) {
  3662. result.copyFrom(vector);
  3663. result.normalize();
  3664. };
  3665. /**
  3666. * Project a Vector3 onto screen space
  3667. * @param vector defines the Vector3 to project
  3668. * @param world defines the world matrix to use
  3669. * @param transform defines the transform (view x projection) matrix to use
  3670. * @param viewport defines the screen viewport to use
  3671. * @returns the new Vector3
  3672. */
  3673. Vector3.Project = function (vector, world, transform, viewport) {
  3674. var cw = viewport.width;
  3675. var ch = viewport.height;
  3676. var cx = viewport.x;
  3677. var cy = viewport.y;
  3678. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3679. 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);
  3680. var matrix = MathTmp.Matrix[0];
  3681. world.multiplyToRef(transform, matrix);
  3682. matrix.multiplyToRef(viewportMatrix, matrix);
  3683. return Vector3.TransformCoordinates(vector, matrix);
  3684. };
  3685. /**
  3686. * Unproject from screen space to object space
  3687. * @param source defines the screen space Vector3 to use
  3688. * @param viewportWidth defines the current width of the viewport
  3689. * @param viewportHeight defines the current height of the viewport
  3690. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3691. * @param transform defines the transform (view x projection) matrix to use
  3692. * @returns the new Vector3
  3693. */
  3694. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3695. var matrix = MathTmp.Matrix[0];
  3696. world.multiplyToRef(transform, matrix);
  3697. matrix.invert();
  3698. source.x = source.x / viewportWidth * 2 - 1;
  3699. source.y = -(source.y / viewportHeight * 2 - 1);
  3700. var vector = Vector3.TransformCoordinates(source, matrix);
  3701. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3702. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3703. vector = vector.scale(1.0 / num);
  3704. }
  3705. return vector;
  3706. };
  3707. /**
  3708. * Unproject from screen space to object space
  3709. * @param source defines the screen space Vector3 to use
  3710. * @param viewportWidth defines the current width of the viewport
  3711. * @param viewportHeight defines the current height of the viewport
  3712. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3713. * @param view defines the view matrix to use
  3714. * @param projection defines the projection matrix to use
  3715. * @returns the new Vector3
  3716. */
  3717. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3718. var result = Vector3.Zero();
  3719. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3720. return result;
  3721. };
  3722. /**
  3723. * Unproject from screen space to object space
  3724. * @param source defines the screen space Vector3 to use
  3725. * @param viewportWidth defines the current width of the viewport
  3726. * @param viewportHeight defines the current height of the viewport
  3727. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3728. * @param view defines the view matrix to use
  3729. * @param projection defines the projection matrix to use
  3730. * @param result defines the Vector3 where to store the result
  3731. */
  3732. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3733. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3734. };
  3735. /**
  3736. * Unproject from screen space to object space
  3737. * @param sourceX defines the screen space x coordinate to use
  3738. * @param sourceY defines the screen space y coordinate to use
  3739. * @param sourceZ defines the screen space z coordinate to use
  3740. * @param viewportWidth defines the current width of the viewport
  3741. * @param viewportHeight defines the current height of the viewport
  3742. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3743. * @param view defines the view matrix to use
  3744. * @param projection defines the projection matrix to use
  3745. * @param result defines the Vector3 where to store the result
  3746. */
  3747. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3748. var matrix = MathTmp.Matrix[0];
  3749. world.multiplyToRef(view, matrix);
  3750. matrix.multiplyToRef(projection, matrix);
  3751. matrix.invert();
  3752. var screenSource = MathTmp.Vector3[0];
  3753. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3754. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3755. screenSource.z = 2 * sourceZ - 1.0;
  3756. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3757. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3758. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3759. result.scaleInPlace(1.0 / num);
  3760. }
  3761. };
  3762. /**
  3763. * Gets the minimal coordinate values between two Vector3
  3764. * @param left defines the first operand
  3765. * @param right defines the second operand
  3766. * @returns the new Vector3
  3767. */
  3768. Vector3.Minimize = function (left, right) {
  3769. var min = left.clone();
  3770. min.minimizeInPlace(right);
  3771. return min;
  3772. };
  3773. /**
  3774. * Gets the maximal coordinate values between two Vector3
  3775. * @param left defines the first operand
  3776. * @param right defines the second operand
  3777. * @returns the new Vector3
  3778. */
  3779. Vector3.Maximize = function (left, right) {
  3780. var max = left.clone();
  3781. max.maximizeInPlace(right);
  3782. return max;
  3783. };
  3784. /**
  3785. * Returns the distance between the vectors "value1" and "value2"
  3786. * @param value1 defines the first operand
  3787. * @param value2 defines the second operand
  3788. * @returns the distance
  3789. */
  3790. Vector3.Distance = function (value1, value2) {
  3791. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3792. };
  3793. /**
  3794. * Returns the squared distance between the vectors "value1" and "value2"
  3795. * @param value1 defines the first operand
  3796. * @param value2 defines the second operand
  3797. * @returns the squared distance
  3798. */
  3799. Vector3.DistanceSquared = function (value1, value2) {
  3800. var x = value1.x - value2.x;
  3801. var y = value1.y - value2.y;
  3802. var z = value1.z - value2.z;
  3803. return (x * x) + (y * y) + (z * z);
  3804. };
  3805. /**
  3806. * Returns a new Vector3 located at the center between "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the new Vector3
  3810. */
  3811. Vector3.Center = function (value1, value2) {
  3812. var center = value1.add(value2);
  3813. center.scaleInPlace(0.5);
  3814. return center;
  3815. };
  3816. /**
  3817. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3818. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3819. * to something in order to rotate it from its local system to the given target system
  3820. * Note: axis1, axis2 and axis3 are normalized during this operation
  3821. * @param axis1 defines the first axis
  3822. * @param axis2 defines the second axis
  3823. * @param axis3 defines the third axis
  3824. * @returns a new Vector3
  3825. */
  3826. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3827. var rotation = Vector3.Zero();
  3828. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3829. return rotation;
  3830. };
  3831. /**
  3832. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @param ref defines the Vector3 where to store the result
  3837. */
  3838. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3839. var quat = MathTmp.Quaternion[0];
  3840. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3841. quat.toEulerAnglesToRef(ref);
  3842. };
  3843. return Vector3;
  3844. }());
  3845. BABYLON.Vector3 = Vector3;
  3846. //Vector4 class created for EulerAngle class conversion to Quaternion
  3847. var Vector4 = /** @class */ (function () {
  3848. /**
  3849. * Creates a Vector4 object from the given floats.
  3850. */
  3851. function Vector4(x, y, z, w) {
  3852. this.x = x;
  3853. this.y = y;
  3854. this.z = z;
  3855. this.w = w;
  3856. }
  3857. /**
  3858. * Returns the string with the Vector4 coordinates.
  3859. */
  3860. Vector4.prototype.toString = function () {
  3861. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3862. };
  3863. /**
  3864. * Returns the string "Vector4".
  3865. */
  3866. Vector4.prototype.getClassName = function () {
  3867. return "Vector4";
  3868. };
  3869. /**
  3870. * Returns the Vector4 hash code.
  3871. */
  3872. Vector4.prototype.getHashCode = function () {
  3873. var hash = this.x || 0;
  3874. hash = (hash * 397) ^ (this.y || 0);
  3875. hash = (hash * 397) ^ (this.z || 0);
  3876. hash = (hash * 397) ^ (this.w || 0);
  3877. return hash;
  3878. };
  3879. // Operators
  3880. /**
  3881. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3882. */
  3883. Vector4.prototype.asArray = function () {
  3884. var result = new Array();
  3885. this.toArray(result, 0);
  3886. return result;
  3887. };
  3888. /**
  3889. * Populates the given array from the given index with the Vector4 coordinates.
  3890. * Returns the Vector4.
  3891. */
  3892. Vector4.prototype.toArray = function (array, index) {
  3893. if (index === undefined) {
  3894. index = 0;
  3895. }
  3896. array[index] = this.x;
  3897. array[index + 1] = this.y;
  3898. array[index + 2] = this.z;
  3899. array[index + 3] = this.w;
  3900. return this;
  3901. };
  3902. /**
  3903. * Adds the given vector to the current Vector4.
  3904. * Returns the updated Vector4.
  3905. */
  3906. Vector4.prototype.addInPlace = function (otherVector) {
  3907. this.x += otherVector.x;
  3908. this.y += otherVector.y;
  3909. this.z += otherVector.z;
  3910. this.w += otherVector.w;
  3911. return this;
  3912. };
  3913. /**
  3914. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3915. */
  3916. Vector4.prototype.add = function (otherVector) {
  3917. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3918. };
  3919. /**
  3920. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3921. * Returns the current Vector4.
  3922. */
  3923. Vector4.prototype.addToRef = function (otherVector, result) {
  3924. result.x = this.x + otherVector.x;
  3925. result.y = this.y + otherVector.y;
  3926. result.z = this.z + otherVector.z;
  3927. result.w = this.w + otherVector.w;
  3928. return this;
  3929. };
  3930. /**
  3931. * Subtract in place the given vector from the current Vector4.
  3932. * Returns the updated Vector4.
  3933. */
  3934. Vector4.prototype.subtractInPlace = function (otherVector) {
  3935. this.x -= otherVector.x;
  3936. this.y -= otherVector.y;
  3937. this.z -= otherVector.z;
  3938. this.w -= otherVector.w;
  3939. return this;
  3940. };
  3941. /**
  3942. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3943. */
  3944. Vector4.prototype.subtract = function (otherVector) {
  3945. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3946. };
  3947. /**
  3948. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3949. * Returns the current Vector4.
  3950. */
  3951. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3952. result.x = this.x - otherVector.x;
  3953. result.y = this.y - otherVector.y;
  3954. result.z = this.z - otherVector.z;
  3955. result.w = this.w - otherVector.w;
  3956. return this;
  3957. };
  3958. /**
  3959. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3960. */
  3961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3963. };
  3964. /**
  3965. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3966. * Returns the current Vector4.
  3967. */
  3968. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3969. result.x = this.x - x;
  3970. result.y = this.y - y;
  3971. result.z = this.z - z;
  3972. result.w = this.w - w;
  3973. return this;
  3974. };
  3975. /**
  3976. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3977. */
  3978. Vector4.prototype.negate = function () {
  3979. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3980. };
  3981. /**
  3982. * Multiplies the current Vector4 coordinates by scale (float).
  3983. * Returns the updated Vector4.
  3984. */
  3985. Vector4.prototype.scaleInPlace = function (scale) {
  3986. this.x *= scale;
  3987. this.y *= scale;
  3988. this.z *= scale;
  3989. this.w *= scale;
  3990. return this;
  3991. };
  3992. /**
  3993. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3994. */
  3995. Vector4.prototype.scale = function (scale) {
  3996. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3997. };
  3998. /**
  3999. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4000. * Returns the current Vector4.
  4001. */
  4002. Vector4.prototype.scaleToRef = function (scale, result) {
  4003. result.x = this.x * scale;
  4004. result.y = this.y * scale;
  4005. result.z = this.z * scale;
  4006. result.w = this.w * scale;
  4007. return this;
  4008. };
  4009. /**
  4010. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4011. * @param scale defines the scale factor
  4012. * @param result defines the Vector4 object where to store the result
  4013. * @returns the unmodified current Vector4
  4014. */
  4015. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4016. result.x += this.x * scale;
  4017. result.y += this.y * scale;
  4018. result.z += this.z * scale;
  4019. result.w += this.w * scale;
  4020. return this;
  4021. };
  4022. /**
  4023. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4024. */
  4025. Vector4.prototype.equals = function (otherVector) {
  4026. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4027. };
  4028. /**
  4029. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4030. */
  4031. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4032. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4033. return otherVector
  4034. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4035. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4036. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4037. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4038. };
  4039. /**
  4040. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4041. */
  4042. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4043. return this.x === x && this.y === y && this.z === z && this.w === w;
  4044. };
  4045. /**
  4046. * Multiplies in place the current Vector4 by the given one.
  4047. * Returns the updated Vector4.
  4048. */
  4049. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4050. this.x *= otherVector.x;
  4051. this.y *= otherVector.y;
  4052. this.z *= otherVector.z;
  4053. this.w *= otherVector.w;
  4054. return this;
  4055. };
  4056. /**
  4057. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4058. */
  4059. Vector4.prototype.multiply = function (otherVector) {
  4060. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4061. };
  4062. /**
  4063. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4064. * Returns the current Vector4.
  4065. */
  4066. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4067. result.x = this.x * otherVector.x;
  4068. result.y = this.y * otherVector.y;
  4069. result.z = this.z * otherVector.z;
  4070. result.w = this.w * otherVector.w;
  4071. return this;
  4072. };
  4073. /**
  4074. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4075. */
  4076. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4077. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4078. };
  4079. /**
  4080. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4081. */
  4082. Vector4.prototype.divide = function (otherVector) {
  4083. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4084. };
  4085. /**
  4086. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4087. * Returns the current Vector4.
  4088. */
  4089. Vector4.prototype.divideToRef = function (otherVector, result) {
  4090. result.x = this.x / otherVector.x;
  4091. result.y = this.y / otherVector.y;
  4092. result.z = this.z / otherVector.z;
  4093. result.w = this.w / otherVector.w;
  4094. return this;
  4095. };
  4096. /**
  4097. * Divides the current Vector3 coordinates by the given ones.
  4098. * @returns the updated Vector3.
  4099. */
  4100. Vector4.prototype.divideInPlace = function (otherVector) {
  4101. return this.divideToRef(otherVector, this);
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.minimizeInPlace = function (other) {
  4109. if (other.x < this.x)
  4110. this.x = other.x;
  4111. if (other.y < this.y)
  4112. this.y = other.y;
  4113. if (other.z < this.z)
  4114. this.z = other.z;
  4115. if (other.w < this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4121. * @param other defines the second operand
  4122. * @returns the current updated Vector4
  4123. */
  4124. Vector4.prototype.maximizeInPlace = function (other) {
  4125. if (other.x > this.x)
  4126. this.x = other.x;
  4127. if (other.y > this.y)
  4128. this.y = other.y;
  4129. if (other.z > this.z)
  4130. this.z = other.z;
  4131. if (other.w > this.w)
  4132. this.w = other.w;
  4133. return this;
  4134. };
  4135. // Properties
  4136. /**
  4137. * Returns the Vector4 length (float).
  4138. */
  4139. Vector4.prototype.length = function () {
  4140. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4141. };
  4142. /**
  4143. * Returns the Vector4 squared length (float).
  4144. */
  4145. Vector4.prototype.lengthSquared = function () {
  4146. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4147. };
  4148. // Methods
  4149. /**
  4150. * Normalizes in place the Vector4.
  4151. * Returns the updated Vector4.
  4152. */
  4153. Vector4.prototype.normalize = function () {
  4154. var len = this.length();
  4155. if (len === 0)
  4156. return this;
  4157. var num = 1.0 / len;
  4158. this.x *= num;
  4159. this.y *= num;
  4160. this.z *= num;
  4161. this.w *= num;
  4162. return this;
  4163. };
  4164. /**
  4165. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4166. */
  4167. Vector4.prototype.toVector3 = function () {
  4168. return new Vector3(this.x, this.y, this.z);
  4169. };
  4170. /**
  4171. * Returns a new Vector4 copied from the current one.
  4172. */
  4173. Vector4.prototype.clone = function () {
  4174. return new Vector4(this.x, this.y, this.z, this.w);
  4175. };
  4176. /**
  4177. * Updates the current Vector4 with the given one coordinates.
  4178. * Returns the updated Vector4.
  4179. */
  4180. Vector4.prototype.copyFrom = function (source) {
  4181. this.x = source.x;
  4182. this.y = source.y;
  4183. this.z = source.z;
  4184. this.w = source.w;
  4185. return this;
  4186. };
  4187. /**
  4188. * Updates the current Vector4 coordinates with the given floats.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4192. this.x = x;
  4193. this.y = y;
  4194. this.z = z;
  4195. this.w = w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.set = function (x, y, z, w) {
  4203. return this.copyFromFloats(x, y, z, w);
  4204. };
  4205. // Statics
  4206. /**
  4207. * Returns a new Vector4 set from the starting index of the given array.
  4208. */
  4209. Vector4.FromArray = function (array, offset) {
  4210. if (!offset) {
  4211. offset = 0;
  4212. }
  4213. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4214. };
  4215. /**
  4216. * Updates the given vector "result" from the starting index of the given array.
  4217. */
  4218. Vector4.FromArrayToRef = function (array, offset, result) {
  4219. result.x = array[offset];
  4220. result.y = array[offset + 1];
  4221. result.z = array[offset + 2];
  4222. result.w = array[offset + 3];
  4223. };
  4224. /**
  4225. * Updates the given vector "result" from the starting index of the given Float32Array.
  4226. */
  4227. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4228. Vector4.FromArrayToRef(array, offset, result);
  4229. };
  4230. /**
  4231. * Updates the given vector "result" coordinates from the given floats.
  4232. */
  4233. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4234. result.x = x;
  4235. result.y = y;
  4236. result.z = z;
  4237. result.w = w;
  4238. };
  4239. /**
  4240. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4241. */
  4242. Vector4.Zero = function () {
  4243. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4244. };
  4245. /**
  4246. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4247. */
  4248. Vector4.One = function () {
  4249. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4250. };
  4251. /**
  4252. * Returns a new normalized Vector4 from the given one.
  4253. */
  4254. Vector4.Normalize = function (vector) {
  4255. var result = Vector4.Zero();
  4256. Vector4.NormalizeToRef(vector, result);
  4257. return result;
  4258. };
  4259. /**
  4260. * Updates the given vector "result" from the normalization of the given one.
  4261. */
  4262. Vector4.NormalizeToRef = function (vector, result) {
  4263. result.copyFrom(vector);
  4264. result.normalize();
  4265. };
  4266. Vector4.Minimize = function (left, right) {
  4267. var min = left.clone();
  4268. min.minimizeInPlace(right);
  4269. return min;
  4270. };
  4271. Vector4.Maximize = function (left, right) {
  4272. var max = left.clone();
  4273. max.maximizeInPlace(right);
  4274. return max;
  4275. };
  4276. /**
  4277. * Returns the distance (float) between the vectors "value1" and "value2".
  4278. */
  4279. Vector4.Distance = function (value1, value2) {
  4280. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4281. };
  4282. /**
  4283. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4284. */
  4285. Vector4.DistanceSquared = function (value1, value2) {
  4286. var x = value1.x - value2.x;
  4287. var y = value1.y - value2.y;
  4288. var z = value1.z - value2.z;
  4289. var w = value1.w - value2.w;
  4290. return (x * x) + (y * y) + (z * z) + (w * w);
  4291. };
  4292. /**
  4293. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4294. */
  4295. Vector4.Center = function (value1, value2) {
  4296. var center = value1.add(value2);
  4297. center.scaleInPlace(0.5);
  4298. return center;
  4299. };
  4300. /**
  4301. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4302. * This methods computes transformed normalized direction vectors only.
  4303. */
  4304. Vector4.TransformNormal = function (vector, transformation) {
  4305. var result = Vector4.Zero();
  4306. Vector4.TransformNormalToRef(vector, transformation, result);
  4307. return result;
  4308. };
  4309. /**
  4310. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4311. * This methods computes transformed normalized direction vectors only.
  4312. */
  4313. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4314. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4315. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4316. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4317. result.x = x;
  4318. result.y = y;
  4319. result.z = z;
  4320. result.w = vector.w;
  4321. };
  4322. /**
  4323. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4324. * This methods computes transformed normalized direction vectors only.
  4325. */
  4326. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4327. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4328. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4329. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4330. result.w = w;
  4331. };
  4332. return Vector4;
  4333. }());
  4334. BABYLON.Vector4 = Vector4;
  4335. var Size = /** @class */ (function () {
  4336. /**
  4337. * Creates a Size object from the given width and height (floats).
  4338. */
  4339. function Size(width, height) {
  4340. this.width = width;
  4341. this.height = height;
  4342. }
  4343. // Returns a string with the Size width and height.
  4344. Size.prototype.toString = function () {
  4345. return "{W: " + this.width + ", H: " + this.height + "}";
  4346. };
  4347. /**
  4348. * Returns the string "Size"
  4349. */
  4350. Size.prototype.getClassName = function () {
  4351. return "Size";
  4352. };
  4353. /**
  4354. * Returns the Size hash code.
  4355. */
  4356. Size.prototype.getHashCode = function () {
  4357. var hash = this.width || 0;
  4358. hash = (hash * 397) ^ (this.height || 0);
  4359. return hash;
  4360. };
  4361. /**
  4362. * Updates the current size from the given one.
  4363. * Returns the updated Size.
  4364. */
  4365. Size.prototype.copyFrom = function (src) {
  4366. this.width = src.width;
  4367. this.height = src.height;
  4368. };
  4369. /**
  4370. * Updates in place the current Size from the given floats.
  4371. * Returns the updated Size.
  4372. */
  4373. Size.prototype.copyFromFloats = function (width, height) {
  4374. this.width = width;
  4375. this.height = height;
  4376. return this;
  4377. };
  4378. /**
  4379. * Updates in place the current Size from the given floats.
  4380. * Returns the updated Size.
  4381. */
  4382. Size.prototype.set = function (width, height) {
  4383. return this.copyFromFloats(width, height);
  4384. };
  4385. /**
  4386. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4387. */
  4388. Size.prototype.multiplyByFloats = function (w, h) {
  4389. return new Size(this.width * w, this.height * h);
  4390. };
  4391. /**
  4392. * Returns a new Size copied from the given one.
  4393. */
  4394. Size.prototype.clone = function () {
  4395. return new Size(this.width, this.height);
  4396. };
  4397. /**
  4398. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4399. */
  4400. Size.prototype.equals = function (other) {
  4401. if (!other) {
  4402. return false;
  4403. }
  4404. return (this.width === other.width) && (this.height === other.height);
  4405. };
  4406. Object.defineProperty(Size.prototype, "surface", {
  4407. /**
  4408. * Returns the surface of the Size : width * height (float).
  4409. */
  4410. get: function () {
  4411. return this.width * this.height;
  4412. },
  4413. enumerable: true,
  4414. configurable: true
  4415. });
  4416. /**
  4417. * Returns a new Size set to (0.0, 0.0)
  4418. */
  4419. Size.Zero = function () {
  4420. return new Size(0.0, 0.0);
  4421. };
  4422. /**
  4423. * Returns a new Size set as the addition result of the current Size and the given one.
  4424. */
  4425. Size.prototype.add = function (otherSize) {
  4426. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4427. return r;
  4428. };
  4429. /**
  4430. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4431. */
  4432. Size.prototype.subtract = function (otherSize) {
  4433. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4434. return r;
  4435. };
  4436. /**
  4437. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4438. */
  4439. Size.Lerp = function (start, end, amount) {
  4440. var w = start.width + ((end.width - start.width) * amount);
  4441. var h = start.height + ((end.height - start.height) * amount);
  4442. return new Size(w, h);
  4443. };
  4444. return Size;
  4445. }());
  4446. BABYLON.Size = Size;
  4447. /**
  4448. * Class used to store quaternion data
  4449. * @see https://en.wikipedia.org/wiki/Quaternion
  4450. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4451. */
  4452. var Quaternion = /** @class */ (function () {
  4453. /**
  4454. * Creates a new Quaternion from the given floats
  4455. * @param x defines the first component (0 by default)
  4456. * @param y defines the second component (0 by default)
  4457. * @param z defines the third component (0 by default)
  4458. * @param w defines the fourth component (1.0 by default)
  4459. */
  4460. function Quaternion(
  4461. /** defines the first component (0 by default) */
  4462. x,
  4463. /** defines the second component (0 by default) */
  4464. y,
  4465. /** defines the third component (0 by default) */
  4466. z,
  4467. /** defines the fourth component (1.0 by default) */
  4468. w) {
  4469. if (x === void 0) { x = 0.0; }
  4470. if (y === void 0) { y = 0.0; }
  4471. if (z === void 0) { z = 0.0; }
  4472. if (w === void 0) { w = 1.0; }
  4473. this.x = x;
  4474. this.y = y;
  4475. this.z = z;
  4476. this.w = w;
  4477. }
  4478. /**
  4479. * Gets a string representation for the current quaternion
  4480. * @returns a string with the Quaternion coordinates
  4481. */
  4482. Quaternion.prototype.toString = function () {
  4483. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4484. };
  4485. /**
  4486. * Gets the class name of the quaternion
  4487. * @returns the string "Quaternion"
  4488. */
  4489. Quaternion.prototype.getClassName = function () {
  4490. return "Quaternion";
  4491. };
  4492. /**
  4493. * Gets a hash code for this quaternion
  4494. * @returns the quaternion hash code
  4495. */
  4496. Quaternion.prototype.getHashCode = function () {
  4497. var hash = this.x || 0;
  4498. hash = (hash * 397) ^ (this.y || 0);
  4499. hash = (hash * 397) ^ (this.z || 0);
  4500. hash = (hash * 397) ^ (this.w || 0);
  4501. return hash;
  4502. };
  4503. /**
  4504. * Copy the quaternion to an array
  4505. * @returns a new array populated with 4 elements from the quaternion coordinates
  4506. */
  4507. Quaternion.prototype.asArray = function () {
  4508. return [this.x, this.y, this.z, this.w];
  4509. };
  4510. /**
  4511. * Check if two quaternions are equals
  4512. * @param otherQuaternion defines the second operand
  4513. * @return true if the current quaternion and the given one coordinates are strictly equals
  4514. */
  4515. Quaternion.prototype.equals = function (otherQuaternion) {
  4516. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4517. };
  4518. /**
  4519. * Clone the current quaternion
  4520. * @returns a new quaternion copied from the current one
  4521. */
  4522. Quaternion.prototype.clone = function () {
  4523. return new Quaternion(this.x, this.y, this.z, this.w);
  4524. };
  4525. /**
  4526. * Copy a quaternion to the current one
  4527. * @param other defines the other quaternion
  4528. * @returns the updated current quaternion
  4529. */
  4530. Quaternion.prototype.copyFrom = function (other) {
  4531. this.x = other.x;
  4532. this.y = other.y;
  4533. this.z = other.z;
  4534. this.w = other.w;
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the current quaternion with the given float coordinates
  4539. * @param x defines the x coordinate
  4540. * @param y defines the y coordinate
  4541. * @param z defines the z coordinate
  4542. * @param w defines the w coordinate
  4543. * @returns the updated current quaternion
  4544. */
  4545. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4546. this.x = x;
  4547. this.y = y;
  4548. this.z = z;
  4549. this.w = w;
  4550. return this;
  4551. };
  4552. /**
  4553. * Updates the current quaternion from the given float coordinates
  4554. * @param x defines the x coordinate
  4555. * @param y defines the y coordinate
  4556. * @param z defines the z coordinate
  4557. * @param w defines the w coordinate
  4558. * @returns the updated current quaternion
  4559. */
  4560. Quaternion.prototype.set = function (x, y, z, w) {
  4561. return this.copyFromFloats(x, y, z, w);
  4562. };
  4563. /**
  4564. * Adds two quaternions
  4565. * @param other defines the second operand
  4566. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4567. */
  4568. Quaternion.prototype.add = function (other) {
  4569. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4570. };
  4571. /**
  4572. * Add a quaternion to the current one
  4573. * @param other defines the quaternion to add
  4574. * @returns the current quaternion
  4575. */
  4576. Quaternion.prototype.addInPlace = function (other) {
  4577. this.x += other.x;
  4578. this.y += other.y;
  4579. this.z += other.z;
  4580. this.w += other.w;
  4581. return this;
  4582. };
  4583. /**
  4584. * Subtract two quaternions
  4585. * @param other defines the second operand
  4586. * @returns a new quaternion as the subtraction result of the given one from the current one
  4587. */
  4588. Quaternion.prototype.subtract = function (other) {
  4589. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4590. };
  4591. /**
  4592. * Multiplies the current quaternion by a scale factor
  4593. * @param value defines the scale factor
  4594. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4595. */
  4596. Quaternion.prototype.scale = function (value) {
  4597. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4598. };
  4599. /**
  4600. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4601. * @param scale defines the scale factor
  4602. * @param result defines the Quaternion object where to store the result
  4603. * @returns the unmodified current quaternion
  4604. */
  4605. Quaternion.prototype.scaleToRef = function (scale, result) {
  4606. result.x = this.x * scale;
  4607. result.y = this.y * scale;
  4608. result.z = this.z * scale;
  4609. result.w = this.w * scale;
  4610. return this;
  4611. };
  4612. /**
  4613. * Multiplies in place the current quaternion by a scale factor
  4614. * @param value defines the scale factor
  4615. * @returns the current modified quaternion
  4616. */
  4617. Quaternion.prototype.scaleInPlace = function (value) {
  4618. this.x *= value;
  4619. this.y *= value;
  4620. this.z *= value;
  4621. this.w *= value;
  4622. return this;
  4623. };
  4624. /**
  4625. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4626. * @param scale defines the scale factor
  4627. * @param result defines the Quaternion object where to store the result
  4628. * @returns the unmodified current quaternion
  4629. */
  4630. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4631. result.x += this.x * scale;
  4632. result.y += this.y * scale;
  4633. result.z += this.z * scale;
  4634. result.w += this.w * scale;
  4635. return this;
  4636. };
  4637. /**
  4638. * Multiplies two quaternions
  4639. * @param q1 defines the second operand
  4640. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4641. */
  4642. Quaternion.prototype.multiply = function (q1) {
  4643. var result = new Quaternion(0, 0, 0, 1.0);
  4644. this.multiplyToRef(q1, result);
  4645. return result;
  4646. };
  4647. /**
  4648. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4649. * @param q1 defines the second operand
  4650. * @param result defines the target quaternion
  4651. * @returns the current quaternion
  4652. */
  4653. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4654. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4655. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4656. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4657. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4658. result.copyFromFloats(x, y, z, w);
  4659. return this;
  4660. };
  4661. /**
  4662. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4663. * @param q1 defines the second operand
  4664. * @returns the currentupdated quaternion
  4665. */
  4666. Quaternion.prototype.multiplyInPlace = function (q1) {
  4667. this.multiplyToRef(q1, this);
  4668. return this;
  4669. };
  4670. /**
  4671. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4672. * @param ref defines the target quaternion
  4673. * @returns the current quaternion
  4674. */
  4675. Quaternion.prototype.conjugateToRef = function (ref) {
  4676. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4677. return this;
  4678. };
  4679. /**
  4680. * Conjugates in place (1-q) the current quaternion
  4681. * @returns the current updated quaternion
  4682. */
  4683. Quaternion.prototype.conjugateInPlace = function () {
  4684. this.x *= -1;
  4685. this.y *= -1;
  4686. this.z *= -1;
  4687. return this;
  4688. };
  4689. /**
  4690. * Conjugates in place (1-q) the current quaternion
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.prototype.conjugate = function () {
  4694. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4695. return result;
  4696. };
  4697. /**
  4698. * Gets length of current quaternion
  4699. * @returns the quaternion length (float)
  4700. */
  4701. Quaternion.prototype.length = function () {
  4702. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4703. };
  4704. /**
  4705. * Normalize in place the current quaternion
  4706. * @returns the current updated quaternion
  4707. */
  4708. Quaternion.prototype.normalize = function () {
  4709. var length = 1.0 / this.length();
  4710. this.x *= length;
  4711. this.y *= length;
  4712. this.z *= length;
  4713. this.w *= length;
  4714. return this;
  4715. };
  4716. /**
  4717. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4718. * @param order is a reserved parameter and is ignore for now
  4719. * @returns a new Vector3 containing the Euler angles
  4720. */
  4721. Quaternion.prototype.toEulerAngles = function (order) {
  4722. if (order === void 0) { order = "YZX"; }
  4723. var result = Vector3.Zero();
  4724. this.toEulerAnglesToRef(result, order);
  4725. return result;
  4726. };
  4727. /**
  4728. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4729. * @param result defines the vector which will be filled with the Euler angles
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns the current unchanged quaternion
  4732. */
  4733. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var qz = this.z;
  4736. var qx = this.x;
  4737. var qy = this.y;
  4738. var qw = this.w;
  4739. var sqw = qw * qw;
  4740. var sqz = qz * qz;
  4741. var sqx = qx * qx;
  4742. var sqy = qy * qy;
  4743. var zAxisY = qy * qz - qx * qw;
  4744. var limit = .4999999;
  4745. if (zAxisY < -limit) {
  4746. result.y = 2 * Math.atan2(qy, qw);
  4747. result.x = Math.PI / 2;
  4748. result.z = 0;
  4749. }
  4750. else if (zAxisY > limit) {
  4751. result.y = 2 * Math.atan2(qy, qw);
  4752. result.x = -Math.PI / 2;
  4753. result.z = 0;
  4754. }
  4755. else {
  4756. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4757. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4758. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4759. }
  4760. return this;
  4761. };
  4762. /**
  4763. * Updates the given rotation matrix with the current quaternion values
  4764. * @param result defines the target matrix
  4765. * @returns the current unchanged quaternion
  4766. */
  4767. Quaternion.prototype.toRotationMatrix = function (result) {
  4768. var xx = this.x * this.x;
  4769. var yy = this.y * this.y;
  4770. var zz = this.z * this.z;
  4771. var xy = this.x * this.y;
  4772. var zw = this.z * this.w;
  4773. var zx = this.z * this.x;
  4774. var yw = this.y * this.w;
  4775. var yz = this.y * this.z;
  4776. var xw = this.x * this.w;
  4777. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4778. result.m[1] = 2.0 * (xy + zw);
  4779. result.m[2] = 2.0 * (zx - yw);
  4780. result.m[3] = 0;
  4781. result.m[4] = 2.0 * (xy - zw);
  4782. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4783. result.m[6] = 2.0 * (yz + xw);
  4784. result.m[7] = 0;
  4785. result.m[8] = 2.0 * (zx + yw);
  4786. result.m[9] = 2.0 * (yz - xw);
  4787. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4788. result.m[11] = 0;
  4789. result.m[12] = 0;
  4790. result.m[13] = 0;
  4791. result.m[14] = 0;
  4792. result.m[15] = 1.0;
  4793. result._markAsUpdated();
  4794. return this;
  4795. };
  4796. /**
  4797. * Updates the current quaternion from the given rotation matrix values
  4798. * @param matrix defines the source matrix
  4799. * @returns the current updated quaternion
  4800. */
  4801. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4802. Quaternion.FromRotationMatrixToRef(matrix, this);
  4803. return this;
  4804. };
  4805. // Statics
  4806. /**
  4807. * Creates a new quaternion from a rotation matrix
  4808. * @param matrix defines the source matrix
  4809. * @returns a new quaternion created from the given rotation matrix values
  4810. */
  4811. Quaternion.FromRotationMatrix = function (matrix) {
  4812. var result = new Quaternion();
  4813. Quaternion.FromRotationMatrixToRef(matrix, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Updates the given quaternion with the given rotation matrix values
  4818. * @param matrix defines the source matrix
  4819. * @param result defines the target quaternion
  4820. */
  4821. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4822. var data = matrix.m;
  4823. var m11 = data[0], m12 = data[4], m13 = data[8];
  4824. var m21 = data[1], m22 = data[5], m23 = data[9];
  4825. var m31 = data[2], m32 = data[6], m33 = data[10];
  4826. var trace = m11 + m22 + m33;
  4827. var s;
  4828. if (trace > 0) {
  4829. s = 0.5 / Math.sqrt(trace + 1.0);
  4830. result.w = 0.25 / s;
  4831. result.x = (m32 - m23) * s;
  4832. result.y = (m13 - m31) * s;
  4833. result.z = (m21 - m12) * s;
  4834. }
  4835. else if (m11 > m22 && m11 > m33) {
  4836. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4837. result.w = (m32 - m23) / s;
  4838. result.x = 0.25 * s;
  4839. result.y = (m12 + m21) / s;
  4840. result.z = (m13 + m31) / s;
  4841. }
  4842. else if (m22 > m33) {
  4843. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4844. result.w = (m13 - m31) / s;
  4845. result.x = (m12 + m21) / s;
  4846. result.y = 0.25 * s;
  4847. result.z = (m23 + m32) / s;
  4848. }
  4849. else {
  4850. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4851. result.w = (m21 - m12) / s;
  4852. result.x = (m13 + m31) / s;
  4853. result.y = (m23 + m32) / s;
  4854. result.z = 0.25 * s;
  4855. }
  4856. };
  4857. /**
  4858. * Returns the dot product (float) between the quaternions "left" and "right"
  4859. * @param left defines the left operand
  4860. * @param right defines the right operand
  4861. * @returns the dot product
  4862. */
  4863. Quaternion.Dot = function (left, right) {
  4864. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4865. };
  4866. /**
  4867. * Checks if the two quaternions are close to each other
  4868. * @param quat0 defines the first quaternion to check
  4869. * @param quat1 defines the second quaternion to check
  4870. * @returns true if the two quaternions are close to each other
  4871. */
  4872. Quaternion.AreClose = function (quat0, quat1) {
  4873. var dot = Quaternion.Dot(quat0, quat1);
  4874. return dot >= 0;
  4875. };
  4876. /**
  4877. * Creates an empty quaternion
  4878. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4879. */
  4880. Quaternion.Zero = function () {
  4881. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4882. };
  4883. /**
  4884. * Inverse a given quaternion
  4885. * @param q defines the source quaternion
  4886. * @returns a new quaternion as the inverted current quaternion
  4887. */
  4888. Quaternion.Inverse = function (q) {
  4889. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4890. };
  4891. /**
  4892. * Creates an identity quaternion
  4893. * @returns the identity quaternion
  4894. */
  4895. Quaternion.Identity = function () {
  4896. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4897. };
  4898. /**
  4899. * Gets a boolean indicating if the given quaternion is identity
  4900. * @param quaternion defines the quaternion to check
  4901. * @returns true if the quaternion is identity
  4902. */
  4903. Quaternion.IsIdentity = function (quaternion) {
  4904. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4905. };
  4906. /**
  4907. * Creates a quaternion from a rotation around an axis
  4908. * @param axis defines the axis to use
  4909. * @param angle defines the angle to use
  4910. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4911. */
  4912. Quaternion.RotationAxis = function (axis, angle) {
  4913. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4914. };
  4915. /**
  4916. * Creates a rotation around an axis and stores it into the given quaternion
  4917. * @param axis defines the axis to use
  4918. * @param angle defines the angle to use
  4919. * @param result defines the target quaternion
  4920. * @returns the target quaternion
  4921. */
  4922. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4923. var sin = Math.sin(angle / 2);
  4924. axis.normalize();
  4925. result.w = Math.cos(angle / 2);
  4926. result.x = axis.x * sin;
  4927. result.y = axis.y * sin;
  4928. result.z = axis.z * sin;
  4929. return result;
  4930. };
  4931. /**
  4932. * Creates a new quaternion from data stored into an array
  4933. * @param array defines the data source
  4934. * @param offset defines the offset in the source array where the data starts
  4935. * @returns a new quaternion
  4936. */
  4937. Quaternion.FromArray = function (array, offset) {
  4938. if (!offset) {
  4939. offset = 0;
  4940. }
  4941. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4942. };
  4943. /**
  4944. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4945. * @param yaw defines the rotation around Y axis
  4946. * @param pitch defines the rotation around X axis
  4947. * @param roll defines the rotation around Z axis
  4948. * @returns the new quaternion
  4949. */
  4950. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4951. var q = new Quaternion();
  4952. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4953. return q;
  4954. };
  4955. /**
  4956. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @param result defines the target quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4963. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4964. var halfRoll = roll * 0.5;
  4965. var halfPitch = pitch * 0.5;
  4966. var halfYaw = yaw * 0.5;
  4967. var sinRoll = Math.sin(halfRoll);
  4968. var cosRoll = Math.cos(halfRoll);
  4969. var sinPitch = Math.sin(halfPitch);
  4970. var cosPitch = Math.cos(halfPitch);
  4971. var sinYaw = Math.sin(halfYaw);
  4972. var cosYaw = Math.cos(halfYaw);
  4973. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4974. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4975. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4976. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4977. };
  4978. /**
  4979. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4980. * @param alpha defines the rotation around first axis
  4981. * @param beta defines the rotation around second axis
  4982. * @param gamma defines the rotation around third axis
  4983. * @returns the new quaternion
  4984. */
  4985. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4986. var result = new Quaternion();
  4987. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4988. return result;
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @param result defines the target quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4998. // Produces a quaternion from Euler angles in the z-x-z orientation
  4999. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5000. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5001. var halfBeta = beta * 0.5;
  5002. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5003. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5004. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5005. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5006. };
  5007. /**
  5008. * 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)
  5009. * @param axis1 defines the first axis
  5010. * @param axis2 defines the second axis
  5011. * @param axis3 defines the third axis
  5012. * @returns the new quaternion
  5013. */
  5014. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5015. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5016. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5017. return quat;
  5018. };
  5019. /**
  5020. * 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
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @param ref defines the target quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5027. var rotMat = MathTmp.Matrix[0];
  5028. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5029. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5030. };
  5031. /**
  5032. * Interpolates between two quaternions
  5033. * @param left defines first quaternion
  5034. * @param right defines second quaternion
  5035. * @param amount defines the gradient to use
  5036. * @returns the new interpolated quaternion
  5037. */
  5038. Quaternion.Slerp = function (left, right, amount) {
  5039. var result = Quaternion.Identity();
  5040. Quaternion.SlerpToRef(left, right, amount, result);
  5041. return result;
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions and stores it into a target quaternion
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @param result defines the target quaternion
  5049. */
  5050. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5051. var num2;
  5052. var num3;
  5053. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5054. var flag = false;
  5055. if (num4 < 0) {
  5056. flag = true;
  5057. num4 = -num4;
  5058. }
  5059. if (num4 > 0.999999) {
  5060. num3 = 1 - amount;
  5061. num2 = flag ? -amount : amount;
  5062. }
  5063. else {
  5064. var num5 = Math.acos(num4);
  5065. var num6 = (1.0 / Math.sin(num5));
  5066. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5067. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5068. }
  5069. result.x = (num3 * left.x) + (num2 * right.x);
  5070. result.y = (num3 * left.y) + (num2 * right.y);
  5071. result.z = (num3 * left.z) + (num2 * right.z);
  5072. result.w = (num3 * left.w) + (num2 * right.w);
  5073. };
  5074. /**
  5075. * Interpolate between two quaternions using Hermite interpolation
  5076. * @param value1 defines first quaternion
  5077. * @param tangent1 defines the incoming tangent
  5078. * @param value2 defines second quaternion
  5079. * @param tangent2 defines the outgoing tangent
  5080. * @param amount defines the target quaternion
  5081. * @returns the new interpolated quaternion
  5082. */
  5083. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5084. var squared = amount * amount;
  5085. var cubed = amount * squared;
  5086. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5087. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5088. var part3 = (cubed - (2.0 * squared)) + amount;
  5089. var part4 = cubed - squared;
  5090. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5091. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5092. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5093. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5094. return new Quaternion(x, y, z, w);
  5095. };
  5096. return Quaternion;
  5097. }());
  5098. BABYLON.Quaternion = Quaternion;
  5099. /**
  5100. * Class used to store matrix data (4x4)
  5101. */
  5102. var Matrix = /** @class */ (function () {
  5103. /**
  5104. * Creates an empty matrix (filled with zeros)
  5105. */
  5106. function Matrix() {
  5107. this._isIdentity = false;
  5108. this._isIdentityDirty = true;
  5109. /**
  5110. * Gets or sets the internal data of the matrix
  5111. */
  5112. this.m = new Float32Array(16);
  5113. this._markAsUpdated();
  5114. }
  5115. /** @hidden */
  5116. Matrix.prototype._markAsUpdated = function () {
  5117. this.updateFlag = Matrix._updateFlagSeed++;
  5118. this._isIdentityDirty = true;
  5119. };
  5120. // Properties
  5121. /**
  5122. * Check if the current matrix is indentity
  5123. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5124. * @returns true is the matrix is the identity matrix
  5125. */
  5126. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5127. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5128. if (this._isIdentityDirty) {
  5129. this._isIdentityDirty = false;
  5130. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5131. this._isIdentity = false;
  5132. }
  5133. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5134. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5135. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5136. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5137. this._isIdentity = false;
  5138. }
  5139. else {
  5140. this._isIdentity = true;
  5141. }
  5142. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. }
  5146. return this._isIdentity;
  5147. };
  5148. /**
  5149. * Gets the determinant of the matrix
  5150. * @returns the matrix determinant
  5151. */
  5152. Matrix.prototype.determinant = function () {
  5153. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5154. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5155. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5156. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5157. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5158. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5159. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5160. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5161. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5162. };
  5163. // Methods
  5164. /**
  5165. * Returns the matrix as a Float32Array
  5166. * @returns the matrix underlying array
  5167. */
  5168. Matrix.prototype.toArray = function () {
  5169. return this.m;
  5170. };
  5171. /**
  5172. * Returns the matrix as a Float32Array
  5173. * @returns the matrix underlying array.
  5174. */
  5175. Matrix.prototype.asArray = function () {
  5176. return this.toArray();
  5177. };
  5178. /**
  5179. * Inverts the current matrix in place
  5180. * @returns the current inverted matrix
  5181. */
  5182. Matrix.prototype.invert = function () {
  5183. this.invertToRef(this);
  5184. return this;
  5185. };
  5186. /**
  5187. * Sets all the matrix elements to zero
  5188. * @returns the current matrix
  5189. */
  5190. Matrix.prototype.reset = function () {
  5191. for (var index = 0; index < 16; index++) {
  5192. this.m[index] = 0.0;
  5193. }
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Adds the current matrix with a second one
  5199. * @param other defines the matrix to add
  5200. * @returns a new matrix as the addition of the current matrix and the given one
  5201. */
  5202. Matrix.prototype.add = function (other) {
  5203. var result = new Matrix();
  5204. this.addToRef(other, result);
  5205. return result;
  5206. };
  5207. /**
  5208. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5209. * @param other defines the matrix to add
  5210. * @param result defines the target matrix
  5211. * @returns the current matrix
  5212. */
  5213. Matrix.prototype.addToRef = function (other, result) {
  5214. for (var index = 0; index < 16; index++) {
  5215. result.m[index] = this.m[index] + other.m[index];
  5216. }
  5217. result._markAsUpdated();
  5218. return this;
  5219. };
  5220. /**
  5221. * Adds in place the given matrix to the current matrix
  5222. * @param other defines the second operand
  5223. * @returns the current updated matrix
  5224. */
  5225. Matrix.prototype.addToSelf = function (other) {
  5226. for (var index = 0; index < 16; index++) {
  5227. this.m[index] += other.m[index];
  5228. }
  5229. this._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Sets the given matrix to the current inverted Matrix
  5234. * @param other defines the target matrix
  5235. * @returns the unmodified current matrix
  5236. */
  5237. Matrix.prototype.invertToRef = function (other) {
  5238. var l1 = this.m[0];
  5239. var l2 = this.m[1];
  5240. var l3 = this.m[2];
  5241. var l4 = this.m[3];
  5242. var l5 = this.m[4];
  5243. var l6 = this.m[5];
  5244. var l7 = this.m[6];
  5245. var l8 = this.m[7];
  5246. var l9 = this.m[8];
  5247. var l10 = this.m[9];
  5248. var l11 = this.m[10];
  5249. var l12 = this.m[11];
  5250. var l13 = this.m[12];
  5251. var l14 = this.m[13];
  5252. var l15 = this.m[14];
  5253. var l16 = this.m[15];
  5254. var l17 = (l11 * l16) - (l12 * l15);
  5255. var l18 = (l10 * l16) - (l12 * l14);
  5256. var l19 = (l10 * l15) - (l11 * l14);
  5257. var l20 = (l9 * l16) - (l12 * l13);
  5258. var l21 = (l9 * l15) - (l11 * l13);
  5259. var l22 = (l9 * l14) - (l10 * l13);
  5260. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5261. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5262. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5263. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5264. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5265. var l28 = (l7 * l16) - (l8 * l15);
  5266. var l29 = (l6 * l16) - (l8 * l14);
  5267. var l30 = (l6 * l15) - (l7 * l14);
  5268. var l31 = (l5 * l16) - (l8 * l13);
  5269. var l32 = (l5 * l15) - (l7 * l13);
  5270. var l33 = (l5 * l14) - (l6 * l13);
  5271. var l34 = (l7 * l12) - (l8 * l11);
  5272. var l35 = (l6 * l12) - (l8 * l10);
  5273. var l36 = (l6 * l11) - (l7 * l10);
  5274. var l37 = (l5 * l12) - (l8 * l9);
  5275. var l38 = (l5 * l11) - (l7 * l9);
  5276. var l39 = (l5 * l10) - (l6 * l9);
  5277. other.m[0] = l23 * l27;
  5278. other.m[4] = l24 * l27;
  5279. other.m[8] = l25 * l27;
  5280. other.m[12] = l26 * l27;
  5281. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5282. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5283. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5284. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5285. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5286. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5287. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5288. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5289. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5290. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5291. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5292. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5293. other._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Inserts the translation vector (using 3 floats) in the current matrix
  5298. * @param x defines the 1st component of the translation
  5299. * @param y defines the 2nd component of the translation
  5300. * @param z defines the 3rd component of the translation
  5301. * @returns the current updated matrix
  5302. */
  5303. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5304. this.m[12] = x;
  5305. this.m[13] = y;
  5306. this.m[14] = z;
  5307. this._markAsUpdated();
  5308. return this;
  5309. };
  5310. /**
  5311. * Inserts the translation vector in the current matrix
  5312. * @param vector3 defines the translation to insert
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslation = function (vector3) {
  5316. this.m[12] = vector3.x;
  5317. this.m[13] = vector3.y;
  5318. this.m[14] = vector3.z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Gets the translation value of the current matrix
  5324. * @returns a new Vector3 as the extracted translation from the matrix
  5325. */
  5326. Matrix.prototype.getTranslation = function () {
  5327. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5328. };
  5329. /**
  5330. * Fill a Vector3 with the extracted translation from the matrix
  5331. * @param result defines the Vector3 where to store the translation
  5332. * @returns the current matrix
  5333. */
  5334. Matrix.prototype.getTranslationToRef = function (result) {
  5335. result.x = this.m[12];
  5336. result.y = this.m[13];
  5337. result.z = this.m[14];
  5338. return this;
  5339. };
  5340. /**
  5341. * Remove rotation and scaling part from the matrix
  5342. * @returns the updated matrix
  5343. */
  5344. Matrix.prototype.removeRotationAndScaling = function () {
  5345. this.setRowFromFloats(0, 1, 0, 0, 0);
  5346. this.setRowFromFloats(1, 0, 1, 0, 0);
  5347. this.setRowFromFloats(2, 0, 0, 1, 0);
  5348. return this;
  5349. };
  5350. /**
  5351. * Multiply two matrices
  5352. * @param other defines the second operand
  5353. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5354. */
  5355. Matrix.prototype.multiply = function (other) {
  5356. var result = new Matrix();
  5357. this.multiplyToRef(other, result);
  5358. return result;
  5359. };
  5360. /**
  5361. * Copy the current matrix from the given one
  5362. * @param other defines the source matrix
  5363. * @returns the current updated matrix
  5364. */
  5365. Matrix.prototype.copyFrom = function (other) {
  5366. for (var index = 0; index < 16; index++) {
  5367. this.m[index] = other.m[index];
  5368. }
  5369. this._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Populates the given array from the starting index with the current matrix values
  5374. * @param array defines the target array
  5375. * @param offset defines the offset in the target array where to start storing values
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.copyToArray = function (array, offset) {
  5379. if (offset === void 0) { offset = 0; }
  5380. for (var index = 0; index < 16; index++) {
  5381. array[offset + index] = this.m[index];
  5382. }
  5383. return this;
  5384. };
  5385. /**
  5386. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5387. * @param other defines the second operand
  5388. * @param result defines the matrix where to store the multiplication
  5389. * @returns the current matrix
  5390. */
  5391. Matrix.prototype.multiplyToRef = function (other, result) {
  5392. this.multiplyToArray(other, result.m, 0);
  5393. result._markAsUpdated();
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the array where to store the multiplication
  5400. * @param offset defines the offset in the target array where to start storing values
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5404. var tm0 = this.m[0];
  5405. var tm1 = this.m[1];
  5406. var tm2 = this.m[2];
  5407. var tm3 = this.m[3];
  5408. var tm4 = this.m[4];
  5409. var tm5 = this.m[5];
  5410. var tm6 = this.m[6];
  5411. var tm7 = this.m[7];
  5412. var tm8 = this.m[8];
  5413. var tm9 = this.m[9];
  5414. var tm10 = this.m[10];
  5415. var tm11 = this.m[11];
  5416. var tm12 = this.m[12];
  5417. var tm13 = this.m[13];
  5418. var tm14 = this.m[14];
  5419. var tm15 = this.m[15];
  5420. var om0 = other.m[0];
  5421. var om1 = other.m[1];
  5422. var om2 = other.m[2];
  5423. var om3 = other.m[3];
  5424. var om4 = other.m[4];
  5425. var om5 = other.m[5];
  5426. var om6 = other.m[6];
  5427. var om7 = other.m[7];
  5428. var om8 = other.m[8];
  5429. var om9 = other.m[9];
  5430. var om10 = other.m[10];
  5431. var om11 = other.m[11];
  5432. var om12 = other.m[12];
  5433. var om13 = other.m[13];
  5434. var om14 = other.m[14];
  5435. var om15 = other.m[15];
  5436. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5437. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5438. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5439. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5440. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5441. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5442. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5443. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5444. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5445. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5446. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5447. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5448. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5449. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5450. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5451. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5452. return this;
  5453. };
  5454. /**
  5455. * Check equality between this matrix and a second one
  5456. * @param value defines the second matrix to compare
  5457. * @returns true is the current matrix and the given one values are strictly equal
  5458. */
  5459. Matrix.prototype.equals = function (value) {
  5460. return value &&
  5461. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5462. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5463. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5464. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5465. };
  5466. /**
  5467. * Clone the current matrix
  5468. * @returns a new matrix from the current matrix
  5469. */
  5470. Matrix.prototype.clone = function () {
  5471. 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]);
  5472. };
  5473. /**
  5474. * Returns the name of the current matrix class
  5475. * @returns the string "Matrix"
  5476. */
  5477. Matrix.prototype.getClassName = function () {
  5478. return "Matrix";
  5479. };
  5480. /**
  5481. * Gets the hash code of the current matrix
  5482. * @returns the hash code
  5483. */
  5484. Matrix.prototype.getHashCode = function () {
  5485. var hash = this.m[0] || 0;
  5486. for (var i = 1; i < 16; i++) {
  5487. hash = (hash * 397) ^ (this.m[i] || 0);
  5488. }
  5489. return hash;
  5490. };
  5491. /**
  5492. * Decomposes the current Matrix into a translation, rotation and scaling components
  5493. * @param scale defines the scale vector3 given as a reference to update
  5494. * @param rotation defines the rotation quaternion given as a reference to update
  5495. * @param translation defines the translation vector3 given as a reference to update
  5496. * @returns true if operation was successful
  5497. */
  5498. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5499. if (translation) {
  5500. translation.x = this.m[12];
  5501. translation.y = this.m[13];
  5502. translation.z = this.m[14];
  5503. }
  5504. scale = scale || MathTmp.Vector3[0];
  5505. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5506. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5507. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5508. if (this.determinant() <= 0) {
  5509. scale.y *= -1;
  5510. }
  5511. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5512. if (rotation) {
  5513. rotation.x = 0;
  5514. rotation.y = 0;
  5515. rotation.z = 0;
  5516. rotation.w = 1;
  5517. }
  5518. return false;
  5519. }
  5520. if (rotation) {
  5521. 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]);
  5522. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5523. }
  5524. return true;
  5525. };
  5526. /**
  5527. * Gets specific row of the matrix
  5528. * @param index defines the number of the row to get
  5529. * @returns the index-th row of the current matrix as a new Vector4
  5530. */
  5531. Matrix.prototype.getRow = function (index) {
  5532. if (index < 0 || index > 3) {
  5533. return null;
  5534. }
  5535. var i = index * 4;
  5536. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5537. };
  5538. /**
  5539. * Sets the index-th row of the current matrix to the vector4 values
  5540. * @param index defines the number of the row to set
  5541. * @param row defines the target vector4
  5542. * @returns the updated current matrix
  5543. */
  5544. Matrix.prototype.setRow = function (index, row) {
  5545. if (index < 0 || index > 3) {
  5546. return this;
  5547. }
  5548. var i = index * 4;
  5549. this.m[i + 0] = row.x;
  5550. this.m[i + 1] = row.y;
  5551. this.m[i + 2] = row.z;
  5552. this.m[i + 3] = row.w;
  5553. this._markAsUpdated();
  5554. return this;
  5555. };
  5556. /**
  5557. * Compute the transpose of the matrix
  5558. * @returns the new transposed matrix
  5559. */
  5560. Matrix.prototype.transpose = function () {
  5561. return Matrix.Transpose(this);
  5562. };
  5563. /**
  5564. * Compute the transpose of the matrix and store it in a given matrix
  5565. * @param result defines the target matrix
  5566. * @returns the current matrix
  5567. */
  5568. Matrix.prototype.transposeToRef = function (result) {
  5569. Matrix.TransposeToRef(this, result);
  5570. return this;
  5571. };
  5572. /**
  5573. * Sets the index-th row of the current matrix with the given 4 x float values
  5574. * @param index defines the row index
  5575. * @param x defines the x component to set
  5576. * @param y defines the y component to set
  5577. * @param z defines the z component to set
  5578. * @param w defines the w component to set
  5579. * @returns the updated current matrix
  5580. */
  5581. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5582. if (index < 0 || index > 3) {
  5583. return this;
  5584. }
  5585. var i = index * 4;
  5586. this.m[i + 0] = x;
  5587. this.m[i + 1] = y;
  5588. this.m[i + 2] = z;
  5589. this.m[i + 3] = w;
  5590. this._markAsUpdated();
  5591. return this;
  5592. };
  5593. /**
  5594. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5595. * @param scale defines the scale factor
  5596. * @returns a new matrix
  5597. */
  5598. Matrix.prototype.scale = function (scale) {
  5599. var result = new Matrix();
  5600. this.scaleToRef(scale, result);
  5601. return result;
  5602. };
  5603. /**
  5604. * Scale the current matrix values by a factor to a given result matrix
  5605. * @param scale defines the scale factor
  5606. * @param result defines the matrix to store the result
  5607. * @returns the current matrix
  5608. */
  5609. Matrix.prototype.scaleToRef = function (scale, result) {
  5610. for (var index = 0; index < 16; index++) {
  5611. result.m[index] = this.m[index] * scale;
  5612. }
  5613. result._markAsUpdated();
  5614. return this;
  5615. };
  5616. /**
  5617. * Scale the current matrix values by a factor and add the result to a given matrix
  5618. * @param scale defines the scale factor
  5619. * @param result defines the Matrix to store the result
  5620. * @returns the current matrix
  5621. */
  5622. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5623. for (var index = 0; index < 16; index++) {
  5624. result.m[index] += this.m[index] * scale;
  5625. }
  5626. result._markAsUpdated();
  5627. return this;
  5628. };
  5629. /**
  5630. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5631. * @param ref matrix to store the result
  5632. */
  5633. Matrix.prototype.toNormalMatrix = function (ref) {
  5634. this.invertToRef(ref);
  5635. ref.transpose();
  5636. var m = ref.m;
  5637. 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);
  5638. };
  5639. /**
  5640. * Gets only rotation part of the current matrix
  5641. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5642. */
  5643. Matrix.prototype.getRotationMatrix = function () {
  5644. var result = Matrix.Identity();
  5645. this.getRotationMatrixToRef(result);
  5646. return result;
  5647. };
  5648. /**
  5649. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5650. * @param result defines the target matrix to store data to
  5651. * @returns the current matrix
  5652. */
  5653. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5654. var m = this.m;
  5655. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5656. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5657. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5658. if (this.determinant() <= 0) {
  5659. sy *= -1;
  5660. }
  5661. if (sx === 0 || sy === 0 || sz === 0) {
  5662. Matrix.IdentityToRef(result);
  5663. }
  5664. else {
  5665. 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);
  5666. }
  5667. return this;
  5668. };
  5669. // Statics
  5670. /**
  5671. * Creates a matrix from an array
  5672. * @param array defines the source array
  5673. * @param offset defines an offset in the source array
  5674. * @returns a new Matrix set from the starting index of the given array
  5675. */
  5676. Matrix.FromArray = function (array, offset) {
  5677. var result = new Matrix();
  5678. if (!offset) {
  5679. offset = 0;
  5680. }
  5681. Matrix.FromArrayToRef(array, offset, result);
  5682. return result;
  5683. };
  5684. /**
  5685. * Copy the content of an array into a given matrix
  5686. * @param array defines the source array
  5687. * @param offset defines an offset in the source array
  5688. * @param result defines the target matrix
  5689. */
  5690. Matrix.FromArrayToRef = function (array, offset, result) {
  5691. for (var index = 0; index < 16; index++) {
  5692. result.m[index] = array[index + offset];
  5693. }
  5694. result._markAsUpdated();
  5695. };
  5696. /**
  5697. * Stores an array into a matrix after having multiplied each component by a given factor
  5698. * @param array defines the source array
  5699. * @param offset defines the offset in the source array
  5700. * @param scale defines the scaling factor
  5701. * @param result defines the target matrix
  5702. */
  5703. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5704. for (var index = 0; index < 16; index++) {
  5705. result.m[index] = array[index + offset] * scale;
  5706. }
  5707. result._markAsUpdated();
  5708. };
  5709. /**
  5710. * Stores a list of values (16) inside a given matrix
  5711. * @param initialM11 defines 1st value of 1st row
  5712. * @param initialM12 defines 2nd value of 1st row
  5713. * @param initialM13 defines 3rd value of 1st row
  5714. * @param initialM14 defines 4th value of 1st row
  5715. * @param initialM21 defines 1st value of 2nd row
  5716. * @param initialM22 defines 2nd value of 2nd row
  5717. * @param initialM23 defines 3rd value of 2nd row
  5718. * @param initialM24 defines 4th value of 2nd row
  5719. * @param initialM31 defines 1st value of 3rd row
  5720. * @param initialM32 defines 2nd value of 3rd row
  5721. * @param initialM33 defines 3rd value of 3rd row
  5722. * @param initialM34 defines 4th value of 3rd row
  5723. * @param initialM41 defines 1st value of 4th row
  5724. * @param initialM42 defines 2nd value of 4th row
  5725. * @param initialM43 defines 3rd value of 4th row
  5726. * @param initialM44 defines 4th value of 4th row
  5727. * @param result defines the target matrix
  5728. */
  5729. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5730. result.m[0] = initialM11;
  5731. result.m[1] = initialM12;
  5732. result.m[2] = initialM13;
  5733. result.m[3] = initialM14;
  5734. result.m[4] = initialM21;
  5735. result.m[5] = initialM22;
  5736. result.m[6] = initialM23;
  5737. result.m[7] = initialM24;
  5738. result.m[8] = initialM31;
  5739. result.m[9] = initialM32;
  5740. result.m[10] = initialM33;
  5741. result.m[11] = initialM34;
  5742. result.m[12] = initialM41;
  5743. result.m[13] = initialM42;
  5744. result.m[14] = initialM43;
  5745. result.m[15] = initialM44;
  5746. result._markAsUpdated();
  5747. };
  5748. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5749. /**
  5750. * Gets an identity matrix that must not be updated
  5751. */
  5752. get: function () {
  5753. return Matrix._identityReadOnly;
  5754. },
  5755. enumerable: true,
  5756. configurable: true
  5757. });
  5758. /**
  5759. * Creates new matrix from a list of values (16)
  5760. * @param initialM11 defines 1st value of 1st row
  5761. * @param initialM12 defines 2nd value of 1st row
  5762. * @param initialM13 defines 3rd value of 1st row
  5763. * @param initialM14 defines 4th value of 1st row
  5764. * @param initialM21 defines 1st value of 2nd row
  5765. * @param initialM22 defines 2nd value of 2nd row
  5766. * @param initialM23 defines 3rd value of 2nd row
  5767. * @param initialM24 defines 4th value of 2nd row
  5768. * @param initialM31 defines 1st value of 3rd row
  5769. * @param initialM32 defines 2nd value of 3rd row
  5770. * @param initialM33 defines 3rd value of 3rd row
  5771. * @param initialM34 defines 4th value of 3rd row
  5772. * @param initialM41 defines 1st value of 4th row
  5773. * @param initialM42 defines 2nd value of 4th row
  5774. * @param initialM43 defines 3rd value of 4th row
  5775. * @param initialM44 defines 4th value of 4th row
  5776. * @returns the new matrix
  5777. */
  5778. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5779. var result = new Matrix();
  5780. result.m[0] = initialM11;
  5781. result.m[1] = initialM12;
  5782. result.m[2] = initialM13;
  5783. result.m[3] = initialM14;
  5784. result.m[4] = initialM21;
  5785. result.m[5] = initialM22;
  5786. result.m[6] = initialM23;
  5787. result.m[7] = initialM24;
  5788. result.m[8] = initialM31;
  5789. result.m[9] = initialM32;
  5790. result.m[10] = initialM33;
  5791. result.m[11] = initialM34;
  5792. result.m[12] = initialM41;
  5793. result.m[13] = initialM42;
  5794. result.m[14] = initialM43;
  5795. result.m[15] = initialM44;
  5796. return result;
  5797. };
  5798. /**
  5799. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5800. * @param scale defines the scale vector3
  5801. * @param rotation defines the rotation quaternion
  5802. * @param translation defines the translation vector3
  5803. * @returns a new matrix
  5804. */
  5805. Matrix.Compose = function (scale, rotation, translation) {
  5806. var result = Matrix.Identity();
  5807. Matrix.ComposeToRef(scale, rotation, translation, result);
  5808. return result;
  5809. };
  5810. /**
  5811. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @param result defines the target matrix
  5816. */
  5817. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5818. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5819. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5820. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5821. result.setTranslation(translation);
  5822. };
  5823. /**
  5824. * Creates a new identity matrix
  5825. * @returns a new identity matrix
  5826. */
  5827. Matrix.Identity = function () {
  5828. 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);
  5829. };
  5830. /**
  5831. * Creates a new identity matrix and stores the result in a given matrix
  5832. * @param result defines the target matrix
  5833. */
  5834. Matrix.IdentityToRef = function (result) {
  5835. 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);
  5836. };
  5837. /**
  5838. * Creates a new zero matrix
  5839. * @returns a new zero matrix
  5840. */
  5841. Matrix.Zero = function () {
  5842. 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);
  5843. };
  5844. /**
  5845. * Creates a new rotation matrix for "angle" radians around the X axis
  5846. * @param angle defines the angle (in radians) to use
  5847. * @return the new matrix
  5848. */
  5849. Matrix.RotationX = function (angle) {
  5850. var result = new Matrix();
  5851. Matrix.RotationXToRef(angle, result);
  5852. return result;
  5853. };
  5854. /**
  5855. * Creates a new matrix as the invert of a given matrix
  5856. * @param source defines the source matrix
  5857. * @returns the new matrix
  5858. */
  5859. Matrix.Invert = function (source) {
  5860. var result = new Matrix();
  5861. source.invertToRef(result);
  5862. return result;
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5866. * @param angle defines the angle (in radians) to use
  5867. * @param result defines the target matrix
  5868. */
  5869. Matrix.RotationXToRef = function (angle, result) {
  5870. var s = Math.sin(angle);
  5871. var c = Math.cos(angle);
  5872. result.m[0] = 1.0;
  5873. result.m[15] = 1.0;
  5874. result.m[5] = c;
  5875. result.m[10] = c;
  5876. result.m[9] = -s;
  5877. result.m[6] = s;
  5878. result.m[1] = 0.0;
  5879. result.m[2] = 0.0;
  5880. result.m[3] = 0.0;
  5881. result.m[4] = 0.0;
  5882. result.m[7] = 0.0;
  5883. result.m[8] = 0.0;
  5884. result.m[11] = 0.0;
  5885. result.m[12] = 0.0;
  5886. result.m[13] = 0.0;
  5887. result.m[14] = 0.0;
  5888. result._markAsUpdated();
  5889. };
  5890. /**
  5891. * Creates a new rotation matrix for "angle" radians around the Y axis
  5892. * @param angle defines the angle (in radians) to use
  5893. * @return the new matrix
  5894. */
  5895. Matrix.RotationY = function (angle) {
  5896. var result = new Matrix();
  5897. Matrix.RotationYToRef(angle, result);
  5898. return result;
  5899. };
  5900. /**
  5901. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5902. * @param angle defines the angle (in radians) to use
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYToRef = function (angle, result) {
  5906. var s = Math.sin(angle);
  5907. var c = Math.cos(angle);
  5908. result.m[5] = 1.0;
  5909. result.m[15] = 1.0;
  5910. result.m[0] = c;
  5911. result.m[2] = -s;
  5912. result.m[8] = s;
  5913. result.m[10] = c;
  5914. result.m[1] = 0.0;
  5915. result.m[3] = 0.0;
  5916. result.m[4] = 0.0;
  5917. result.m[6] = 0.0;
  5918. result.m[7] = 0.0;
  5919. result.m[9] = 0.0;
  5920. result.m[11] = 0.0;
  5921. result.m[12] = 0.0;
  5922. result.m[13] = 0.0;
  5923. result.m[14] = 0.0;
  5924. result._markAsUpdated();
  5925. };
  5926. /**
  5927. * Creates a new rotation matrix for "angle" radians around the Z axis
  5928. * @param angle defines the angle (in radians) to use
  5929. * @return the new matrix
  5930. */
  5931. Matrix.RotationZ = function (angle) {
  5932. var result = new Matrix();
  5933. Matrix.RotationZToRef(angle, result);
  5934. return result;
  5935. };
  5936. /**
  5937. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5938. * @param angle defines the angle (in radians) to use
  5939. * @param result defines the target matrix
  5940. */
  5941. Matrix.RotationZToRef = function (angle, result) {
  5942. var s = Math.sin(angle);
  5943. var c = Math.cos(angle);
  5944. result.m[10] = 1.0;
  5945. result.m[15] = 1.0;
  5946. result.m[0] = c;
  5947. result.m[1] = s;
  5948. result.m[4] = -s;
  5949. result.m[5] = c;
  5950. result.m[2] = 0.0;
  5951. result.m[3] = 0.0;
  5952. result.m[6] = 0.0;
  5953. result.m[7] = 0.0;
  5954. result.m[8] = 0.0;
  5955. result.m[9] = 0.0;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result._markAsUpdated();
  5961. };
  5962. /**
  5963. * Creates a new rotation matrix for "angle" radians around the given axis
  5964. * @param axis defines the axis to use
  5965. * @param angle defines the angle (in radians) to use
  5966. * @return the new matrix
  5967. */
  5968. Matrix.RotationAxis = function (axis, angle) {
  5969. var result = Matrix.Zero();
  5970. Matrix.RotationAxisToRef(axis, angle, result);
  5971. return result;
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @param result defines the target matrix
  5978. */
  5979. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5980. var s = Math.sin(-angle);
  5981. var c = Math.cos(-angle);
  5982. var c1 = 1 - c;
  5983. axis.normalize();
  5984. result.m[0] = (axis.x * axis.x) * c1 + c;
  5985. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5986. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5987. result.m[3] = 0.0;
  5988. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5989. result.m[5] = (axis.y * axis.y) * c1 + c;
  5990. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5991. result.m[7] = 0.0;
  5992. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5993. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5994. result.m[10] = (axis.z * axis.z) * c1 + c;
  5995. result.m[11] = 0.0;
  5996. result.m[15] = 1.0;
  5997. result._markAsUpdated();
  5998. };
  5999. /**
  6000. * Creates a rotation matrix
  6001. * @param yaw defines the yaw angle in radians (Y axis)
  6002. * @param pitch defines the pitch angle in radians (X axis)
  6003. * @param roll defines the roll angle in radians (X axis)
  6004. * @returns the new rotation matrix
  6005. */
  6006. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6007. var result = new Matrix();
  6008. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6009. return result;
  6010. };
  6011. /**
  6012. * Creates a rotation matrix and stores it in a given matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @param result defines the target matrix
  6017. */
  6018. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6019. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6020. this._tempQuaternion.toRotationMatrix(result);
  6021. };
  6022. /**
  6023. * Creates a scaling matrix
  6024. * @param x defines the scale factor on X axis
  6025. * @param y defines the scale factor on Y axis
  6026. * @param z defines the scale factor on Z axis
  6027. * @returns the new matrix
  6028. */
  6029. Matrix.Scaling = function (x, y, z) {
  6030. var result = Matrix.Zero();
  6031. Matrix.ScalingToRef(x, y, z, result);
  6032. return result;
  6033. };
  6034. /**
  6035. * Creates a scaling matrix and stores it in a given matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @param result defines the target matrix
  6040. */
  6041. Matrix.ScalingToRef = function (x, y, z, result) {
  6042. result.m[0] = x;
  6043. result.m[1] = 0.0;
  6044. result.m[2] = 0.0;
  6045. result.m[3] = 0.0;
  6046. result.m[4] = 0.0;
  6047. result.m[5] = y;
  6048. result.m[6] = 0.0;
  6049. result.m[7] = 0.0;
  6050. result.m[8] = 0.0;
  6051. result.m[9] = 0.0;
  6052. result.m[10] = z;
  6053. result.m[11] = 0.0;
  6054. result.m[12] = 0.0;
  6055. result.m[13] = 0.0;
  6056. result.m[14] = 0.0;
  6057. result.m[15] = 1.0;
  6058. result._markAsUpdated();
  6059. };
  6060. /**
  6061. * Creates a translation matrix
  6062. * @param x defines the translation on X axis
  6063. * @param y defines the translation on Y axis
  6064. * @param z defines the translationon Z axis
  6065. * @returns the new matrix
  6066. */
  6067. Matrix.Translation = function (x, y, z) {
  6068. var result = Matrix.Identity();
  6069. Matrix.TranslationToRef(x, y, z, result);
  6070. return result;
  6071. };
  6072. /**
  6073. * Creates a translation matrix and stores it in a given matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @param result defines the target matrix
  6078. */
  6079. Matrix.TranslationToRef = function (x, y, z, result) {
  6080. 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);
  6081. };
  6082. /**
  6083. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6084. * @param startValue defines the start value
  6085. * @param endValue defines the end value
  6086. * @param gradient defines the gradient factor
  6087. * @returns the new matrix
  6088. */
  6089. Matrix.Lerp = function (startValue, endValue, gradient) {
  6090. var result = Matrix.Zero();
  6091. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6092. return result;
  6093. };
  6094. /**
  6095. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @param result defines the Matrix object where to store data
  6100. */
  6101. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6102. for (var index = 0; index < 16; index++) {
  6103. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6104. }
  6105. result._markAsUpdated();
  6106. };
  6107. /**
  6108. * Builds a new matrix whose values are computed by:
  6109. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6110. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6111. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6112. * @param startValue defines the first matrix
  6113. * @param endValue defines the second matrix
  6114. * @param gradient defines the gradient between the two matrices
  6115. * @returns the new matrix
  6116. */
  6117. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6118. var result = Matrix.Zero();
  6119. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6120. return result;
  6121. };
  6122. /**
  6123. * Update a matrix to values which are computed by:
  6124. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6125. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6126. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6127. * @param startValue defines the first matrix
  6128. * @param endValue defines the second matrix
  6129. * @param gradient defines the gradient between the two matrices
  6130. * @param result defines the target matrix
  6131. */
  6132. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6133. var startScale = MathTmp.Vector3[0];
  6134. var startRotation = MathTmp.Quaternion[0];
  6135. var startTranslation = MathTmp.Vector3[1];
  6136. startValue.decompose(startScale, startRotation, startTranslation);
  6137. var endScale = MathTmp.Vector3[2];
  6138. var endRotation = MathTmp.Quaternion[1];
  6139. var endTranslation = MathTmp.Vector3[3];
  6140. endValue.decompose(endScale, endRotation, endTranslation);
  6141. var resultScale = MathTmp.Vector3[4];
  6142. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6143. var resultRotation = MathTmp.Quaternion[2];
  6144. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6145. var resultTranslation = MathTmp.Vector3[5];
  6146. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6147. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6148. };
  6149. /**
  6150. * 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"
  6151. * This function works in left handed mode
  6152. * @param eye defines the final position of the entity
  6153. * @param target defines where the entity should look at
  6154. * @param up defines the up vector for the entity
  6155. * @returns the new matrix
  6156. */
  6157. Matrix.LookAtLH = function (eye, target, up) {
  6158. var result = Matrix.Zero();
  6159. Matrix.LookAtLHToRef(eye, target, up, result);
  6160. return result;
  6161. };
  6162. /**
  6163. * 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".
  6164. * This function works in left handed mode
  6165. * @param eye defines the final position of the entity
  6166. * @param target defines where the entity should look at
  6167. * @param up defines the up vector for the entity
  6168. * @param result defines the target matrix
  6169. */
  6170. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6171. // Z axis
  6172. target.subtractToRef(eye, this._zAxis);
  6173. this._zAxis.normalize();
  6174. // X axis
  6175. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6176. if (this._xAxis.lengthSquared() === 0) {
  6177. this._xAxis.x = 1.0;
  6178. }
  6179. else {
  6180. this._xAxis.normalize();
  6181. }
  6182. // Y axis
  6183. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6184. this._yAxis.normalize();
  6185. // Eye angles
  6186. var ex = -Vector3.Dot(this._xAxis, eye);
  6187. var ey = -Vector3.Dot(this._yAxis, eye);
  6188. var ez = -Vector3.Dot(this._zAxis, eye);
  6189. 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);
  6190. };
  6191. /**
  6192. * 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"
  6193. * This function works in right handed mode
  6194. * @param eye defines the final position of the entity
  6195. * @param target defines where the entity should look at
  6196. * @param up defines the up vector for the entity
  6197. * @returns the new matrix
  6198. */
  6199. Matrix.LookAtRH = function (eye, target, up) {
  6200. var result = Matrix.Zero();
  6201. Matrix.LookAtRHToRef(eye, target, up, result);
  6202. return result;
  6203. };
  6204. /**
  6205. * 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".
  6206. * This function works in right handed mode
  6207. * @param eye defines the final position of the entity
  6208. * @param target defines where the entity should look at
  6209. * @param up defines the up vector for the entity
  6210. * @param result defines the target matrix
  6211. */
  6212. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6213. // Z axis
  6214. eye.subtractToRef(target, this._zAxis);
  6215. this._zAxis.normalize();
  6216. // X axis
  6217. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6218. if (this._xAxis.lengthSquared() === 0) {
  6219. this._xAxis.x = 1.0;
  6220. }
  6221. else {
  6222. this._xAxis.normalize();
  6223. }
  6224. // Y axis
  6225. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6226. this._yAxis.normalize();
  6227. // Eye angles
  6228. var ex = -Vector3.Dot(this._xAxis, eye);
  6229. var ey = -Vector3.Dot(this._yAxis, eye);
  6230. var ez = -Vector3.Dot(this._zAxis, eye);
  6231. 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);
  6232. };
  6233. /**
  6234. * Create a left-handed orthographic projection matrix
  6235. * @param width defines the viewport width
  6236. * @param height defines the viewport height
  6237. * @param znear defines the near clip plane
  6238. * @param zfar defines the far clip plane
  6239. * @returns a new matrix as a left-handed orthographic projection matrix
  6240. */
  6241. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6242. var matrix = Matrix.Zero();
  6243. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6244. return matrix;
  6245. };
  6246. /**
  6247. * Store a left-handed orthographic projection to a given matrix
  6248. * @param width defines the viewport width
  6249. * @param height defines the viewport height
  6250. * @param znear defines the near clip plane
  6251. * @param zfar defines the far clip plane
  6252. * @param result defines the target matrix
  6253. */
  6254. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6255. var n = znear;
  6256. var f = zfar;
  6257. var a = 2.0 / width;
  6258. var b = 2.0 / height;
  6259. var c = 2.0 / (f - n);
  6260. var d = -(f + n) / (f - n);
  6261. 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);
  6262. };
  6263. /**
  6264. * Create a left-handed orthographic projection matrix
  6265. * @param left defines the viewport left coordinate
  6266. * @param right defines the viewport right coordinate
  6267. * @param bottom defines the viewport bottom coordinate
  6268. * @param top defines the viewport top coordinate
  6269. * @param znear defines the near clip plane
  6270. * @param zfar defines the far clip plane
  6271. * @returns a new matrix as a left-handed orthographic projection matrix
  6272. */
  6273. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6274. var matrix = Matrix.Zero();
  6275. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6276. return matrix;
  6277. };
  6278. /**
  6279. * Stores a left-handed orthographic projection into a given matrix
  6280. * @param left defines the viewport left coordinate
  6281. * @param right defines the viewport right coordinate
  6282. * @param bottom defines the viewport bottom coordinate
  6283. * @param top defines the viewport top coordinate
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. */
  6288. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6289. var n = znear;
  6290. var f = zfar;
  6291. var a = 2.0 / (right - left);
  6292. var b = 2.0 / (top - bottom);
  6293. var c = 2.0 / (f - n);
  6294. var d = -(f + n) / (f - n);
  6295. var i0 = (left + right) / (left - right);
  6296. var i1 = (top + bottom) / (bottom - top);
  6297. 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);
  6298. };
  6299. /**
  6300. * Creates a right-handed orthographic projection matrix
  6301. * @param left defines the viewport left coordinate
  6302. * @param right defines the viewport right coordinate
  6303. * @param bottom defines the viewport bottom coordinate
  6304. * @param top defines the viewport top coordinate
  6305. * @param znear defines the near clip plane
  6306. * @param zfar defines the far clip plane
  6307. * @returns a new matrix as a right-handed orthographic projection matrix
  6308. */
  6309. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6310. var matrix = Matrix.Zero();
  6311. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6312. return matrix;
  6313. };
  6314. /**
  6315. * Stores a right-handed orthographic projection into a given matrix
  6316. * @param left defines the viewport left coordinate
  6317. * @param right defines the viewport right coordinate
  6318. * @param bottom defines the viewport bottom coordinate
  6319. * @param top defines the viewport top coordinate
  6320. * @param znear defines the near clip plane
  6321. * @param zfar defines the far clip plane
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6325. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6326. result.m[10] *= -1.0;
  6327. };
  6328. /**
  6329. * Creates a left-handed perspective projection matrix
  6330. * @param width defines the viewport width
  6331. * @param height defines the viewport height
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @returns a new matrix as a left-handed perspective projection matrix
  6335. */
  6336. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6337. var matrix = Matrix.Zero();
  6338. var n = znear;
  6339. var f = zfar;
  6340. var a = 2.0 * n / width;
  6341. var b = 2.0 * n / height;
  6342. var c = (f + n) / (f - n);
  6343. var d = -2.0 * f * n / (f - n);
  6344. 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);
  6345. return matrix;
  6346. };
  6347. /**
  6348. * Creates a left-handed perspective projection matrix
  6349. * @param fov defines the horizontal field of view
  6350. * @param aspect defines the aspect ratio
  6351. * @param znear defines the near clip plane
  6352. * @param zfar defines the far clip plane
  6353. * @returns a new matrix as a left-handed perspective projection matrix
  6354. */
  6355. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6356. var matrix = Matrix.Zero();
  6357. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6358. return matrix;
  6359. };
  6360. /**
  6361. * Stores a left-handed perspective projection into a given matrix
  6362. * @param fov defines the horizontal field of view
  6363. * @param aspect defines the aspect ratio
  6364. * @param znear defines the near clip plane
  6365. * @param zfar defines the far clip plane
  6366. * @param result defines the target matrix
  6367. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6368. */
  6369. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6370. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6371. var n = znear;
  6372. var f = zfar;
  6373. var t = 1.0 / (Math.tan(fov * 0.5));
  6374. var a = isVerticalFovFixed ? (t / aspect) : t;
  6375. var b = isVerticalFovFixed ? t : (t * aspect);
  6376. var c = (f + n) / (f - n);
  6377. var d = -2.0 * f * n / (f - n);
  6378. 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);
  6379. };
  6380. /**
  6381. * Creates a right-handed perspective projection matrix
  6382. * @param fov defines the horizontal field of view
  6383. * @param aspect defines the aspect ratio
  6384. * @param znear defines the near clip plane
  6385. * @param zfar defines the far clip plane
  6386. * @returns a new matrix as a right-handed perspective projection matrix
  6387. */
  6388. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6389. var matrix = Matrix.Zero();
  6390. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6391. return matrix;
  6392. };
  6393. /**
  6394. * Stores a right-handed perspective projection into a given matrix
  6395. * @param fov defines the horizontal field of view
  6396. * @param aspect defines the aspect ratio
  6397. * @param znear defines the near clip plane
  6398. * @param zfar defines the far clip plane
  6399. * @param result defines the target matrix
  6400. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6401. */
  6402. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6403. //alternatively this could be expressed as:
  6404. // m = PerspectiveFovLHToRef
  6405. // m[10] *= -1.0;
  6406. // m[11] *= -1.0;
  6407. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6408. var n = znear;
  6409. var f = zfar;
  6410. var t = 1.0 / (Math.tan(fov * 0.5));
  6411. var a = isVerticalFovFixed ? (t / aspect) : t;
  6412. var b = isVerticalFovFixed ? t : (t * aspect);
  6413. var c = -(f + n) / (f - n);
  6414. var d = -2 * f * n / (f - n);
  6415. 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);
  6416. };
  6417. /**
  6418. * Stores a perspective projection for WebVR info a given matrix
  6419. * @param fov defines the field of view
  6420. * @param znear defines the near clip plane
  6421. * @param zfar defines the far clip plane
  6422. * @param result defines the target matrix
  6423. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6424. */
  6425. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6426. if (rightHanded === void 0) { rightHanded = false; }
  6427. var rightHandedFactor = rightHanded ? -1 : 1;
  6428. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6429. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6430. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6431. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6432. var xScale = 2.0 / (leftTan + rightTan);
  6433. var yScale = 2.0 / (upTan + downTan);
  6434. result.m[0] = xScale;
  6435. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6436. result.m[5] = yScale;
  6437. result.m[6] = result.m[7] = 0.0;
  6438. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6439. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6440. result.m[10] = -zfar / (znear - zfar);
  6441. result.m[11] = 1.0 * rightHandedFactor;
  6442. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6443. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6444. result._markAsUpdated();
  6445. };
  6446. /**
  6447. * Computes a complete transformation matrix
  6448. * @param viewport defines the viewport to use
  6449. * @param world defines the world matrix
  6450. * @param view defines the view matrix
  6451. * @param projection defines the projection matrix
  6452. * @param zmin defines the near clip plane
  6453. * @param zmax defines the far clip plane
  6454. * @returns the transformation matrix
  6455. */
  6456. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6457. var cw = viewport.width;
  6458. var ch = viewport.height;
  6459. var cx = viewport.x;
  6460. var cy = viewport.y;
  6461. 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);
  6462. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6463. };
  6464. /**
  6465. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6466. * @param matrix defines the matrix to use
  6467. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6468. */
  6469. Matrix.GetAsMatrix2x2 = function (matrix) {
  6470. return new Float32Array([
  6471. matrix.m[0], matrix.m[1],
  6472. matrix.m[4], matrix.m[5]
  6473. ]);
  6474. };
  6475. /**
  6476. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix3x3 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1], matrix.m[2],
  6483. matrix.m[4], matrix.m[5], matrix.m[6],
  6484. matrix.m[8], matrix.m[9], matrix.m[10]
  6485. ]);
  6486. };
  6487. /**
  6488. * Compute the transpose of a given matrix
  6489. * @param matrix defines the matrix to transpose
  6490. * @returns the new matrix
  6491. */
  6492. Matrix.Transpose = function (matrix) {
  6493. var result = new Matrix();
  6494. Matrix.TransposeToRef(matrix, result);
  6495. return result;
  6496. };
  6497. /**
  6498. * Compute the transpose of a matrix and store it in a target matrix
  6499. * @param matrix defines the matrix to transpose
  6500. * @param result defines the target matrix
  6501. */
  6502. Matrix.TransposeToRef = function (matrix, result) {
  6503. result.m[0] = matrix.m[0];
  6504. result.m[1] = matrix.m[4];
  6505. result.m[2] = matrix.m[8];
  6506. result.m[3] = matrix.m[12];
  6507. result.m[4] = matrix.m[1];
  6508. result.m[5] = matrix.m[5];
  6509. result.m[6] = matrix.m[9];
  6510. result.m[7] = matrix.m[13];
  6511. result.m[8] = matrix.m[2];
  6512. result.m[9] = matrix.m[6];
  6513. result.m[10] = matrix.m[10];
  6514. result.m[11] = matrix.m[14];
  6515. result.m[12] = matrix.m[3];
  6516. result.m[13] = matrix.m[7];
  6517. result.m[14] = matrix.m[11];
  6518. result.m[15] = matrix.m[15];
  6519. };
  6520. /**
  6521. * Computes a reflection matrix from a plane
  6522. * @param plane defines the reflection plane
  6523. * @returns a new matrix
  6524. */
  6525. Matrix.Reflection = function (plane) {
  6526. var matrix = new Matrix();
  6527. Matrix.ReflectionToRef(plane, matrix);
  6528. return matrix;
  6529. };
  6530. /**
  6531. * Computes a reflection matrix from a plane
  6532. * @param plane defines the reflection plane
  6533. * @param result defines the target matrix
  6534. */
  6535. Matrix.ReflectionToRef = function (plane, result) {
  6536. plane.normalize();
  6537. var x = plane.normal.x;
  6538. var y = plane.normal.y;
  6539. var z = plane.normal.z;
  6540. var temp = -2 * x;
  6541. var temp2 = -2 * y;
  6542. var temp3 = -2 * z;
  6543. result.m[0] = (temp * x) + 1;
  6544. result.m[1] = temp2 * x;
  6545. result.m[2] = temp3 * x;
  6546. result.m[3] = 0.0;
  6547. result.m[4] = temp * y;
  6548. result.m[5] = (temp2 * y) + 1;
  6549. result.m[6] = temp3 * y;
  6550. result.m[7] = 0.0;
  6551. result.m[8] = temp * z;
  6552. result.m[9] = temp2 * z;
  6553. result.m[10] = (temp3 * z) + 1;
  6554. result.m[11] = 0.0;
  6555. result.m[12] = temp * plane.d;
  6556. result.m[13] = temp2 * plane.d;
  6557. result.m[14] = temp3 * plane.d;
  6558. result.m[15] = 1.0;
  6559. result._markAsUpdated();
  6560. };
  6561. /**
  6562. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6563. * @param xaxis defines the value of the 1st axis
  6564. * @param yaxis defines the value of the 2nd axis
  6565. * @param zaxis defines the value of the 3rd axis
  6566. * @param result defines the target matrix
  6567. */
  6568. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6569. result.m[0] = xaxis.x;
  6570. result.m[1] = xaxis.y;
  6571. result.m[2] = xaxis.z;
  6572. result.m[3] = 0.0;
  6573. result.m[4] = yaxis.x;
  6574. result.m[5] = yaxis.y;
  6575. result.m[6] = yaxis.z;
  6576. result.m[7] = 0.0;
  6577. result.m[8] = zaxis.x;
  6578. result.m[9] = zaxis.y;
  6579. result.m[10] = zaxis.z;
  6580. result.m[11] = 0.0;
  6581. result.m[12] = 0.0;
  6582. result.m[13] = 0.0;
  6583. result.m[14] = 0.0;
  6584. result.m[15] = 1.0;
  6585. result._markAsUpdated();
  6586. };
  6587. /**
  6588. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6589. * @param quat defines the quaternion to use
  6590. * @param result defines the target matrix
  6591. */
  6592. Matrix.FromQuaternionToRef = function (quat, result) {
  6593. var xx = quat.x * quat.x;
  6594. var yy = quat.y * quat.y;
  6595. var zz = quat.z * quat.z;
  6596. var xy = quat.x * quat.y;
  6597. var zw = quat.z * quat.w;
  6598. var zx = quat.z * quat.x;
  6599. var yw = quat.y * quat.w;
  6600. var yz = quat.y * quat.z;
  6601. var xw = quat.x * quat.w;
  6602. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6603. result.m[1] = 2.0 * (xy + zw);
  6604. result.m[2] = 2.0 * (zx - yw);
  6605. result.m[3] = 0.0;
  6606. result.m[4] = 2.0 * (xy - zw);
  6607. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6608. result.m[6] = 2.0 * (yz + xw);
  6609. result.m[7] = 0.0;
  6610. result.m[8] = 2.0 * (zx + yw);
  6611. result.m[9] = 2.0 * (yz - xw);
  6612. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6613. result.m[11] = 0.0;
  6614. result.m[12] = 0.0;
  6615. result.m[13] = 0.0;
  6616. result.m[14] = 0.0;
  6617. result.m[15] = 1.0;
  6618. result._markAsUpdated();
  6619. };
  6620. Matrix._tempQuaternion = new Quaternion();
  6621. Matrix._xAxis = Vector3.Zero();
  6622. Matrix._yAxis = Vector3.Zero();
  6623. Matrix._zAxis = Vector3.Zero();
  6624. Matrix._updateFlagSeed = 0;
  6625. Matrix._identityReadOnly = Matrix.Identity();
  6626. return Matrix;
  6627. }());
  6628. BABYLON.Matrix = Matrix;
  6629. var Plane = /** @class */ (function () {
  6630. /**
  6631. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6632. */
  6633. function Plane(a, b, c, d) {
  6634. this.normal = new Vector3(a, b, c);
  6635. this.d = d;
  6636. }
  6637. /**
  6638. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6639. */
  6640. Plane.prototype.asArray = function () {
  6641. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6642. };
  6643. // Methods
  6644. /**
  6645. * Returns a new plane copied from the current Plane.
  6646. */
  6647. Plane.prototype.clone = function () {
  6648. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6649. };
  6650. /**
  6651. * Returns the string "Plane".
  6652. */
  6653. Plane.prototype.getClassName = function () {
  6654. return "Plane";
  6655. };
  6656. /**
  6657. * Returns the Plane hash code.
  6658. */
  6659. Plane.prototype.getHashCode = function () {
  6660. var hash = this.normal.getHashCode();
  6661. hash = (hash * 397) ^ (this.d || 0);
  6662. return hash;
  6663. };
  6664. /**
  6665. * Normalize the current Plane in place.
  6666. * Returns the updated Plane.
  6667. */
  6668. Plane.prototype.normalize = function () {
  6669. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6670. var magnitude = 0.0;
  6671. if (norm !== 0) {
  6672. magnitude = 1.0 / norm;
  6673. }
  6674. this.normal.x *= magnitude;
  6675. this.normal.y *= magnitude;
  6676. this.normal.z *= magnitude;
  6677. this.d *= magnitude;
  6678. return this;
  6679. };
  6680. /**
  6681. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6682. */
  6683. Plane.prototype.transform = function (transformation) {
  6684. var transposedMatrix = Matrix.Transpose(transformation);
  6685. var x = this.normal.x;
  6686. var y = this.normal.y;
  6687. var z = this.normal.z;
  6688. var d = this.d;
  6689. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6690. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6691. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6692. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6693. return new Plane(normalX, normalY, normalZ, finalD);
  6694. };
  6695. /**
  6696. * Returns the dot product (float) of the point coordinates and the plane normal.
  6697. */
  6698. Plane.prototype.dotCoordinate = function (point) {
  6699. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6700. };
  6701. /**
  6702. * Updates the current Plane from the plane defined by the three given points.
  6703. * Returns the updated Plane.
  6704. */
  6705. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6706. var x1 = point2.x - point1.x;
  6707. var y1 = point2.y - point1.y;
  6708. var z1 = point2.z - point1.z;
  6709. var x2 = point3.x - point1.x;
  6710. var y2 = point3.y - point1.y;
  6711. var z2 = point3.z - point1.z;
  6712. var yz = (y1 * z2) - (z1 * y2);
  6713. var xz = (z1 * x2) - (x1 * z2);
  6714. var xy = (x1 * y2) - (y1 * x2);
  6715. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6716. var invPyth;
  6717. if (pyth !== 0) {
  6718. invPyth = 1.0 / pyth;
  6719. }
  6720. else {
  6721. invPyth = 0.0;
  6722. }
  6723. this.normal.x = yz * invPyth;
  6724. this.normal.y = xz * invPyth;
  6725. this.normal.z = xy * invPyth;
  6726. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6727. return this;
  6728. };
  6729. /**
  6730. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6731. */
  6732. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6733. var dot = Vector3.Dot(this.normal, direction);
  6734. return (dot <= epsilon);
  6735. };
  6736. /**
  6737. * Returns the signed distance (float) from the given point to the Plane.
  6738. */
  6739. Plane.prototype.signedDistanceTo = function (point) {
  6740. return Vector3.Dot(point, this.normal) + this.d;
  6741. };
  6742. // Statics
  6743. /**
  6744. * Returns a new Plane from the given array.
  6745. */
  6746. Plane.FromArray = function (array) {
  6747. return new Plane(array[0], array[1], array[2], array[3]);
  6748. };
  6749. /**
  6750. * Returns a new Plane defined by the three given points.
  6751. */
  6752. Plane.FromPoints = function (point1, point2, point3) {
  6753. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6754. result.copyFromPoints(point1, point2, point3);
  6755. return result;
  6756. };
  6757. /**
  6758. * Returns a new Plane the normal vector to this plane at the given origin point.
  6759. * Note : the vector "normal" is updated because normalized.
  6760. */
  6761. Plane.FromPositionAndNormal = function (origin, normal) {
  6762. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6763. normal.normalize();
  6764. result.normal = normal;
  6765. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6770. */
  6771. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6772. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6773. return Vector3.Dot(point, normal) + d;
  6774. };
  6775. return Plane;
  6776. }());
  6777. BABYLON.Plane = Plane;
  6778. var Viewport = /** @class */ (function () {
  6779. /**
  6780. * Creates a Viewport object located at (x, y) and sized (width, height).
  6781. */
  6782. function Viewport(x, y, width, height) {
  6783. this.x = x;
  6784. this.y = y;
  6785. this.width = width;
  6786. this.height = height;
  6787. }
  6788. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6789. if (renderWidthOrEngine.getRenderWidth) {
  6790. var engine = renderWidthOrEngine;
  6791. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6792. }
  6793. var renderWidth = renderWidthOrEngine;
  6794. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6795. };
  6796. /**
  6797. * Returns a new Viewport copied from the current one.
  6798. */
  6799. Viewport.prototype.clone = function () {
  6800. return new Viewport(this.x, this.y, this.width, this.height);
  6801. };
  6802. return Viewport;
  6803. }());
  6804. BABYLON.Viewport = Viewport;
  6805. var Frustum = /** @class */ (function () {
  6806. function Frustum() {
  6807. }
  6808. /**
  6809. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6810. */
  6811. Frustum.GetPlanes = function (transform) {
  6812. var frustumPlanes = [];
  6813. for (var index = 0; index < 6; index++) {
  6814. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6815. }
  6816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6817. return frustumPlanes;
  6818. };
  6819. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6820. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6821. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6822. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6823. frustumPlane.d = transform.m[15] + transform.m[14];
  6824. frustumPlane.normalize();
  6825. };
  6826. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6827. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6828. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6829. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6830. frustumPlane.d = transform.m[15] - transform.m[14];
  6831. frustumPlane.normalize();
  6832. };
  6833. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6834. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6835. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6836. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6837. frustumPlane.d = transform.m[15] + transform.m[12];
  6838. frustumPlane.normalize();
  6839. };
  6840. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6841. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6842. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6843. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6844. frustumPlane.d = transform.m[15] - transform.m[12];
  6845. frustumPlane.normalize();
  6846. };
  6847. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6848. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6849. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6850. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6851. frustumPlane.d = transform.m[15] - transform.m[13];
  6852. frustumPlane.normalize();
  6853. };
  6854. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6855. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6856. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6857. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6858. frustumPlane.d = transform.m[15] + transform.m[13];
  6859. frustumPlane.normalize();
  6860. };
  6861. /**
  6862. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6863. */
  6864. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6865. // Near
  6866. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6867. // Far
  6868. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6869. // Left
  6870. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6871. // Right
  6872. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6873. // Top
  6874. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6875. // Bottom
  6876. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6877. };
  6878. return Frustum;
  6879. }());
  6880. BABYLON.Frustum = Frustum;
  6881. /** Defines supported spaces */
  6882. var Space;
  6883. (function (Space) {
  6884. /** Local (object) space */
  6885. Space[Space["LOCAL"] = 0] = "LOCAL";
  6886. /** World space */
  6887. Space[Space["WORLD"] = 1] = "WORLD";
  6888. /** Bone space */
  6889. Space[Space["BONE"] = 2] = "BONE";
  6890. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6891. /** Defines the 3 main axes */
  6892. var Axis = /** @class */ (function () {
  6893. function Axis() {
  6894. }
  6895. /** X axis */
  6896. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6897. /** Y axis */
  6898. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6899. /** Z axis */
  6900. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6901. return Axis;
  6902. }());
  6903. BABYLON.Axis = Axis;
  6904. ;
  6905. var BezierCurve = /** @class */ (function () {
  6906. function BezierCurve() {
  6907. }
  6908. /**
  6909. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6910. */
  6911. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6912. // Extract X (which is equal to time here)
  6913. var f0 = 1 - 3 * x2 + 3 * x1;
  6914. var f1 = 3 * x2 - 6 * x1;
  6915. var f2 = 3 * x1;
  6916. var refinedT = t;
  6917. for (var i = 0; i < 5; i++) {
  6918. var refinedT2 = refinedT * refinedT;
  6919. var refinedT3 = refinedT2 * refinedT;
  6920. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6921. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6922. refinedT -= (x - t) * slope;
  6923. refinedT = Math.min(1, Math.max(0, refinedT));
  6924. }
  6925. // Resolve cubic bezier for the given x
  6926. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6927. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6928. Math.pow(refinedT, 3);
  6929. };
  6930. return BezierCurve;
  6931. }());
  6932. BABYLON.BezierCurve = BezierCurve;
  6933. /**
  6934. * Defines potential orientation for back face culling
  6935. */
  6936. var Orientation;
  6937. (function (Orientation) {
  6938. /**
  6939. * Clockwise
  6940. */
  6941. Orientation[Orientation["CW"] = 0] = "CW";
  6942. /** Counter clockwise */
  6943. Orientation[Orientation["CCW"] = 1] = "CCW";
  6944. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6945. /**
  6946. * Defines angle representation
  6947. */
  6948. var Angle = /** @class */ (function () {
  6949. /**
  6950. * Creates an Angle object of "radians" radians (float).
  6951. */
  6952. function Angle(radians) {
  6953. this._radians = radians;
  6954. if (this._radians < 0.0)
  6955. this._radians += (2.0 * Math.PI);
  6956. }
  6957. /**
  6958. * Get value in degrees
  6959. * @returns the Angle value in degrees (float)
  6960. */
  6961. Angle.prototype.degrees = function () {
  6962. return this._radians * 180.0 / Math.PI;
  6963. };
  6964. /**
  6965. * Get value in radians
  6966. * @returns the Angle value in radians (float)
  6967. */
  6968. Angle.prototype.radians = function () {
  6969. return this._radians;
  6970. };
  6971. /**
  6972. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6973. * @param a defines first vector
  6974. * @param b defines second vector
  6975. * @returns a new Angle
  6976. */
  6977. Angle.BetweenTwoPoints = function (a, b) {
  6978. var delta = b.subtract(a);
  6979. var theta = Math.atan2(delta.y, delta.x);
  6980. return new Angle(theta);
  6981. };
  6982. /**
  6983. * Gets a new Angle object from the given float in radians
  6984. * @param radians defines the angle value in radians
  6985. * @returns a new Angle
  6986. */
  6987. Angle.FromRadians = function (radians) {
  6988. return new Angle(radians);
  6989. };
  6990. /**
  6991. * Gets a new Angle object from the given float in degrees
  6992. * @param degrees defines the angle value in degrees
  6993. * @returns a new Angle
  6994. */
  6995. Angle.FromDegrees = function (degrees) {
  6996. return new Angle(degrees * Math.PI / 180.0);
  6997. };
  6998. return Angle;
  6999. }());
  7000. BABYLON.Angle = Angle;
  7001. var Arc2 = /** @class */ (function () {
  7002. /**
  7003. * Creates an Arc object from the three given points : start, middle and end.
  7004. */
  7005. function Arc2(startPoint, midPoint, endPoint) {
  7006. this.startPoint = startPoint;
  7007. this.midPoint = midPoint;
  7008. this.endPoint = endPoint;
  7009. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7010. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7011. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7012. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7013. 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);
  7014. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7015. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7016. var a1 = this.startAngle.degrees();
  7017. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7018. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7019. // angles correction
  7020. if (a2 - a1 > +180.0)
  7021. a2 -= 360.0;
  7022. if (a2 - a1 < -180.0)
  7023. a2 += 360.0;
  7024. if (a3 - a2 > +180.0)
  7025. a3 -= 360.0;
  7026. if (a3 - a2 < -180.0)
  7027. a3 += 360.0;
  7028. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7029. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7030. }
  7031. return Arc2;
  7032. }());
  7033. BABYLON.Arc2 = Arc2;
  7034. var Path2 = /** @class */ (function () {
  7035. /**
  7036. * Creates a Path2 object from the starting 2D coordinates x and y.
  7037. */
  7038. function Path2(x, y) {
  7039. this._points = new Array();
  7040. this._length = 0.0;
  7041. this.closed = false;
  7042. this._points.push(new Vector2(x, y));
  7043. }
  7044. /**
  7045. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7046. * Returns the updated Path2.
  7047. */
  7048. Path2.prototype.addLineTo = function (x, y) {
  7049. if (this.closed) {
  7050. return this;
  7051. }
  7052. var newPoint = new Vector2(x, y);
  7053. var previousPoint = this._points[this._points.length - 1];
  7054. this._points.push(newPoint);
  7055. this._length += newPoint.subtract(previousPoint).length();
  7056. return this;
  7057. };
  7058. /**
  7059. * 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.
  7060. * Returns the updated Path2.
  7061. */
  7062. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7063. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7064. if (this.closed) {
  7065. return this;
  7066. }
  7067. var startPoint = this._points[this._points.length - 1];
  7068. var midPoint = new Vector2(midX, midY);
  7069. var endPoint = new Vector2(endX, endY);
  7070. var arc = new Arc2(startPoint, midPoint, endPoint);
  7071. var increment = arc.angle.radians() / numberOfSegments;
  7072. if (arc.orientation === Orientation.CW)
  7073. increment *= -1;
  7074. var currentAngle = arc.startAngle.radians() + increment;
  7075. for (var i = 0; i < numberOfSegments; i++) {
  7076. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7077. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7078. this.addLineTo(x, y);
  7079. currentAngle += increment;
  7080. }
  7081. return this;
  7082. };
  7083. /**
  7084. * Closes the Path2.
  7085. * Returns the Path2.
  7086. */
  7087. Path2.prototype.close = function () {
  7088. this.closed = true;
  7089. return this;
  7090. };
  7091. /**
  7092. * Returns the Path2 total length (float).
  7093. */
  7094. Path2.prototype.length = function () {
  7095. var result = this._length;
  7096. if (!this.closed) {
  7097. var lastPoint = this._points[this._points.length - 1];
  7098. var firstPoint = this._points[0];
  7099. result += (firstPoint.subtract(lastPoint).length());
  7100. }
  7101. return result;
  7102. };
  7103. /**
  7104. * Returns the Path2 internal array of points.
  7105. */
  7106. Path2.prototype.getPoints = function () {
  7107. return this._points;
  7108. };
  7109. /**
  7110. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7111. */
  7112. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7113. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7114. return Vector2.Zero();
  7115. }
  7116. var lengthPosition = normalizedLengthPosition * this.length();
  7117. var previousOffset = 0;
  7118. for (var i = 0; i < this._points.length; i++) {
  7119. var j = (i + 1) % this._points.length;
  7120. var a = this._points[i];
  7121. var b = this._points[j];
  7122. var bToA = b.subtract(a);
  7123. var nextOffset = (bToA.length() + previousOffset);
  7124. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7125. var dir = bToA.normalize();
  7126. var localOffset = lengthPosition - previousOffset;
  7127. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7128. }
  7129. previousOffset = nextOffset;
  7130. }
  7131. return Vector2.Zero();
  7132. };
  7133. /**
  7134. * Returns a new Path2 starting at the coordinates (x, y).
  7135. */
  7136. Path2.StartingAt = function (x, y) {
  7137. return new Path2(x, y);
  7138. };
  7139. return Path2;
  7140. }());
  7141. BABYLON.Path2 = Path2;
  7142. var Path3D = /** @class */ (function () {
  7143. /**
  7144. * new Path3D(path, normal, raw)
  7145. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7146. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7147. * path : an array of Vector3, the curve axis of the Path3D
  7148. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7149. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7150. */
  7151. function Path3D(path, firstNormal, raw) {
  7152. if (firstNormal === void 0) { firstNormal = null; }
  7153. this.path = path;
  7154. this._curve = new Array();
  7155. this._distances = new Array();
  7156. this._tangents = new Array();
  7157. this._normals = new Array();
  7158. this._binormals = new Array();
  7159. for (var p = 0; p < path.length; p++) {
  7160. this._curve[p] = path[p].clone(); // hard copy
  7161. }
  7162. this._raw = raw || false;
  7163. this._compute(firstNormal);
  7164. }
  7165. /**
  7166. * Returns the Path3D array of successive Vector3 designing its curve.
  7167. */
  7168. Path3D.prototype.getCurve = function () {
  7169. return this._curve;
  7170. };
  7171. /**
  7172. * Returns an array populated with tangent vectors on each Path3D curve point.
  7173. */
  7174. Path3D.prototype.getTangents = function () {
  7175. return this._tangents;
  7176. };
  7177. /**
  7178. * Returns an array populated with normal vectors on each Path3D curve point.
  7179. */
  7180. Path3D.prototype.getNormals = function () {
  7181. return this._normals;
  7182. };
  7183. /**
  7184. * Returns an array populated with binormal vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getBinormals = function () {
  7187. return this._binormals;
  7188. };
  7189. /**
  7190. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7191. */
  7192. Path3D.prototype.getDistances = function () {
  7193. return this._distances;
  7194. };
  7195. /**
  7196. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7197. * Returns the same object updated.
  7198. */
  7199. Path3D.prototype.update = function (path, firstNormal) {
  7200. if (firstNormal === void 0) { firstNormal = null; }
  7201. for (var p = 0; p < path.length; p++) {
  7202. this._curve[p].x = path[p].x;
  7203. this._curve[p].y = path[p].y;
  7204. this._curve[p].z = path[p].z;
  7205. }
  7206. this._compute(firstNormal);
  7207. return this;
  7208. };
  7209. // private function compute() : computes tangents, normals and binormals
  7210. Path3D.prototype._compute = function (firstNormal) {
  7211. var l = this._curve.length;
  7212. // first and last tangents
  7213. this._tangents[0] = this._getFirstNonNullVector(0);
  7214. if (!this._raw) {
  7215. this._tangents[0].normalize();
  7216. }
  7217. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7218. if (!this._raw) {
  7219. this._tangents[l - 1].normalize();
  7220. }
  7221. // normals and binormals at first point : arbitrary vector with _normalVector()
  7222. var tg0 = this._tangents[0];
  7223. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7224. this._normals[0] = pp0;
  7225. if (!this._raw) {
  7226. this._normals[0].normalize();
  7227. }
  7228. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7229. if (!this._raw) {
  7230. this._binormals[0].normalize();
  7231. }
  7232. this._distances[0] = 0.0;
  7233. // normals and binormals : next points
  7234. var prev; // previous vector (segment)
  7235. var cur; // current vector (segment)
  7236. var curTang; // current tangent
  7237. // previous normal
  7238. var prevBinor; // previous binormal
  7239. for (var i = 1; i < l; i++) {
  7240. // tangents
  7241. prev = this._getLastNonNullVector(i);
  7242. if (i < l - 1) {
  7243. cur = this._getFirstNonNullVector(i);
  7244. this._tangents[i] = prev.add(cur);
  7245. this._tangents[i].normalize();
  7246. }
  7247. this._distances[i] = this._distances[i - 1] + prev.length();
  7248. // normals and binormals
  7249. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7250. curTang = this._tangents[i];
  7251. prevBinor = this._binormals[i - 1];
  7252. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7253. if (!this._raw) {
  7254. this._normals[i].normalize();
  7255. }
  7256. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7257. if (!this._raw) {
  7258. this._binormals[i].normalize();
  7259. }
  7260. }
  7261. };
  7262. // private function getFirstNonNullVector(index)
  7263. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7264. Path3D.prototype._getFirstNonNullVector = function (index) {
  7265. var i = 1;
  7266. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7267. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7268. i++;
  7269. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7270. }
  7271. return nNVector;
  7272. };
  7273. // private function getLastNonNullVector(index)
  7274. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7275. Path3D.prototype._getLastNonNullVector = function (index) {
  7276. var i = 1;
  7277. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7278. while (nLVector.length() === 0 && index > i + 1) {
  7279. i++;
  7280. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7281. }
  7282. return nLVector;
  7283. };
  7284. // private function normalVector(v0, vt, va) :
  7285. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7286. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7287. Path3D.prototype._normalVector = function (v0, vt, va) {
  7288. var normal0;
  7289. var tgl = vt.length();
  7290. if (tgl === 0.0) {
  7291. tgl = 1.0;
  7292. }
  7293. if (va === undefined || va === null) {
  7294. var point;
  7295. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7296. point = new Vector3(0.0, -1.0, 0.0);
  7297. }
  7298. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7299. point = new Vector3(1.0, 0.0, 0.0);
  7300. }
  7301. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7302. point = new Vector3(0.0, 0.0, 1.0);
  7303. }
  7304. else {
  7305. point = Vector3.Zero();
  7306. }
  7307. normal0 = Vector3.Cross(vt, point);
  7308. }
  7309. else {
  7310. normal0 = Vector3.Cross(vt, va);
  7311. Vector3.CrossToRef(normal0, vt, normal0);
  7312. }
  7313. normal0.normalize();
  7314. return normal0;
  7315. };
  7316. return Path3D;
  7317. }());
  7318. BABYLON.Path3D = Path3D;
  7319. var Curve3 = /** @class */ (function () {
  7320. /**
  7321. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7322. * A Curve3 is designed from a series of successive Vector3.
  7323. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7324. */
  7325. function Curve3(points) {
  7326. this._length = 0.0;
  7327. this._points = points;
  7328. this._length = this._computeLength(points);
  7329. }
  7330. /**
  7331. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7332. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7333. * @param v1 (Vector3) the control point
  7334. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7335. * @param nbPoints (integer) the wanted number of points in the curve
  7336. */
  7337. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7338. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7339. var bez = new Array();
  7340. var equation = function (t, val0, val1, val2) {
  7341. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7342. return res;
  7343. };
  7344. for (var i = 0; i <= nbPoints; i++) {
  7345. 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)));
  7346. }
  7347. return new Curve3(bez);
  7348. };
  7349. /**
  7350. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7351. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7352. * @param v1 (Vector3) the first control point
  7353. * @param v2 (Vector3) the second control point
  7354. * @param v3 (Vector3) the end point of the Cubic Bezier
  7355. * @param nbPoints (integer) the wanted number of points in the curve
  7356. */
  7357. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7358. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7359. var bez = new Array();
  7360. var equation = function (t, val0, val1, val2, val3) {
  7361. 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;
  7362. return res;
  7363. };
  7364. for (var i = 0; i <= nbPoints; i++) {
  7365. 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)));
  7366. }
  7367. return new Curve3(bez);
  7368. };
  7369. /**
  7370. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7371. * @param p1 (Vector3) the origin point of the Hermite Spline
  7372. * @param t1 (Vector3) the tangent vector at the origin point
  7373. * @param p2 (Vector3) the end point of the Hermite Spline
  7374. * @param t2 (Vector3) the tangent vector at the end point
  7375. * @param nbPoints (integer) the wanted number of points in the curve
  7376. */
  7377. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7378. var hermite = new Array();
  7379. var step = 1.0 / nbPoints;
  7380. for (var i = 0; i <= nbPoints; i++) {
  7381. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7382. }
  7383. return new Curve3(hermite);
  7384. };
  7385. /**
  7386. * Returns a Curve3 object along a CatmullRom Spline curve :
  7387. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7388. * @param nbPoints (integer) the wanted number of points between each curve control points
  7389. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7390. */
  7391. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7392. var catmullRom = new Array();
  7393. var step = 1.0 / nbPoints;
  7394. var amount = 0.0;
  7395. if (closed) {
  7396. var pointsCount = points.length;
  7397. for (var i = 0; i < pointsCount; i++) {
  7398. amount = 0;
  7399. for (var c = 0; c < nbPoints; c++) {
  7400. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7401. amount += step;
  7402. }
  7403. }
  7404. catmullRom.push(catmullRom[0]);
  7405. }
  7406. else {
  7407. var totalPoints = new Array();
  7408. totalPoints.push(points[0].clone());
  7409. Array.prototype.push.apply(totalPoints, points);
  7410. totalPoints.push(points[points.length - 1].clone());
  7411. for (var i = 0; i < totalPoints.length - 3; i++) {
  7412. amount = 0;
  7413. for (var c = 0; c < nbPoints; c++) {
  7414. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7415. amount += step;
  7416. }
  7417. }
  7418. i--;
  7419. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7420. }
  7421. return new Curve3(catmullRom);
  7422. };
  7423. /**
  7424. * Returns the Curve3 stored array of successive Vector3
  7425. */
  7426. Curve3.prototype.getPoints = function () {
  7427. return this._points;
  7428. };
  7429. /**
  7430. * Returns the computed length (float) of the curve.
  7431. */
  7432. Curve3.prototype.length = function () {
  7433. return this._length;
  7434. };
  7435. /**
  7436. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7437. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7438. * curveA and curveB keep unchanged.
  7439. */
  7440. Curve3.prototype.continue = function (curve) {
  7441. var lastPoint = this._points[this._points.length - 1];
  7442. var continuedPoints = this._points.slice();
  7443. var curvePoints = curve.getPoints();
  7444. for (var i = 1; i < curvePoints.length; i++) {
  7445. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7446. }
  7447. var continuedCurve = new Curve3(continuedPoints);
  7448. return continuedCurve;
  7449. };
  7450. Curve3.prototype._computeLength = function (path) {
  7451. var l = 0;
  7452. for (var i = 1; i < path.length; i++) {
  7453. l += (path[i].subtract(path[i - 1])).length();
  7454. }
  7455. return l;
  7456. };
  7457. return Curve3;
  7458. }());
  7459. BABYLON.Curve3 = Curve3;
  7460. // Vertex formats
  7461. var PositionNormalVertex = /** @class */ (function () {
  7462. function PositionNormalVertex(position, normal) {
  7463. if (position === void 0) { position = Vector3.Zero(); }
  7464. if (normal === void 0) { normal = Vector3.Up(); }
  7465. this.position = position;
  7466. this.normal = normal;
  7467. }
  7468. PositionNormalVertex.prototype.clone = function () {
  7469. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7470. };
  7471. return PositionNormalVertex;
  7472. }());
  7473. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7474. var PositionNormalTextureVertex = /** @class */ (function () {
  7475. function PositionNormalTextureVertex(position, normal, uv) {
  7476. if (position === void 0) { position = Vector3.Zero(); }
  7477. if (normal === void 0) { normal = Vector3.Up(); }
  7478. if (uv === void 0) { uv = Vector2.Zero(); }
  7479. this.position = position;
  7480. this.normal = normal;
  7481. this.uv = uv;
  7482. }
  7483. PositionNormalTextureVertex.prototype.clone = function () {
  7484. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7485. };
  7486. return PositionNormalTextureVertex;
  7487. }());
  7488. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7489. // Temporary pre-allocated objects for engine internal use
  7490. // usage in any internal function :
  7491. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7492. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7493. var Tmp = /** @class */ (function () {
  7494. function Tmp() {
  7495. }
  7496. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7497. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7498. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7499. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7500. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7501. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7502. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero(),
  7505. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7506. return Tmp;
  7507. }());
  7508. BABYLON.Tmp = Tmp;
  7509. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7510. var MathTmp = /** @class */ (function () {
  7511. function MathTmp() {
  7512. }
  7513. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7514. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7515. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7516. return MathTmp;
  7517. }());
  7518. })(BABYLON || (BABYLON = {}));
  7519. //# sourceMappingURL=babylon.math.js.map
  7520. var BABYLON;
  7521. (function (BABYLON) {
  7522. var Scalar = /** @class */ (function () {
  7523. function Scalar() {
  7524. }
  7525. /**
  7526. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7527. */
  7528. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7529. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7530. var num = a - b;
  7531. return -epsilon <= num && num <= epsilon;
  7532. };
  7533. /**
  7534. * Returns a string : the upper case translation of the number i to hexadecimal.
  7535. */
  7536. Scalar.ToHex = function (i) {
  7537. var str = i.toString(16);
  7538. if (i <= 15) {
  7539. return ("0" + str).toUpperCase();
  7540. }
  7541. return str.toUpperCase();
  7542. };
  7543. /**
  7544. * Returns -1 if value is negative and +1 is value is positive.
  7545. * Returns the value itself if it's equal to zero.
  7546. */
  7547. Scalar.Sign = function (value) {
  7548. value = +value; // convert to a number
  7549. if (value === 0 || isNaN(value))
  7550. return value;
  7551. return value > 0 ? 1 : -1;
  7552. };
  7553. /**
  7554. * Returns the value itself if it's between min and max.
  7555. * Returns min if the value is lower than min.
  7556. * Returns max if the value is greater than max.
  7557. */
  7558. Scalar.Clamp = function (value, min, max) {
  7559. if (min === void 0) { min = 0; }
  7560. if (max === void 0) { max = 1; }
  7561. return Math.min(max, Math.max(min, value));
  7562. };
  7563. /**
  7564. * Returns the log2 of value.
  7565. */
  7566. Scalar.Log2 = function (value) {
  7567. return Math.log(value) * Math.LOG2E;
  7568. };
  7569. /**
  7570. * Loops the value, so that it is never larger than length and never smaller than 0.
  7571. *
  7572. * This is similar to the modulo operator but it works with floating point numbers.
  7573. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7574. * With t = 5 and length = 2.5, the result would be 0.0.
  7575. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7576. */
  7577. Scalar.Repeat = function (value, length) {
  7578. return value - Math.floor(value / length) * length;
  7579. };
  7580. /**
  7581. * Normalize the value between 0.0 and 1.0 using min and max values
  7582. */
  7583. Scalar.Normalize = function (value, min, max) {
  7584. return (value - min) / (max - min);
  7585. };
  7586. /**
  7587. * Denormalize the value from 0.0 and 1.0 using min and max values
  7588. */
  7589. Scalar.Denormalize = function (normalized, min, max) {
  7590. return (normalized * (max - min) + min);
  7591. };
  7592. /**
  7593. * Calculates the shortest difference between two given angles given in degrees.
  7594. */
  7595. Scalar.DeltaAngle = function (current, target) {
  7596. var num = Scalar.Repeat(target - current, 360.0);
  7597. if (num > 180.0) {
  7598. num -= 360.0;
  7599. }
  7600. return num;
  7601. };
  7602. /**
  7603. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7604. *
  7605. * The returned value will move back and forth between 0 and length
  7606. */
  7607. Scalar.PingPong = function (tx, length) {
  7608. var t = Scalar.Repeat(tx, length * 2.0);
  7609. return length - Math.abs(t - length);
  7610. };
  7611. /**
  7612. * Interpolates between min and max with smoothing at the limits.
  7613. *
  7614. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7615. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7616. */
  7617. Scalar.SmoothStep = function (from, to, tx) {
  7618. var t = Scalar.Clamp(tx);
  7619. t = -2.0 * t * t * t + 3.0 * t * t;
  7620. return to * t + from * (1.0 - t);
  7621. };
  7622. /**
  7623. * Moves a value current towards target.
  7624. *
  7625. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7626. * Negative values of maxDelta pushes the value away from target.
  7627. */
  7628. Scalar.MoveTowards = function (current, target, maxDelta) {
  7629. var result = 0;
  7630. if (Math.abs(target - current) <= maxDelta) {
  7631. result = target;
  7632. }
  7633. else {
  7634. result = current + Scalar.Sign(target - current) * maxDelta;
  7635. }
  7636. return result;
  7637. };
  7638. /**
  7639. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7640. *
  7641. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7642. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7643. */
  7644. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7645. var num = Scalar.DeltaAngle(current, target);
  7646. var result = 0;
  7647. if (-maxDelta < num && num < maxDelta) {
  7648. result = target;
  7649. }
  7650. else {
  7651. target = current + num;
  7652. result = Scalar.MoveTowards(current, target, maxDelta);
  7653. }
  7654. return result;
  7655. };
  7656. /**
  7657. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7658. */
  7659. Scalar.Lerp = function (start, end, amount) {
  7660. return start + ((end - start) * amount);
  7661. };
  7662. /**
  7663. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7664. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7665. */
  7666. Scalar.LerpAngle = function (start, end, amount) {
  7667. var num = Scalar.Repeat(end - start, 360.0);
  7668. if (num > 180.0) {
  7669. num -= 360.0;
  7670. }
  7671. return start + num * Scalar.Clamp(amount);
  7672. };
  7673. /**
  7674. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7675. */
  7676. Scalar.InverseLerp = function (a, b, value) {
  7677. var result = 0;
  7678. if (a != b) {
  7679. result = Scalar.Clamp((value - a) / (b - a));
  7680. }
  7681. else {
  7682. result = 0.0;
  7683. }
  7684. return result;
  7685. };
  7686. /**
  7687. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7688. */
  7689. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7690. var squared = amount * amount;
  7691. var cubed = amount * squared;
  7692. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7693. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7694. var part3 = (cubed - (2.0 * squared)) + amount;
  7695. var part4 = cubed - squared;
  7696. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7697. };
  7698. /**
  7699. * Returns a random float number between and min and max values
  7700. */
  7701. Scalar.RandomRange = function (min, max) {
  7702. if (min === max)
  7703. return min;
  7704. return ((Math.random() * (max - min)) + min);
  7705. };
  7706. /**
  7707. * This function returns percentage of a number in a given range.
  7708. *
  7709. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7710. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7711. */
  7712. Scalar.RangeToPercent = function (number, min, max) {
  7713. return ((number - min) / (max - min));
  7714. };
  7715. /**
  7716. * This function returns number that corresponds to the percentage in a given range.
  7717. *
  7718. * PercentToRange(0.34,0,100) will return 34.
  7719. */
  7720. Scalar.PercentToRange = function (percent, min, max) {
  7721. return ((max - min) * percent + min);
  7722. };
  7723. /**
  7724. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7725. * @param angle The angle to normalize in radian.
  7726. * @return The converted angle.
  7727. */
  7728. Scalar.NormalizeRadians = function (angle) {
  7729. // More precise but slower version kept for reference.
  7730. // angle = angle % Tools.TwoPi;
  7731. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7732. //if (angle > Math.PI) {
  7733. // angle -= Tools.TwoPi;
  7734. //}
  7735. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7736. return angle;
  7737. };
  7738. /**
  7739. * Two pi constants convenient for computation.
  7740. */
  7741. Scalar.TwoPi = Math.PI * 2;
  7742. return Scalar;
  7743. }());
  7744. BABYLON.Scalar = Scalar;
  7745. })(BABYLON || (BABYLON = {}));
  7746. //# sourceMappingURL=babylon.math.scalar.js.map
  7747. //# sourceMappingURL=babylon.mixins.js.map
  7748. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7749. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7750. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7751. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7752. //# sourceMappingURL=babylon.webgl2.js.map
  7753. var BABYLON;
  7754. (function (BABYLON) {
  7755. var __decoratorInitialStore = {};
  7756. var __mergedStore = {};
  7757. var _copySource = function (creationFunction, source, instanciate) {
  7758. var destination = creationFunction();
  7759. // Tags
  7760. if (BABYLON.Tags) {
  7761. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7762. }
  7763. var classStore = getMergedStore(destination);
  7764. // Properties
  7765. for (var property in classStore) {
  7766. var propertyDescriptor = classStore[property];
  7767. var sourceProperty = source[property];
  7768. var propertyType = propertyDescriptor.type;
  7769. if (sourceProperty !== undefined && sourceProperty !== null) {
  7770. switch (propertyType) {
  7771. case 0: // Value
  7772. case 6: // Mesh reference
  7773. case 11: // Camera reference
  7774. destination[property] = sourceProperty;
  7775. break;
  7776. case 1: // Texture
  7777. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7778. break;
  7779. case 2: // Color3
  7780. case 3: // FresnelParameters
  7781. case 4: // Vector2
  7782. case 5: // Vector3
  7783. case 7: // Color Curves
  7784. case 10: // Quaternion
  7785. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7786. break;
  7787. }
  7788. }
  7789. }
  7790. return destination;
  7791. };
  7792. function getDirectStore(target) {
  7793. var classKey = target.getClassName();
  7794. if (!__decoratorInitialStore[classKey]) {
  7795. __decoratorInitialStore[classKey] = {};
  7796. }
  7797. return __decoratorInitialStore[classKey];
  7798. }
  7799. /**
  7800. * Return the list of properties flagged as serializable
  7801. * @param target: host object
  7802. */
  7803. function getMergedStore(target) {
  7804. var classKey = target.getClassName();
  7805. if (__mergedStore[classKey]) {
  7806. return __mergedStore[classKey];
  7807. }
  7808. __mergedStore[classKey] = {};
  7809. var store = __mergedStore[classKey];
  7810. var currentTarget = target;
  7811. var currentKey = classKey;
  7812. while (currentKey) {
  7813. var initialStore = __decoratorInitialStore[currentKey];
  7814. for (var property in initialStore) {
  7815. store[property] = initialStore[property];
  7816. }
  7817. var parent_1 = void 0;
  7818. var done = false;
  7819. do {
  7820. parent_1 = Object.getPrototypeOf(currentTarget);
  7821. if (!parent_1.getClassName) {
  7822. done = true;
  7823. break;
  7824. }
  7825. if (parent_1.getClassName() !== currentKey) {
  7826. break;
  7827. }
  7828. currentTarget = parent_1;
  7829. } while (parent_1);
  7830. if (done) {
  7831. break;
  7832. }
  7833. currentKey = parent_1.getClassName();
  7834. currentTarget = parent_1;
  7835. }
  7836. return store;
  7837. }
  7838. function generateSerializableMember(type, sourceName) {
  7839. return function (target, propertyKey) {
  7840. var classStore = getDirectStore(target);
  7841. if (!classStore[propertyKey]) {
  7842. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7843. }
  7844. };
  7845. }
  7846. function generateExpandMember(setCallback, targetKey) {
  7847. if (targetKey === void 0) { targetKey = null; }
  7848. return function (target, propertyKey) {
  7849. var key = targetKey || ("_" + propertyKey);
  7850. Object.defineProperty(target, propertyKey, {
  7851. get: function () {
  7852. return this[key];
  7853. },
  7854. set: function (value) {
  7855. if (this[key] === value) {
  7856. return;
  7857. }
  7858. this[key] = value;
  7859. target[setCallback].apply(this);
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. };
  7865. }
  7866. function expandToProperty(callback, targetKey) {
  7867. if (targetKey === void 0) { targetKey = null; }
  7868. return generateExpandMember(callback, targetKey);
  7869. }
  7870. BABYLON.expandToProperty = expandToProperty;
  7871. function serialize(sourceName) {
  7872. return generateSerializableMember(0, sourceName); // value member
  7873. }
  7874. BABYLON.serialize = serialize;
  7875. function serializeAsTexture(sourceName) {
  7876. return generateSerializableMember(1, sourceName); // texture member
  7877. }
  7878. BABYLON.serializeAsTexture = serializeAsTexture;
  7879. function serializeAsColor3(sourceName) {
  7880. return generateSerializableMember(2, sourceName); // color3 member
  7881. }
  7882. BABYLON.serializeAsColor3 = serializeAsColor3;
  7883. function serializeAsFresnelParameters(sourceName) {
  7884. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7885. }
  7886. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7887. function serializeAsVector2(sourceName) {
  7888. return generateSerializableMember(4, sourceName); // vector2 member
  7889. }
  7890. BABYLON.serializeAsVector2 = serializeAsVector2;
  7891. function serializeAsVector3(sourceName) {
  7892. return generateSerializableMember(5, sourceName); // vector3 member
  7893. }
  7894. BABYLON.serializeAsVector3 = serializeAsVector3;
  7895. function serializeAsMeshReference(sourceName) {
  7896. return generateSerializableMember(6, sourceName); // mesh reference member
  7897. }
  7898. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7899. function serializeAsColorCurves(sourceName) {
  7900. return generateSerializableMember(7, sourceName); // color curves
  7901. }
  7902. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7903. function serializeAsColor4(sourceName) {
  7904. return generateSerializableMember(8, sourceName); // color 4
  7905. }
  7906. BABYLON.serializeAsColor4 = serializeAsColor4;
  7907. function serializeAsImageProcessingConfiguration(sourceName) {
  7908. return generateSerializableMember(9, sourceName); // image processing
  7909. }
  7910. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7911. function serializeAsQuaternion(sourceName) {
  7912. return generateSerializableMember(10, sourceName); // quaternion member
  7913. }
  7914. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7915. /**
  7916. * Decorator used to define property that can be serialized as reference to a camera
  7917. * @param sourceName defines the name of the property to decorate
  7918. */
  7919. function serializeAsCameraReference(sourceName) {
  7920. return generateSerializableMember(11, sourceName); // camera reference member
  7921. }
  7922. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7923. var SerializationHelper = /** @class */ (function () {
  7924. function SerializationHelper() {
  7925. }
  7926. SerializationHelper.Serialize = function (entity, serializationObject) {
  7927. if (!serializationObject) {
  7928. serializationObject = {};
  7929. }
  7930. // Tags
  7931. if (BABYLON.Tags) {
  7932. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7933. }
  7934. var serializedProperties = getMergedStore(entity);
  7935. // Properties
  7936. for (var property in serializedProperties) {
  7937. var propertyDescriptor = serializedProperties[property];
  7938. var targetPropertyName = propertyDescriptor.sourceName || property;
  7939. var propertyType = propertyDescriptor.type;
  7940. var sourceProperty = entity[property];
  7941. if (sourceProperty !== undefined && sourceProperty !== null) {
  7942. switch (propertyType) {
  7943. case 0: // Value
  7944. serializationObject[targetPropertyName] = sourceProperty;
  7945. break;
  7946. case 1: // Texture
  7947. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7948. break;
  7949. case 2: // Color3
  7950. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7951. break;
  7952. case 3: // FresnelParameters
  7953. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7954. break;
  7955. case 4: // Vector2
  7956. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7957. break;
  7958. case 5: // Vector3
  7959. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7960. break;
  7961. case 6: // Mesh reference
  7962. serializationObject[targetPropertyName] = sourceProperty.id;
  7963. break;
  7964. case 7: // Color Curves
  7965. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7966. break;
  7967. case 8: // Color 4
  7968. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7969. break;
  7970. case 9: // Image Processing
  7971. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7972. break;
  7973. case 10: // Quaternion
  7974. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7975. break;
  7976. case 11: // Camera reference
  7977. serializationObject[targetPropertyName] = sourceProperty.id;
  7978. break;
  7979. }
  7980. }
  7981. }
  7982. return serializationObject;
  7983. };
  7984. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7985. if (rootUrl === void 0) { rootUrl = null; }
  7986. var destination = creationFunction();
  7987. if (!rootUrl) {
  7988. rootUrl = "";
  7989. }
  7990. // Tags
  7991. if (BABYLON.Tags) {
  7992. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7993. }
  7994. var classStore = getMergedStore(destination);
  7995. // Properties
  7996. for (var property in classStore) {
  7997. var propertyDescriptor = classStore[property];
  7998. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7999. var propertyType = propertyDescriptor.type;
  8000. if (sourceProperty !== undefined && sourceProperty !== null) {
  8001. var dest = destination;
  8002. switch (propertyType) {
  8003. case 0: // Value
  8004. dest[property] = sourceProperty;
  8005. break;
  8006. case 1: // Texture
  8007. if (scene) {
  8008. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8009. }
  8010. break;
  8011. case 2: // Color3
  8012. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8013. break;
  8014. case 3: // FresnelParameters
  8015. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8016. break;
  8017. case 4: // Vector2
  8018. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8019. break;
  8020. case 5: // Vector3
  8021. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8022. break;
  8023. case 6: // Mesh reference
  8024. if (scene) {
  8025. dest[property] = scene.getLastMeshByID(sourceProperty);
  8026. }
  8027. break;
  8028. case 7: // Color Curves
  8029. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8030. break;
  8031. case 8: // Color 4
  8032. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8033. break;
  8034. case 9: // Image Processing
  8035. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8036. break;
  8037. case 10: // Quaternion
  8038. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8039. break;
  8040. case 11: // Camera reference
  8041. if (scene) {
  8042. dest[property] = scene.getCameraByID(sourceProperty);
  8043. }
  8044. break;
  8045. }
  8046. }
  8047. }
  8048. return destination;
  8049. };
  8050. SerializationHelper.Clone = function (creationFunction, source) {
  8051. return _copySource(creationFunction, source, false);
  8052. };
  8053. SerializationHelper.Instanciate = function (creationFunction, source) {
  8054. return _copySource(creationFunction, source, true);
  8055. };
  8056. return SerializationHelper;
  8057. }());
  8058. BABYLON.SerializationHelper = SerializationHelper;
  8059. })(BABYLON || (BABYLON = {}));
  8060. //# sourceMappingURL=babylon.decorators.js.map
  8061. var BABYLON;
  8062. (function (BABYLON) {
  8063. /**
  8064. * Wrapper class for promise with external resolve and reject.
  8065. */
  8066. var Deferred = /** @class */ (function () {
  8067. /**
  8068. * Constructor for this deferred object.
  8069. */
  8070. function Deferred() {
  8071. var _this = this;
  8072. this.promise = new Promise(function (resolve, reject) {
  8073. _this._resolve = resolve;
  8074. _this._reject = reject;
  8075. });
  8076. }
  8077. Object.defineProperty(Deferred.prototype, "resolve", {
  8078. /**
  8079. * The resolve method of the promise associated with this deferred object.
  8080. */
  8081. get: function () {
  8082. return this._resolve;
  8083. },
  8084. enumerable: true,
  8085. configurable: true
  8086. });
  8087. Object.defineProperty(Deferred.prototype, "reject", {
  8088. /**
  8089. * The reject method of the promise associated with this deferred object.
  8090. */
  8091. get: function () {
  8092. return this._reject;
  8093. },
  8094. enumerable: true,
  8095. configurable: true
  8096. });
  8097. return Deferred;
  8098. }());
  8099. BABYLON.Deferred = Deferred;
  8100. })(BABYLON || (BABYLON = {}));
  8101. //# sourceMappingURL=babylon.deferred.js.map
  8102. var BABYLON;
  8103. (function (BABYLON) {
  8104. /**
  8105. * A class serves as a medium between the observable and its observers
  8106. */
  8107. var EventState = /** @class */ (function () {
  8108. /**
  8109. * Create a new EventState
  8110. * @param mask defines the mask associated with this state
  8111. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8112. * @param target defines the original target of the state
  8113. * @param currentTarget defines the current target of the state
  8114. */
  8115. function EventState(mask, skipNextObservers, target, currentTarget) {
  8116. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8117. this.initalize(mask, skipNextObservers, target, currentTarget);
  8118. }
  8119. /**
  8120. * Initialize the current event state
  8121. * @param mask defines the mask associated with this state
  8122. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8123. * @param target defines the original target of the state
  8124. * @param currentTarget defines the current target of the state
  8125. * @returns the current event state
  8126. */
  8127. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8128. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8129. this.mask = mask;
  8130. this.skipNextObservers = skipNextObservers;
  8131. this.target = target;
  8132. this.currentTarget = currentTarget;
  8133. return this;
  8134. };
  8135. return EventState;
  8136. }());
  8137. BABYLON.EventState = EventState;
  8138. /**
  8139. * Represent an Observer registered to a given Observable object.
  8140. */
  8141. var Observer = /** @class */ (function () {
  8142. /**
  8143. * Creates a new observer
  8144. * @param callback defines the callback to call when the observer is notified
  8145. * @param mask defines the mask of the observer (used to filter notifications)
  8146. * @param scope defines the current scope used to restore the JS context
  8147. */
  8148. function Observer(
  8149. /**
  8150. * Defines the callback to call when the observer is notified
  8151. */
  8152. callback,
  8153. /**
  8154. * Defines the mask of the observer (used to filter notifications)
  8155. */
  8156. mask,
  8157. /**
  8158. * Defines the current scope used to restore the JS context
  8159. */
  8160. scope) {
  8161. if (scope === void 0) { scope = null; }
  8162. this.callback = callback;
  8163. this.mask = mask;
  8164. this.scope = scope;
  8165. /** @hidden */
  8166. this._willBeUnregistered = false;
  8167. /**
  8168. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8169. */
  8170. this.unregisterOnNextCall = false;
  8171. }
  8172. return Observer;
  8173. }());
  8174. BABYLON.Observer = Observer;
  8175. /**
  8176. * Represent a list of observers registered to multiple Observables object.
  8177. */
  8178. var MultiObserver = /** @class */ (function () {
  8179. function MultiObserver() {
  8180. }
  8181. /**
  8182. * Release associated resources
  8183. */
  8184. MultiObserver.prototype.dispose = function () {
  8185. if (this._observers && this._observables) {
  8186. for (var index = 0; index < this._observers.length; index++) {
  8187. this._observables[index].remove(this._observers[index]);
  8188. }
  8189. }
  8190. this._observers = null;
  8191. this._observables = null;
  8192. };
  8193. /**
  8194. * Raise a callback when one of the observable will notify
  8195. * @param observables defines a list of observables to watch
  8196. * @param callback defines the callback to call on notification
  8197. * @param mask defines the mask used to filter notifications
  8198. * @param scope defines the current scope used to restore the JS context
  8199. * @returns the new MultiObserver
  8200. */
  8201. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8202. if (mask === void 0) { mask = -1; }
  8203. if (scope === void 0) { scope = null; }
  8204. var result = new MultiObserver();
  8205. result._observers = new Array();
  8206. result._observables = observables;
  8207. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8208. var observable = observables_1[_i];
  8209. var observer = observable.add(callback, mask, false, scope);
  8210. if (observer) {
  8211. result._observers.push(observer);
  8212. }
  8213. }
  8214. return result;
  8215. };
  8216. return MultiObserver;
  8217. }());
  8218. BABYLON.MultiObserver = MultiObserver;
  8219. /**
  8220. * The Observable class is a simple implementation of the Observable pattern.
  8221. *
  8222. * 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.
  8223. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8224. * 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).
  8225. * 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.
  8226. */
  8227. var Observable = /** @class */ (function () {
  8228. /**
  8229. * Creates a new observable
  8230. * @param onObserverAdded defines a callback to call when a new observer is added
  8231. */
  8232. function Observable(onObserverAdded) {
  8233. this._observers = new Array();
  8234. this._eventState = new EventState(0);
  8235. if (onObserverAdded) {
  8236. this._onObserverAdded = onObserverAdded;
  8237. }
  8238. }
  8239. /**
  8240. * Create a new Observer with the specified callback
  8241. * @param callback the callback that will be executed for that Observer
  8242. * @param mask the mask used to filter observers
  8243. * @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.
  8244. * @param scope optional scope for the callback to be called from
  8245. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8246. * @returns the new observer created for the callback
  8247. */
  8248. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8249. if (mask === void 0) { mask = -1; }
  8250. if (insertFirst === void 0) { insertFirst = false; }
  8251. if (scope === void 0) { scope = null; }
  8252. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8253. if (!callback) {
  8254. return null;
  8255. }
  8256. var observer = new Observer(callback, mask, scope);
  8257. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8258. if (insertFirst) {
  8259. this._observers.unshift(observer);
  8260. }
  8261. else {
  8262. this._observers.push(observer);
  8263. }
  8264. if (this._onObserverAdded) {
  8265. this._onObserverAdded(observer);
  8266. }
  8267. return observer;
  8268. };
  8269. /**
  8270. * Create a new Observer with the specified callback and unregisters after the next notification
  8271. * @param callback the callback that will be executed for that Observer
  8272. * @returns the new observer created for the callback
  8273. */
  8274. Observable.prototype.addOnce = function (callback) {
  8275. return this.add(callback, undefined, undefined, undefined, true);
  8276. };
  8277. /**
  8278. * Remove an Observer from the Observable object
  8279. * @param observer the instance of the Observer to remove
  8280. * @returns false if it doesn't belong to this Observable
  8281. */
  8282. Observable.prototype.remove = function (observer) {
  8283. if (!observer) {
  8284. return false;
  8285. }
  8286. var index = this._observers.indexOf(observer);
  8287. if (index !== -1) {
  8288. this._observers.splice(index, 1);
  8289. return true;
  8290. }
  8291. return false;
  8292. };
  8293. /**
  8294. * Remove a callback from the Observable object
  8295. * @param callback the callback to remove
  8296. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8297. * @returns false if it doesn't belong to this Observable
  8298. */
  8299. Observable.prototype.removeCallback = function (callback, scope) {
  8300. for (var index = 0; index < this._observers.length; index++) {
  8301. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8302. this._observers.splice(index, 1);
  8303. return true;
  8304. }
  8305. }
  8306. return false;
  8307. };
  8308. Observable.prototype._deferUnregister = function (observer) {
  8309. var _this = this;
  8310. observer.unregisterOnNextCall = false;
  8311. observer._willBeUnregistered = true;
  8312. BABYLON.Tools.SetImmediate(function () {
  8313. _this.remove(observer);
  8314. });
  8315. };
  8316. /**
  8317. * Notify all Observers by calling their respective callback with the given data
  8318. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8319. * @param eventData defines the data to send to all observers
  8320. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8321. * @param target defines the original target of the state
  8322. * @param currentTarget defines the current target of the state
  8323. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8324. */
  8325. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8326. if (mask === void 0) { mask = -1; }
  8327. if (!this._observers.length) {
  8328. return true;
  8329. }
  8330. var state = this._eventState;
  8331. state.mask = mask;
  8332. state.target = target;
  8333. state.currentTarget = currentTarget;
  8334. state.skipNextObservers = false;
  8335. state.lastReturnValue = eventData;
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs._willBeUnregistered) {
  8339. continue;
  8340. }
  8341. if (obs.mask & mask) {
  8342. if (obs.scope) {
  8343. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8344. }
  8345. else {
  8346. state.lastReturnValue = obs.callback(eventData, state);
  8347. }
  8348. if (obs.unregisterOnNextCall) {
  8349. this._deferUnregister(obs);
  8350. }
  8351. }
  8352. if (state.skipNextObservers) {
  8353. return false;
  8354. }
  8355. }
  8356. return true;
  8357. };
  8358. /**
  8359. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8360. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8361. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8362. * and it is crucial that all callbacks will be executed.
  8363. * The order of the callbacks is kept, callbacks are not executed parallel.
  8364. *
  8365. * @param eventData The data to be sent to each callback
  8366. * @param mask is used to filter observers defaults to -1
  8367. * @param target defines the callback target (see EventState)
  8368. * @param currentTarget defines he current object in the bubbling phase
  8369. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8370. */
  8371. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8372. var _this = this;
  8373. if (mask === void 0) { mask = -1; }
  8374. // create an empty promise
  8375. var p = Promise.resolve(eventData);
  8376. // no observers? return this promise.
  8377. if (!this._observers.length) {
  8378. return p;
  8379. }
  8380. var state = this._eventState;
  8381. state.mask = mask;
  8382. state.target = target;
  8383. state.currentTarget = currentTarget;
  8384. state.skipNextObservers = false;
  8385. // execute one callback after another (not using Promise.all, the order is important)
  8386. this._observers.forEach(function (obs) {
  8387. if (state.skipNextObservers) {
  8388. return;
  8389. }
  8390. if (obs._willBeUnregistered) {
  8391. return;
  8392. }
  8393. if (obs.mask & mask) {
  8394. if (obs.scope) {
  8395. p = p.then(function (lastReturnedValue) {
  8396. state.lastReturnValue = lastReturnedValue;
  8397. return obs.callback.apply(obs.scope, [eventData, state]);
  8398. });
  8399. }
  8400. else {
  8401. p = p.then(function (lastReturnedValue) {
  8402. state.lastReturnValue = lastReturnedValue;
  8403. return obs.callback(eventData, state);
  8404. });
  8405. }
  8406. if (obs.unregisterOnNextCall) {
  8407. _this._deferUnregister(obs);
  8408. }
  8409. }
  8410. });
  8411. // return the eventData
  8412. return p.then(function () { return eventData; });
  8413. };
  8414. /**
  8415. * Notify a specific observer
  8416. * @param observer defines the observer to notify
  8417. * @param eventData defines the data to be sent to each callback
  8418. * @param mask is used to filter observers defaults to -1
  8419. */
  8420. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8421. if (mask === void 0) { mask = -1; }
  8422. var state = this._eventState;
  8423. state.mask = mask;
  8424. state.skipNextObservers = false;
  8425. observer.callback(eventData, state);
  8426. };
  8427. /**
  8428. * Gets a boolean indicating if the observable has at least one observer
  8429. * @returns true is the Observable has at least one Observer registered
  8430. */
  8431. Observable.prototype.hasObservers = function () {
  8432. return this._observers.length > 0;
  8433. };
  8434. /**
  8435. * Clear the list of observers
  8436. */
  8437. Observable.prototype.clear = function () {
  8438. this._observers = new Array();
  8439. this._onObserverAdded = null;
  8440. };
  8441. /**
  8442. * Clone the current observable
  8443. * @returns a new observable
  8444. */
  8445. Observable.prototype.clone = function () {
  8446. var result = new Observable();
  8447. result._observers = this._observers.slice(0);
  8448. return result;
  8449. };
  8450. /**
  8451. * Does this observable handles observer registered with a given mask
  8452. * @param mask defines the mask to be tested
  8453. * @return whether or not one observer registered with the given mask is handeled
  8454. **/
  8455. Observable.prototype.hasSpecificMask = function (mask) {
  8456. if (mask === void 0) { mask = -1; }
  8457. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8458. var obs = _a[_i];
  8459. if (obs.mask & mask || obs.mask === mask) {
  8460. return true;
  8461. }
  8462. }
  8463. return false;
  8464. };
  8465. return Observable;
  8466. }());
  8467. BABYLON.Observable = Observable;
  8468. })(BABYLON || (BABYLON = {}));
  8469. //# sourceMappingURL=babylon.observable.js.map
  8470. var BABYLON;
  8471. (function (BABYLON) {
  8472. var SmartArray = /** @class */ (function () {
  8473. function SmartArray(capacity) {
  8474. this.length = 0;
  8475. this.data = new Array(capacity);
  8476. this._id = SmartArray._GlobalId++;
  8477. }
  8478. SmartArray.prototype.push = function (value) {
  8479. this.data[this.length++] = value;
  8480. if (this.length > this.data.length) {
  8481. this.data.length *= 2;
  8482. }
  8483. };
  8484. SmartArray.prototype.forEach = function (func) {
  8485. for (var index = 0; index < this.length; index++) {
  8486. func(this.data[index]);
  8487. }
  8488. };
  8489. SmartArray.prototype.sort = function (compareFn) {
  8490. this.data.sort(compareFn);
  8491. };
  8492. SmartArray.prototype.reset = function () {
  8493. this.length = 0;
  8494. };
  8495. SmartArray.prototype.dispose = function () {
  8496. this.reset();
  8497. if (this.data) {
  8498. this.data.length = 0;
  8499. this.data = [];
  8500. }
  8501. };
  8502. SmartArray.prototype.concat = function (array) {
  8503. if (array.length === 0) {
  8504. return;
  8505. }
  8506. if (this.length + array.length > this.data.length) {
  8507. this.data.length = (this.length + array.length) * 2;
  8508. }
  8509. for (var index = 0; index < array.length; index++) {
  8510. this.data[this.length++] = (array.data || array)[index];
  8511. }
  8512. };
  8513. SmartArray.prototype.indexOf = function (value) {
  8514. var position = this.data.indexOf(value);
  8515. if (position >= this.length) {
  8516. return -1;
  8517. }
  8518. return position;
  8519. };
  8520. SmartArray.prototype.contains = function (value) {
  8521. return this.data.indexOf(value) !== -1;
  8522. };
  8523. // Statics
  8524. SmartArray._GlobalId = 0;
  8525. return SmartArray;
  8526. }());
  8527. BABYLON.SmartArray = SmartArray;
  8528. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8529. __extends(SmartArrayNoDuplicate, _super);
  8530. function SmartArrayNoDuplicate() {
  8531. var _this = _super !== null && _super.apply(this, arguments) || this;
  8532. _this._duplicateId = 0;
  8533. return _this;
  8534. }
  8535. SmartArrayNoDuplicate.prototype.push = function (value) {
  8536. _super.prototype.push.call(this, value);
  8537. if (!value.__smartArrayFlags) {
  8538. value.__smartArrayFlags = {};
  8539. }
  8540. value.__smartArrayFlags[this._id] = this._duplicateId;
  8541. };
  8542. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8543. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8544. return false;
  8545. }
  8546. this.push(value);
  8547. return true;
  8548. };
  8549. SmartArrayNoDuplicate.prototype.reset = function () {
  8550. _super.prototype.reset.call(this);
  8551. this._duplicateId++;
  8552. };
  8553. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8554. if (array.length === 0) {
  8555. return;
  8556. }
  8557. if (this.length + array.length > this.data.length) {
  8558. this.data.length = (this.length + array.length) * 2;
  8559. }
  8560. for (var index = 0; index < array.length; index++) {
  8561. var item = (array.data || array)[index];
  8562. this.pushNoDuplicate(item);
  8563. }
  8564. };
  8565. return SmartArrayNoDuplicate;
  8566. }(SmartArray));
  8567. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8568. })(BABYLON || (BABYLON = {}));
  8569. //# sourceMappingURL=babylon.smartArray.js.map
  8570. var BABYLON;
  8571. (function (BABYLON) {
  8572. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8573. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8574. var LoadFileError = /** @class */ (function (_super) {
  8575. __extends(LoadFileError, _super);
  8576. function LoadFileError(message, request) {
  8577. var _this = _super.call(this, message) || this;
  8578. _this.request = request;
  8579. _this.name = "LoadFileError";
  8580. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8581. return _this;
  8582. }
  8583. // Polyfill for Object.setPrototypeOf if necessary.
  8584. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8585. return LoadFileError;
  8586. }(Error));
  8587. BABYLON.LoadFileError = LoadFileError;
  8588. var RetryStrategy = /** @class */ (function () {
  8589. function RetryStrategy() {
  8590. }
  8591. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8592. if (maxRetries === void 0) { maxRetries = 3; }
  8593. if (baseInterval === void 0) { baseInterval = 500; }
  8594. return function (url, request, retryIndex) {
  8595. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8596. return -1;
  8597. }
  8598. return Math.pow(2, retryIndex) * baseInterval;
  8599. };
  8600. };
  8601. return RetryStrategy;
  8602. }());
  8603. BABYLON.RetryStrategy = RetryStrategy;
  8604. // Screenshots
  8605. var screenshotCanvas;
  8606. var cloneValue = function (source, destinationObject) {
  8607. if (!source)
  8608. return null;
  8609. if (source instanceof BABYLON.Mesh) {
  8610. return null;
  8611. }
  8612. if (source instanceof BABYLON.SubMesh) {
  8613. return source.clone(destinationObject);
  8614. }
  8615. else if (source.clone) {
  8616. return source.clone();
  8617. }
  8618. return null;
  8619. };
  8620. var Tools = /** @class */ (function () {
  8621. function Tools() {
  8622. }
  8623. /**
  8624. * Interpolates between a and b via alpha
  8625. * @param a The lower value (returned when alpha = 0)
  8626. * @param b The upper value (returned when alpha = 1)
  8627. * @param alpha The interpolation-factor
  8628. * @return The mixed value
  8629. */
  8630. Tools.Mix = function (a, b, alpha) {
  8631. return a * (1 - alpha) + b * alpha;
  8632. };
  8633. Tools.Instantiate = function (className) {
  8634. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8635. return Tools.RegisteredExternalClasses[className];
  8636. }
  8637. var arr = className.split(".");
  8638. var fn = (window || this);
  8639. for (var i = 0, len = arr.length; i < len; i++) {
  8640. fn = fn[arr[i]];
  8641. }
  8642. if (typeof fn !== "function") {
  8643. return null;
  8644. }
  8645. return fn;
  8646. };
  8647. /**
  8648. * Provides a slice function that will work even on IE
  8649. * @param data defines the array to slice
  8650. * @param start defines the start of the data (optional)
  8651. * @param end defines the end of the data (optional)
  8652. * @returns the new sliced array
  8653. */
  8654. Tools.Slice = function (data, start, end) {
  8655. if (data.slice) {
  8656. return data.slice(start, end);
  8657. }
  8658. return Array.prototype.slice.call(data, start, end);
  8659. };
  8660. Tools.SetImmediate = function (action) {
  8661. if (window.setImmediate) {
  8662. window.setImmediate(action);
  8663. }
  8664. else {
  8665. setTimeout(action, 1);
  8666. }
  8667. };
  8668. Tools.IsExponentOfTwo = function (value) {
  8669. var count = 1;
  8670. do {
  8671. count *= 2;
  8672. } while (count < value);
  8673. return count === value;
  8674. };
  8675. /**
  8676. * Returns the nearest 32-bit single precision float representation of a Number
  8677. * @param value A Number. If the parameter is of a different type, it will get converted
  8678. * to a number or to NaN if it cannot be converted
  8679. * @returns number
  8680. */
  8681. Tools.FloatRound = function (value) {
  8682. if (Math.fround) {
  8683. return Math.fround(value);
  8684. }
  8685. return (Tools._tmpFloatArray[0] = value);
  8686. };
  8687. /**
  8688. * Find the next highest power of two.
  8689. * @param x Number to start search from.
  8690. * @return Next highest power of two.
  8691. */
  8692. Tools.CeilingPOT = function (x) {
  8693. x--;
  8694. x |= x >> 1;
  8695. x |= x >> 2;
  8696. x |= x >> 4;
  8697. x |= x >> 8;
  8698. x |= x >> 16;
  8699. x++;
  8700. return x;
  8701. };
  8702. /**
  8703. * Find the next lowest power of two.
  8704. * @param x Number to start search from.
  8705. * @return Next lowest power of two.
  8706. */
  8707. Tools.FloorPOT = function (x) {
  8708. x = x | (x >> 1);
  8709. x = x | (x >> 2);
  8710. x = x | (x >> 4);
  8711. x = x | (x >> 8);
  8712. x = x | (x >> 16);
  8713. return x - (x >> 1);
  8714. };
  8715. /**
  8716. * Find the nearest power of two.
  8717. * @param x Number to start search from.
  8718. * @return Next nearest power of two.
  8719. */
  8720. Tools.NearestPOT = function (x) {
  8721. var c = Tools.CeilingPOT(x);
  8722. var f = Tools.FloorPOT(x);
  8723. return (c - x) > (x - f) ? f : c;
  8724. };
  8725. Tools.GetExponentOfTwo = function (value, max, mode) {
  8726. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8727. var pot;
  8728. switch (mode) {
  8729. case BABYLON.Engine.SCALEMODE_FLOOR:
  8730. pot = Tools.FloorPOT(value);
  8731. break;
  8732. case BABYLON.Engine.SCALEMODE_NEAREST:
  8733. pot = Tools.NearestPOT(value);
  8734. break;
  8735. case BABYLON.Engine.SCALEMODE_CEILING:
  8736. default:
  8737. pot = Tools.CeilingPOT(value);
  8738. break;
  8739. }
  8740. return Math.min(pot, max);
  8741. };
  8742. Tools.GetFilename = function (path) {
  8743. var index = path.lastIndexOf("/");
  8744. if (index < 0)
  8745. return path;
  8746. return path.substring(index + 1);
  8747. };
  8748. /**
  8749. * Extracts the "folder" part of a path (everything before the filename).
  8750. * @param uri The URI to extract the info from
  8751. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8752. * @returns The "folder" part of the path
  8753. */
  8754. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8755. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8756. var index = uri.lastIndexOf("/");
  8757. if (index < 0) {
  8758. if (returnUnchangedIfNoSlash) {
  8759. return uri;
  8760. }
  8761. return "";
  8762. }
  8763. return uri.substring(0, index + 1);
  8764. };
  8765. Tools.GetDOMTextContent = function (element) {
  8766. var result = "";
  8767. var child = element.firstChild;
  8768. while (child) {
  8769. if (child.nodeType === 3) {
  8770. result += child.textContent;
  8771. }
  8772. child = child.nextSibling;
  8773. }
  8774. return result;
  8775. };
  8776. Tools.ToDegrees = function (angle) {
  8777. return angle * 180 / Math.PI;
  8778. };
  8779. Tools.ToRadians = function (angle) {
  8780. return angle * Math.PI / 180;
  8781. };
  8782. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8783. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8784. var output = "";
  8785. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8786. var i = 0;
  8787. var bytes = new Uint8Array(buffer);
  8788. while (i < bytes.length) {
  8789. chr1 = bytes[i++];
  8790. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8791. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8792. enc1 = chr1 >> 2;
  8793. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8794. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8795. enc4 = chr3 & 63;
  8796. if (isNaN(chr2)) {
  8797. enc3 = enc4 = 64;
  8798. }
  8799. else if (isNaN(chr3)) {
  8800. enc4 = 64;
  8801. }
  8802. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8803. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8804. }
  8805. return "data:image/png;base64," + output;
  8806. };
  8807. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8808. if (bias === void 0) { bias = null; }
  8809. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8810. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8811. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8812. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8813. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8814. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8815. }
  8816. if (bias) {
  8817. minimum.x -= minimum.x * bias.x + bias.y;
  8818. minimum.y -= minimum.y * bias.x + bias.y;
  8819. minimum.z -= minimum.z * bias.x + bias.y;
  8820. maximum.x += maximum.x * bias.x + bias.y;
  8821. maximum.y += maximum.y * bias.x + bias.y;
  8822. maximum.z += maximum.z * bias.x + bias.y;
  8823. }
  8824. return {
  8825. minimum: minimum,
  8826. maximum: maximum
  8827. };
  8828. };
  8829. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8830. if (bias === void 0) { bias = null; }
  8831. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8832. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8833. if (!stride) {
  8834. stride = 3;
  8835. }
  8836. for (var index = start; index < start + count; index++) {
  8837. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8838. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8839. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8840. }
  8841. if (bias) {
  8842. minimum.x -= minimum.x * bias.x + bias.y;
  8843. minimum.y -= minimum.y * bias.x + bias.y;
  8844. minimum.z -= minimum.z * bias.x + bias.y;
  8845. maximum.x += maximum.x * bias.x + bias.y;
  8846. maximum.y += maximum.y * bias.x + bias.y;
  8847. maximum.z += maximum.z * bias.x + bias.y;
  8848. }
  8849. return {
  8850. minimum: minimum,
  8851. maximum: maximum
  8852. };
  8853. };
  8854. Tools.Vector2ArrayFeeder = function (array) {
  8855. return function (index) {
  8856. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8857. var length = isFloatArray ? array.length / 2 : array.length;
  8858. if (index >= length) {
  8859. return null;
  8860. }
  8861. if (isFloatArray) {
  8862. var fa = array;
  8863. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8864. }
  8865. var a = array;
  8866. return a[index];
  8867. };
  8868. };
  8869. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8870. if (bias === void 0) { bias = null; }
  8871. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8872. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8873. var i = 0;
  8874. var cur = feeder(i++);
  8875. while (cur) {
  8876. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8877. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8878. cur = feeder(i++);
  8879. }
  8880. if (bias) {
  8881. minimum.x -= minimum.x * bias.x + bias.y;
  8882. minimum.y -= minimum.y * bias.x + bias.y;
  8883. maximum.x += maximum.x * bias.x + bias.y;
  8884. maximum.y += maximum.y * bias.x + bias.y;
  8885. }
  8886. return {
  8887. minimum: minimum,
  8888. maximum: maximum
  8889. };
  8890. };
  8891. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8892. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8893. return null;
  8894. return Array.isArray(obj) ? obj : [obj];
  8895. };
  8896. // Misc.
  8897. Tools.GetPointerPrefix = function () {
  8898. var eventPrefix = "pointer";
  8899. // Check if pointer events are supported
  8900. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8901. eventPrefix = "mouse";
  8902. }
  8903. return eventPrefix;
  8904. };
  8905. /**
  8906. * @param func - the function to be called
  8907. * @param requester - the object that will request the next frame. Falls back to window.
  8908. */
  8909. Tools.QueueNewFrame = function (func, requester) {
  8910. if (!Tools.IsWindowObjectExist()) {
  8911. return setTimeout(func, 16);
  8912. }
  8913. if (!requester) {
  8914. requester = window;
  8915. }
  8916. if (requester.requestAnimationFrame) {
  8917. return requester.requestAnimationFrame(func);
  8918. }
  8919. else if (requester.msRequestAnimationFrame) {
  8920. return requester.msRequestAnimationFrame(func);
  8921. }
  8922. else if (requester.webkitRequestAnimationFrame) {
  8923. return requester.webkitRequestAnimationFrame(func);
  8924. }
  8925. else if (requester.mozRequestAnimationFrame) {
  8926. return requester.mozRequestAnimationFrame(func);
  8927. }
  8928. else if (requester.oRequestAnimationFrame) {
  8929. return requester.oRequestAnimationFrame(func);
  8930. }
  8931. else {
  8932. return window.setTimeout(func, 16);
  8933. }
  8934. };
  8935. Tools.RequestFullscreen = function (element) {
  8936. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8937. if (!requestFunction)
  8938. return;
  8939. requestFunction.call(element);
  8940. };
  8941. Tools.ExitFullscreen = function () {
  8942. if (document.exitFullscreen) {
  8943. document.exitFullscreen();
  8944. }
  8945. else if (document.mozCancelFullScreen) {
  8946. document.mozCancelFullScreen();
  8947. }
  8948. else if (document.webkitCancelFullScreen) {
  8949. document.webkitCancelFullScreen();
  8950. }
  8951. else if (document.msCancelFullScreen) {
  8952. document.msCancelFullScreen();
  8953. }
  8954. };
  8955. Tools.SetCorsBehavior = function (url, element) {
  8956. if (url && url.indexOf("data:") === 0) {
  8957. return;
  8958. }
  8959. if (Tools.CorsBehavior) {
  8960. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8961. element.crossOrigin = Tools.CorsBehavior;
  8962. }
  8963. else {
  8964. var result = Tools.CorsBehavior(url);
  8965. if (result) {
  8966. element.crossOrigin = result;
  8967. }
  8968. }
  8969. }
  8970. };
  8971. // External files
  8972. Tools.CleanUrl = function (url) {
  8973. url = url.replace(/#/mg, "%23");
  8974. return url;
  8975. };
  8976. /**
  8977. * Loads an image as an HTMLImageElement.
  8978. * @param input url string, ArrayBuffer, or Blob to load
  8979. * @param onLoad callback called when the image successfully loads
  8980. * @param onError callback called when the image fails to load
  8981. * @param database database for caching
  8982. * @returns the HTMLImageElement of the loaded image
  8983. */
  8984. Tools.LoadImage = function (input, onLoad, onError, database) {
  8985. var url;
  8986. var usingObjectURL = false;
  8987. if (input instanceof ArrayBuffer) {
  8988. url = URL.createObjectURL(new Blob([input]));
  8989. usingObjectURL = true;
  8990. }
  8991. else if (input instanceof Blob) {
  8992. url = URL.createObjectURL(input);
  8993. usingObjectURL = true;
  8994. }
  8995. else {
  8996. url = Tools.CleanUrl(input);
  8997. url = Tools.PreprocessUrl(input);
  8998. }
  8999. var img = new Image();
  9000. Tools.SetCorsBehavior(url, img);
  9001. var loadHandler = function () {
  9002. if (usingObjectURL && img.src) {
  9003. URL.revokeObjectURL(img.src);
  9004. }
  9005. img.removeEventListener("load", loadHandler);
  9006. img.removeEventListener("error", errorHandler);
  9007. onLoad(img);
  9008. };
  9009. var errorHandler = function (err) {
  9010. if (usingObjectURL && img.src) {
  9011. URL.revokeObjectURL(img.src);
  9012. }
  9013. img.removeEventListener("load", loadHandler);
  9014. img.removeEventListener("error", errorHandler);
  9015. Tools.Error("Error while trying to load image: " + input);
  9016. if (onError) {
  9017. onError("Error while trying to load image: " + input, err);
  9018. }
  9019. };
  9020. img.addEventListener("load", loadHandler);
  9021. img.addEventListener("error", errorHandler);
  9022. var noIndexedDB = function () {
  9023. img.src = url;
  9024. };
  9025. var loadFromIndexedDB = function () {
  9026. if (database) {
  9027. database.loadImageFromDB(url, img);
  9028. }
  9029. };
  9030. //ANY database to do!
  9031. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9032. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9033. }
  9034. else {
  9035. if (url.indexOf("file:") !== -1) {
  9036. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9037. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9038. try {
  9039. var blobURL;
  9040. try {
  9041. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9042. }
  9043. catch (ex) {
  9044. // Chrome doesn't support oneTimeOnly parameter
  9045. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9046. }
  9047. img.src = blobURL;
  9048. usingObjectURL = true;
  9049. }
  9050. catch (e) {
  9051. img.src = "";
  9052. }
  9053. return img;
  9054. }
  9055. }
  9056. noIndexedDB();
  9057. }
  9058. return img;
  9059. };
  9060. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9061. url = Tools.CleanUrl(url);
  9062. url = Tools.PreprocessUrl(url);
  9063. // If file and file input are set
  9064. if (url.indexOf("file:") !== -1) {
  9065. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9066. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9067. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9068. }
  9069. }
  9070. var loadUrl = Tools.BaseUrl + url;
  9071. var aborted = false;
  9072. var fileRequest = {
  9073. onCompleteObservable: new BABYLON.Observable(),
  9074. abort: function () { return aborted = true; },
  9075. };
  9076. var requestFile = function () {
  9077. var request = new XMLHttpRequest();
  9078. var retryHandle = null;
  9079. fileRequest.abort = function () {
  9080. aborted = true;
  9081. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9082. request.abort();
  9083. }
  9084. if (retryHandle !== null) {
  9085. clearTimeout(retryHandle);
  9086. retryHandle = null;
  9087. }
  9088. };
  9089. var retryLoop = function (retryIndex) {
  9090. request.open('GET', loadUrl, true);
  9091. if (useArrayBuffer) {
  9092. request.responseType = "arraybuffer";
  9093. }
  9094. if (onProgress) {
  9095. request.addEventListener("progress", onProgress);
  9096. }
  9097. var onLoadEnd = function () {
  9098. request.removeEventListener("loadend", onLoadEnd);
  9099. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9100. fileRequest.onCompleteObservable.clear();
  9101. };
  9102. request.addEventListener("loadend", onLoadEnd);
  9103. var onReadyStateChange = function () {
  9104. if (aborted) {
  9105. return;
  9106. }
  9107. // In case of undefined state in some browsers.
  9108. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9109. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9110. request.removeEventListener("readystatechange", onReadyStateChange);
  9111. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9112. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9113. return;
  9114. }
  9115. var retryStrategy = Tools.DefaultRetryStrategy;
  9116. if (retryStrategy) {
  9117. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9118. if (waitTime !== -1) {
  9119. // Prevent the request from completing for retry.
  9120. request.removeEventListener("loadend", onLoadEnd);
  9121. request = new XMLHttpRequest();
  9122. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9123. return;
  9124. }
  9125. }
  9126. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9127. if (onError) {
  9128. onError(request, e);
  9129. }
  9130. else {
  9131. throw e;
  9132. }
  9133. }
  9134. };
  9135. request.addEventListener("readystatechange", onReadyStateChange);
  9136. request.send();
  9137. };
  9138. retryLoop(0);
  9139. };
  9140. // Caching all files
  9141. if (database && database.enableSceneOffline) {
  9142. var noIndexedDB_1 = function () {
  9143. if (!aborted) {
  9144. requestFile();
  9145. }
  9146. };
  9147. var loadFromIndexedDB = function () {
  9148. // TODO: database needs to support aborting and should return a IFileRequest
  9149. if (aborted) {
  9150. return;
  9151. }
  9152. if (database) {
  9153. database.loadFileFromDB(url, function (data) {
  9154. if (!aborted) {
  9155. onSuccess(data);
  9156. }
  9157. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9158. }, onProgress ? function (event) {
  9159. if (!aborted) {
  9160. onProgress(event);
  9161. }
  9162. } : undefined, noIndexedDB_1, useArrayBuffer);
  9163. }
  9164. };
  9165. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9166. }
  9167. else {
  9168. requestFile();
  9169. }
  9170. return fileRequest;
  9171. };
  9172. /**
  9173. * Load a script (identified by an url). When the url returns, the
  9174. * content of this file is added into a new script element, attached to the DOM (body element)
  9175. */
  9176. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9177. var head = document.getElementsByTagName('head')[0];
  9178. var script = document.createElement('script');
  9179. script.type = 'text/javascript';
  9180. script.src = scriptUrl;
  9181. script.onload = function () {
  9182. if (onSuccess) {
  9183. onSuccess();
  9184. }
  9185. };
  9186. script.onerror = function (e) {
  9187. if (onError) {
  9188. onError("Unable to load script '" + scriptUrl + "'", e);
  9189. }
  9190. };
  9191. head.appendChild(script);
  9192. };
  9193. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9194. var reader = new FileReader();
  9195. var request = {
  9196. onCompleteObservable: new BABYLON.Observable(),
  9197. abort: function () { return reader.abort(); },
  9198. };
  9199. reader.onloadend = function (e) {
  9200. request.onCompleteObservable.notifyObservers(request);
  9201. };
  9202. reader.onload = function (e) {
  9203. //target doesn't have result from ts 1.3
  9204. callback(e.target['result']);
  9205. };
  9206. reader.onprogress = progressCallback;
  9207. reader.readAsDataURL(fileToLoad);
  9208. return request;
  9209. };
  9210. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9211. var reader = new FileReader();
  9212. var request = {
  9213. onCompleteObservable: new BABYLON.Observable(),
  9214. abort: function () { return reader.abort(); },
  9215. };
  9216. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9217. reader.onerror = function (e) {
  9218. Tools.Log("Error while reading file: " + fileToLoad.name);
  9219. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9220. };
  9221. reader.onload = function (e) {
  9222. //target doesn't have result from ts 1.3
  9223. callback(e.target['result']);
  9224. };
  9225. if (progressCallBack) {
  9226. reader.onprogress = progressCallBack;
  9227. }
  9228. if (!useArrayBuffer) {
  9229. // Asynchronous read
  9230. reader.readAsText(fileToLoad);
  9231. }
  9232. else {
  9233. reader.readAsArrayBuffer(fileToLoad);
  9234. }
  9235. return request;
  9236. };
  9237. //returns a downloadable url to a file content.
  9238. Tools.FileAsURL = function (content) {
  9239. var fileBlob = new Blob([content]);
  9240. var url = window.URL || window.webkitURL;
  9241. var link = url.createObjectURL(fileBlob);
  9242. return link;
  9243. };
  9244. // Misc.
  9245. Tools.Format = function (value, decimals) {
  9246. if (decimals === void 0) { decimals = 2; }
  9247. return value.toFixed(decimals);
  9248. };
  9249. Tools.CheckExtends = function (v, min, max) {
  9250. if (v.x < min.x)
  9251. min.x = v.x;
  9252. if (v.y < min.y)
  9253. min.y = v.y;
  9254. if (v.z < min.z)
  9255. min.z = v.z;
  9256. if (v.x > max.x)
  9257. max.x = v.x;
  9258. if (v.y > max.y)
  9259. max.y = v.y;
  9260. if (v.z > max.z)
  9261. max.z = v.z;
  9262. };
  9263. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9264. for (var prop in source) {
  9265. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9266. continue;
  9267. }
  9268. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9269. continue;
  9270. }
  9271. var sourceValue = source[prop];
  9272. var typeOfSourceValue = typeof sourceValue;
  9273. if (typeOfSourceValue === "function") {
  9274. continue;
  9275. }
  9276. try {
  9277. if (typeOfSourceValue === "object") {
  9278. if (sourceValue instanceof Array) {
  9279. destination[prop] = [];
  9280. if (sourceValue.length > 0) {
  9281. if (typeof sourceValue[0] == "object") {
  9282. for (var index = 0; index < sourceValue.length; index++) {
  9283. var clonedValue = cloneValue(sourceValue[index], destination);
  9284. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9285. destination[prop].push(clonedValue);
  9286. }
  9287. }
  9288. }
  9289. else {
  9290. destination[prop] = sourceValue.slice(0);
  9291. }
  9292. }
  9293. }
  9294. else {
  9295. destination[prop] = cloneValue(sourceValue, destination);
  9296. }
  9297. }
  9298. else {
  9299. destination[prop] = sourceValue;
  9300. }
  9301. }
  9302. catch (e) {
  9303. // Just ignore error (it could be because of a read-only property)
  9304. }
  9305. }
  9306. };
  9307. Tools.IsEmpty = function (obj) {
  9308. for (var i in obj) {
  9309. if (obj.hasOwnProperty(i)) {
  9310. return false;
  9311. }
  9312. }
  9313. return true;
  9314. };
  9315. Tools.RegisterTopRootEvents = function (events) {
  9316. for (var index = 0; index < events.length; index++) {
  9317. var event = events[index];
  9318. window.addEventListener(event.name, event.handler, false);
  9319. try {
  9320. if (window.parent) {
  9321. window.parent.addEventListener(event.name, event.handler, false);
  9322. }
  9323. }
  9324. catch (e) {
  9325. // Silently fails...
  9326. }
  9327. }
  9328. };
  9329. Tools.UnregisterTopRootEvents = function (events) {
  9330. for (var index = 0; index < events.length; index++) {
  9331. var event = events[index];
  9332. window.removeEventListener(event.name, event.handler);
  9333. try {
  9334. if (window.parent) {
  9335. window.parent.removeEventListener(event.name, event.handler);
  9336. }
  9337. }
  9338. catch (e) {
  9339. // Silently fails...
  9340. }
  9341. }
  9342. };
  9343. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9344. if (mimeType === void 0) { mimeType = "image/png"; }
  9345. // Read the contents of the framebuffer
  9346. var numberOfChannelsByLine = width * 4;
  9347. var halfHeight = height / 2;
  9348. //Reading datas from WebGL
  9349. var data = engine.readPixels(0, 0, width, height);
  9350. //To flip image on Y axis.
  9351. for (var i = 0; i < halfHeight; i++) {
  9352. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9353. var currentCell = j + i * numberOfChannelsByLine;
  9354. var targetLine = height - i - 1;
  9355. var targetCell = j + targetLine * numberOfChannelsByLine;
  9356. var temp = data[currentCell];
  9357. data[currentCell] = data[targetCell];
  9358. data[targetCell] = temp;
  9359. }
  9360. }
  9361. // Create a 2D canvas to store the result
  9362. if (!screenshotCanvas) {
  9363. screenshotCanvas = document.createElement('canvas');
  9364. }
  9365. screenshotCanvas.width = width;
  9366. screenshotCanvas.height = height;
  9367. var context = screenshotCanvas.getContext('2d');
  9368. if (context) {
  9369. // Copy the pixels to a 2D canvas
  9370. var imageData = context.createImageData(width, height);
  9371. var castData = (imageData.data);
  9372. castData.set(data);
  9373. context.putImageData(imageData, 0, 0);
  9374. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9375. }
  9376. };
  9377. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9378. if (mimeType === void 0) { mimeType = "image/png"; }
  9379. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9380. if (successCallback) {
  9381. successCallback(base64Image);
  9382. }
  9383. else {
  9384. // We need HTMLCanvasElement.toBlob for HD screenshots
  9385. if (!screenshotCanvas.toBlob) {
  9386. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9387. screenshotCanvas.toBlob = function (callback, type, quality) {
  9388. var _this = this;
  9389. setTimeout(function () {
  9390. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9391. for (var i = 0; i < len; i++) {
  9392. arr[i] = binStr.charCodeAt(i);
  9393. }
  9394. callback(new Blob([arr], { type: type || 'image/png' }));
  9395. });
  9396. };
  9397. }
  9398. screenshotCanvas.toBlob(function (blob) {
  9399. var url = URL.createObjectURL(blob);
  9400. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9401. if (("download" in document.createElement("a"))) {
  9402. var a = window.document.createElement("a");
  9403. a.href = url;
  9404. if (fileName) {
  9405. a.setAttribute("download", fileName);
  9406. }
  9407. else {
  9408. var date = new Date();
  9409. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9410. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9411. }
  9412. window.document.body.appendChild(a);
  9413. a.addEventListener("click", function () {
  9414. if (a.parentElement) {
  9415. a.parentElement.removeChild(a);
  9416. }
  9417. });
  9418. a.click();
  9419. }
  9420. else {
  9421. var newWindow = window.open("");
  9422. if (!newWindow)
  9423. return;
  9424. var img = newWindow.document.createElement("img");
  9425. img.onload = function () {
  9426. // no longer need to read the blob so it's revoked
  9427. URL.revokeObjectURL(url);
  9428. };
  9429. img.src = url;
  9430. newWindow.document.body.appendChild(img);
  9431. }
  9432. });
  9433. }
  9434. };
  9435. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. var width;
  9438. var height;
  9439. // If a precision value is specified
  9440. if (size.precision) {
  9441. width = Math.round(engine.getRenderWidth() * size.precision);
  9442. height = Math.round(width / engine.getAspectRatio(camera));
  9443. }
  9444. else if (size.width && size.height) {
  9445. width = size.width;
  9446. height = size.height;
  9447. }
  9448. //If passing only width, computing height to keep display canvas ratio.
  9449. else if (size.width && !size.height) {
  9450. width = size.width;
  9451. height = Math.round(width / engine.getAspectRatio(camera));
  9452. }
  9453. //If passing only height, computing width to keep display canvas ratio.
  9454. else if (size.height && !size.width) {
  9455. height = size.height;
  9456. width = Math.round(height * engine.getAspectRatio(camera));
  9457. }
  9458. //Assuming here that "size" parameter is a number
  9459. else if (!isNaN(size)) {
  9460. height = size;
  9461. width = size;
  9462. }
  9463. else {
  9464. Tools.Error("Invalid 'size' parameter !");
  9465. return;
  9466. }
  9467. if (!screenshotCanvas) {
  9468. screenshotCanvas = document.createElement('canvas');
  9469. }
  9470. screenshotCanvas.width = width;
  9471. screenshotCanvas.height = height;
  9472. var renderContext = screenshotCanvas.getContext("2d");
  9473. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9474. var newWidth = width;
  9475. var newHeight = newWidth / ratio;
  9476. if (newHeight > height) {
  9477. newHeight = height;
  9478. newWidth = newHeight * ratio;
  9479. }
  9480. var offsetX = Math.max(0, width - newWidth) / 2;
  9481. var offsetY = Math.max(0, height - newHeight) / 2;
  9482. var renderingCanvas = engine.getRenderingCanvas();
  9483. if (renderContext && renderingCanvas) {
  9484. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9485. }
  9486. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9487. };
  9488. /**
  9489. * Generates an image screenshot from the specified camera.
  9490. *
  9491. * @param engine The engine to use for rendering
  9492. * @param camera The camera to use for rendering
  9493. * @param size This parameter can be set to a single number or to an object with the
  9494. * following (optional) properties: precision, width, height. If a single number is passed,
  9495. * it will be used for both width and height. If an object is passed, the screenshot size
  9496. * will be derived from the parameters. The precision property is a multiplier allowing
  9497. * rendering at a higher or lower resolution.
  9498. * @param successCallback The callback receives a single parameter which contains the
  9499. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9500. * src parameter of an <img> to display it.
  9501. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9502. * Check your browser for supported MIME types.
  9503. * @param samples Texture samples (default: 1)
  9504. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9505. * @param fileName A name for for the downloaded file.
  9506. * @constructor
  9507. */
  9508. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9509. if (mimeType === void 0) { mimeType = "image/png"; }
  9510. if (samples === void 0) { samples = 1; }
  9511. if (antialiasing === void 0) { antialiasing = false; }
  9512. var width;
  9513. var height;
  9514. //If a precision value is specified
  9515. if (size.precision) {
  9516. width = Math.round(engine.getRenderWidth() * size.precision);
  9517. height = Math.round(width / engine.getAspectRatio(camera));
  9518. size = { width: width, height: height };
  9519. }
  9520. else if (size.width && size.height) {
  9521. width = size.width;
  9522. height = size.height;
  9523. }
  9524. //If passing only width, computing height to keep display canvas ratio.
  9525. else if (size.width && !size.height) {
  9526. width = size.width;
  9527. height = Math.round(width / engine.getAspectRatio(camera));
  9528. size = { width: width, height: height };
  9529. }
  9530. //If passing only height, computing width to keep display canvas ratio.
  9531. else if (size.height && !size.width) {
  9532. height = size.height;
  9533. width = Math.round(height * engine.getAspectRatio(camera));
  9534. size = { width: width, height: height };
  9535. }
  9536. //Assuming here that "size" parameter is a number
  9537. else if (!isNaN(size)) {
  9538. height = size;
  9539. width = size;
  9540. }
  9541. else {
  9542. Tools.Error("Invalid 'size' parameter !");
  9543. return;
  9544. }
  9545. var scene = camera.getScene();
  9546. var previousCamera = null;
  9547. if (scene.activeCamera !== camera) {
  9548. previousCamera = scene.activeCamera;
  9549. scene.activeCamera = camera;
  9550. }
  9551. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9552. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9553. texture.renderList = null;
  9554. texture.samples = samples;
  9555. if (antialiasing) {
  9556. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9557. }
  9558. texture.onAfterRenderObservable.add(function () {
  9559. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9560. });
  9561. scene.incrementRenderId();
  9562. scene.resetCachedMaterial();
  9563. texture.render(true);
  9564. texture.dispose();
  9565. if (previousCamera) {
  9566. scene.activeCamera = previousCamera;
  9567. }
  9568. camera.getProjectionMatrix(true); // Force cache refresh;
  9569. };
  9570. // XHR response validator for local file scenario
  9571. Tools.ValidateXHRData = function (xhr, dataType) {
  9572. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9573. if (dataType === void 0) { dataType = 7; }
  9574. try {
  9575. if (dataType & 1) {
  9576. if (xhr.responseText && xhr.responseText.length > 0) {
  9577. return true;
  9578. }
  9579. else if (dataType === 1) {
  9580. return false;
  9581. }
  9582. }
  9583. if (dataType & 2) {
  9584. // Check header width and height since there is no "TGA" magic number
  9585. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9586. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9587. return true;
  9588. }
  9589. else if (dataType === 2) {
  9590. return false;
  9591. }
  9592. }
  9593. if (dataType & 4) {
  9594. // Check for the "DDS" magic number
  9595. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9596. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9597. return true;
  9598. }
  9599. else {
  9600. return false;
  9601. }
  9602. }
  9603. }
  9604. catch (e) {
  9605. // Global protection
  9606. }
  9607. return false;
  9608. };
  9609. /**
  9610. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9611. * Be aware Math.random() could cause collisions, but:
  9612. * "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"
  9613. */
  9614. Tools.RandomId = function () {
  9615. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9616. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9617. return v.toString(16);
  9618. });
  9619. };
  9620. /**
  9621. * Test if the given uri is a base64 string.
  9622. * @param uri The uri to test
  9623. * @return True if the uri is a base64 string or false otherwise.
  9624. */
  9625. Tools.IsBase64 = function (uri) {
  9626. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9627. };
  9628. /**
  9629. * Decode the given base64 uri.
  9630. * @param uri The uri to decode
  9631. * @return The decoded base64 data.
  9632. */
  9633. Tools.DecodeBase64 = function (uri) {
  9634. var decodedString = atob(uri.split(",")[1]);
  9635. var bufferLength = decodedString.length;
  9636. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9637. for (var i = 0; i < bufferLength; i++) {
  9638. bufferView[i] = decodedString.charCodeAt(i);
  9639. }
  9640. return bufferView.buffer;
  9641. };
  9642. Object.defineProperty(Tools, "NoneLogLevel", {
  9643. get: function () {
  9644. return Tools._NoneLogLevel;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(Tools, "MessageLogLevel", {
  9650. get: function () {
  9651. return Tools._MessageLogLevel;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(Tools, "WarningLogLevel", {
  9657. get: function () {
  9658. return Tools._WarningLogLevel;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(Tools, "ErrorLogLevel", {
  9664. get: function () {
  9665. return Tools._ErrorLogLevel;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(Tools, "AllLogLevel", {
  9671. get: function () {
  9672. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Tools._AddLogEntry = function (entry) {
  9678. Tools._LogCache = entry + Tools._LogCache;
  9679. if (Tools.OnNewCacheEntry) {
  9680. Tools.OnNewCacheEntry(entry);
  9681. }
  9682. };
  9683. Tools._FormatMessage = function (message) {
  9684. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9685. var date = new Date();
  9686. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9687. };
  9688. Tools._LogDisabled = function (message) {
  9689. // nothing to do
  9690. };
  9691. Tools._LogEnabled = function (message) {
  9692. var formattedMessage = Tools._FormatMessage(message);
  9693. console.log("BJS - " + formattedMessage);
  9694. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9695. Tools._AddLogEntry(entry);
  9696. };
  9697. Tools._WarnDisabled = function (message) {
  9698. // nothing to do
  9699. };
  9700. Tools._WarnEnabled = function (message) {
  9701. var formattedMessage = Tools._FormatMessage(message);
  9702. console.warn("BJS - " + formattedMessage);
  9703. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9704. Tools._AddLogEntry(entry);
  9705. };
  9706. Tools._ErrorDisabled = function (message) {
  9707. // nothing to do
  9708. };
  9709. Tools._ErrorEnabled = function (message) {
  9710. Tools.errorsCount++;
  9711. var formattedMessage = Tools._FormatMessage(message);
  9712. console.error("BJS - " + formattedMessage);
  9713. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9714. Tools._AddLogEntry(entry);
  9715. };
  9716. Object.defineProperty(Tools, "LogCache", {
  9717. get: function () {
  9718. return Tools._LogCache;
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. Tools.ClearLogCache = function () {
  9724. Tools._LogCache = "";
  9725. Tools.errorsCount = 0;
  9726. };
  9727. Object.defineProperty(Tools, "LogLevels", {
  9728. set: function (level) {
  9729. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9730. Tools.Log = Tools._LogEnabled;
  9731. }
  9732. else {
  9733. Tools.Log = Tools._LogDisabled;
  9734. }
  9735. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9736. Tools.Warn = Tools._WarnEnabled;
  9737. }
  9738. else {
  9739. Tools.Warn = Tools._WarnDisabled;
  9740. }
  9741. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9742. Tools.Error = Tools._ErrorEnabled;
  9743. }
  9744. else {
  9745. Tools.Error = Tools._ErrorDisabled;
  9746. }
  9747. },
  9748. enumerable: true,
  9749. configurable: true
  9750. });
  9751. Tools.IsWindowObjectExist = function () {
  9752. return (typeof window) !== "undefined";
  9753. };
  9754. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9755. get: function () {
  9756. return Tools._PerformanceNoneLogLevel;
  9757. },
  9758. enumerable: true,
  9759. configurable: true
  9760. });
  9761. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9762. get: function () {
  9763. return Tools._PerformanceUserMarkLogLevel;
  9764. },
  9765. enumerable: true,
  9766. configurable: true
  9767. });
  9768. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9769. get: function () {
  9770. return Tools._PerformanceConsoleLogLevel;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9776. set: function (level) {
  9777. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9778. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9779. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9780. return;
  9781. }
  9782. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9783. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9784. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9785. return;
  9786. }
  9787. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9788. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9789. },
  9790. enumerable: true,
  9791. configurable: true
  9792. });
  9793. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9794. };
  9795. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9796. };
  9797. Tools._StartUserMark = function (counterName, condition) {
  9798. if (condition === void 0) { condition = true; }
  9799. if (!Tools._performance) {
  9800. if (!Tools.IsWindowObjectExist()) {
  9801. return;
  9802. }
  9803. Tools._performance = window.performance;
  9804. }
  9805. if (!condition || !Tools._performance.mark) {
  9806. return;
  9807. }
  9808. Tools._performance.mark(counterName + "-Begin");
  9809. };
  9810. Tools._EndUserMark = function (counterName, condition) {
  9811. if (condition === void 0) { condition = true; }
  9812. if (!condition || !Tools._performance.mark) {
  9813. return;
  9814. }
  9815. Tools._performance.mark(counterName + "-End");
  9816. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9817. };
  9818. Tools._StartPerformanceConsole = function (counterName, condition) {
  9819. if (condition === void 0) { condition = true; }
  9820. if (!condition) {
  9821. return;
  9822. }
  9823. Tools._StartUserMark(counterName, condition);
  9824. if (console.time) {
  9825. console.time(counterName);
  9826. }
  9827. };
  9828. Tools._EndPerformanceConsole = function (counterName, condition) {
  9829. if (condition === void 0) { condition = true; }
  9830. if (!condition) {
  9831. return;
  9832. }
  9833. Tools._EndUserMark(counterName, condition);
  9834. if (console.time) {
  9835. console.timeEnd(counterName);
  9836. }
  9837. };
  9838. Object.defineProperty(Tools, "Now", {
  9839. get: function () {
  9840. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9841. return window.performance.now();
  9842. }
  9843. return Date.now();
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. /**
  9849. * This method will return the name of the class used to create the instance of the given object.
  9850. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9851. * @param object the object to get the class name from
  9852. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9853. */
  9854. Tools.GetClassName = function (object, isType) {
  9855. if (isType === void 0) { isType = false; }
  9856. var name = null;
  9857. if (!isType && object.getClassName) {
  9858. name = object.getClassName();
  9859. }
  9860. else {
  9861. if (object instanceof Object) {
  9862. var classObj = isType ? object : Object.getPrototypeOf(object);
  9863. name = classObj.constructor["__bjsclassName__"];
  9864. }
  9865. if (!name) {
  9866. name = typeof object;
  9867. }
  9868. }
  9869. return name;
  9870. };
  9871. Tools.First = function (array, predicate) {
  9872. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9873. var el = array_1[_i];
  9874. if (predicate(el)) {
  9875. return el;
  9876. }
  9877. }
  9878. return null;
  9879. };
  9880. /**
  9881. * This method will return the name of the full name of the class, including its owning module (if any).
  9882. * 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).
  9883. * @param object the object to get the class name from
  9884. * @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.
  9885. */
  9886. Tools.getFullClassName = function (object, isType) {
  9887. if (isType === void 0) { isType = false; }
  9888. var className = null;
  9889. var moduleName = null;
  9890. if (!isType && object.getClassName) {
  9891. className = object.getClassName();
  9892. }
  9893. else {
  9894. if (object instanceof Object) {
  9895. var classObj = isType ? object : Object.getPrototypeOf(object);
  9896. className = classObj.constructor["__bjsclassName__"];
  9897. moduleName = classObj.constructor["__bjsmoduleName__"];
  9898. }
  9899. if (!className) {
  9900. className = typeof object;
  9901. }
  9902. }
  9903. if (!className) {
  9904. return null;
  9905. }
  9906. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9907. };
  9908. /**
  9909. * 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.
  9910. * @param array
  9911. */
  9912. Tools.arrayOrStringFeeder = function (array) {
  9913. return function (index) {
  9914. if (index >= array.length) {
  9915. return null;
  9916. }
  9917. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9918. if (val && val.getHashCode) {
  9919. val = val.getHashCode();
  9920. }
  9921. if (typeof val === "string") {
  9922. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9923. }
  9924. return val;
  9925. };
  9926. };
  9927. /**
  9928. * Compute the hashCode of a stream of number
  9929. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9930. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9931. * @return the hash code computed
  9932. */
  9933. Tools.hashCodeFromStream = function (feeder) {
  9934. // Based from here: http://stackoverflow.com/a/7616484/802124
  9935. var hash = 0;
  9936. var index = 0;
  9937. var chr = feeder(index++);
  9938. while (chr != null) {
  9939. hash = ((hash << 5) - hash) + chr;
  9940. hash |= 0; // Convert to 32bit integer
  9941. chr = feeder(index++);
  9942. }
  9943. return hash;
  9944. };
  9945. /**
  9946. * Returns a promise that resolves after the given amount of time.
  9947. * @param delay Number of milliseconds to delay
  9948. * @returns Promise that resolves after the given amount of time
  9949. */
  9950. Tools.DelayAsync = function (delay) {
  9951. return new Promise(function (resolve) {
  9952. setTimeout(function () {
  9953. resolve();
  9954. }, delay);
  9955. });
  9956. };
  9957. Tools.BaseUrl = "";
  9958. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9959. /**
  9960. * Default behaviour for cors in the application.
  9961. * It can be a string if the expected behavior is identical in the entire app.
  9962. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9963. */
  9964. Tools.CorsBehavior = "anonymous";
  9965. Tools.UseFallbackTexture = true;
  9966. /**
  9967. * Use this object to register external classes like custom textures or material
  9968. * to allow the laoders to instantiate them
  9969. */
  9970. Tools.RegisteredExternalClasses = {};
  9971. // Used in case of a texture loading problem
  9972. 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";
  9973. Tools._tmpFloatArray = new Float32Array(1);
  9974. Tools.PreprocessUrl = function (url) {
  9975. return url;
  9976. };
  9977. // Logs
  9978. Tools._NoneLogLevel = 0;
  9979. Tools._MessageLogLevel = 1;
  9980. Tools._WarningLogLevel = 2;
  9981. Tools._ErrorLogLevel = 4;
  9982. Tools._LogCache = "";
  9983. Tools.errorsCount = 0;
  9984. Tools.Log = Tools._LogEnabled;
  9985. Tools.Warn = Tools._WarnEnabled;
  9986. Tools.Error = Tools._ErrorEnabled;
  9987. // Performances
  9988. Tools._PerformanceNoneLogLevel = 0;
  9989. Tools._PerformanceUserMarkLogLevel = 1;
  9990. Tools._PerformanceConsoleLogLevel = 2;
  9991. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9992. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9993. return Tools;
  9994. }());
  9995. BABYLON.Tools = Tools;
  9996. /**
  9997. * This class is used to track a performance counter which is number based.
  9998. * The user has access to many properties which give statistics of different nature
  9999. *
  10000. * The implementer can track two kinds of Performance Counter: time and count
  10001. * 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.
  10002. * 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.
  10003. */
  10004. var PerfCounter = /** @class */ (function () {
  10005. function PerfCounter() {
  10006. this._startMonitoringTime = 0;
  10007. this._min = 0;
  10008. this._max = 0;
  10009. this._average = 0;
  10010. this._lastSecAverage = 0;
  10011. this._current = 0;
  10012. this._totalValueCount = 0;
  10013. this._totalAccumulated = 0;
  10014. this._lastSecAccumulated = 0;
  10015. this._lastSecTime = 0;
  10016. this._lastSecValueCount = 0;
  10017. }
  10018. Object.defineProperty(PerfCounter.prototype, "min", {
  10019. /**
  10020. * Returns the smallest value ever
  10021. */
  10022. get: function () {
  10023. return this._min;
  10024. },
  10025. enumerable: true,
  10026. configurable: true
  10027. });
  10028. Object.defineProperty(PerfCounter.prototype, "max", {
  10029. /**
  10030. * Returns the biggest value ever
  10031. */
  10032. get: function () {
  10033. return this._max;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(PerfCounter.prototype, "average", {
  10039. /**
  10040. * Returns the average value since the performance counter is running
  10041. */
  10042. get: function () {
  10043. return this._average;
  10044. },
  10045. enumerable: true,
  10046. configurable: true
  10047. });
  10048. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10049. /**
  10050. * Returns the average value of the last second the counter was monitored
  10051. */
  10052. get: function () {
  10053. return this._lastSecAverage;
  10054. },
  10055. enumerable: true,
  10056. configurable: true
  10057. });
  10058. Object.defineProperty(PerfCounter.prototype, "current", {
  10059. /**
  10060. * Returns the current value
  10061. */
  10062. get: function () {
  10063. return this._current;
  10064. },
  10065. enumerable: true,
  10066. configurable: true
  10067. });
  10068. Object.defineProperty(PerfCounter.prototype, "total", {
  10069. get: function () {
  10070. return this._totalAccumulated;
  10071. },
  10072. enumerable: true,
  10073. configurable: true
  10074. });
  10075. Object.defineProperty(PerfCounter.prototype, "count", {
  10076. get: function () {
  10077. return this._totalValueCount;
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. /**
  10083. * Call this method to start monitoring a new frame.
  10084. * 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.
  10085. */
  10086. PerfCounter.prototype.fetchNewFrame = function () {
  10087. this._totalValueCount++;
  10088. this._current = 0;
  10089. this._lastSecValueCount++;
  10090. };
  10091. /**
  10092. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10093. * @param newCount the count value to add to the monitored count
  10094. * @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.
  10095. */
  10096. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10097. if (!PerfCounter.Enabled) {
  10098. return;
  10099. }
  10100. this._current += newCount;
  10101. if (fetchResult) {
  10102. this._fetchResult();
  10103. }
  10104. };
  10105. /**
  10106. * Start monitoring this performance counter
  10107. */
  10108. PerfCounter.prototype.beginMonitoring = function () {
  10109. if (!PerfCounter.Enabled) {
  10110. return;
  10111. }
  10112. this._startMonitoringTime = Tools.Now;
  10113. };
  10114. /**
  10115. * Compute the time lapsed since the previous beginMonitoring() call.
  10116. * @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
  10117. */
  10118. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10119. if (newFrame === void 0) { newFrame = true; }
  10120. if (!PerfCounter.Enabled) {
  10121. return;
  10122. }
  10123. if (newFrame) {
  10124. this.fetchNewFrame();
  10125. }
  10126. var currentTime = Tools.Now;
  10127. this._current = currentTime - this._startMonitoringTime;
  10128. if (newFrame) {
  10129. this._fetchResult();
  10130. }
  10131. };
  10132. PerfCounter.prototype._fetchResult = function () {
  10133. this._totalAccumulated += this._current;
  10134. this._lastSecAccumulated += this._current;
  10135. // Min/Max update
  10136. this._min = Math.min(this._min, this._current);
  10137. this._max = Math.max(this._max, this._current);
  10138. this._average = this._totalAccumulated / this._totalValueCount;
  10139. // Reset last sec?
  10140. var now = Tools.Now;
  10141. if ((now - this._lastSecTime) > 1000) {
  10142. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10143. this._lastSecTime = now;
  10144. this._lastSecAccumulated = 0;
  10145. this._lastSecValueCount = 0;
  10146. }
  10147. };
  10148. PerfCounter.Enabled = true;
  10149. return PerfCounter;
  10150. }());
  10151. BABYLON.PerfCounter = PerfCounter;
  10152. /**
  10153. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10154. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10155. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10156. * @param name The name of the class, case should be preserved
  10157. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10158. */
  10159. function className(name, module) {
  10160. return function (target) {
  10161. target["__bjsclassName__"] = name;
  10162. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10163. };
  10164. }
  10165. BABYLON.className = className;
  10166. /**
  10167. * An implementation of a loop for asynchronous functions.
  10168. */
  10169. var AsyncLoop = /** @class */ (function () {
  10170. /**
  10171. * Constroctor.
  10172. * @param iterations the number of iterations.
  10173. * @param _fn the function to run each iteration
  10174. * @param _successCallback the callback that will be called upon succesful execution
  10175. * @param offset starting offset.
  10176. */
  10177. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10178. if (offset === void 0) { offset = 0; }
  10179. this.iterations = iterations;
  10180. this._fn = _fn;
  10181. this._successCallback = _successCallback;
  10182. this.index = offset - 1;
  10183. this._done = false;
  10184. }
  10185. /**
  10186. * Execute the next iteration. Must be called after the last iteration was finished.
  10187. */
  10188. AsyncLoop.prototype.executeNext = function () {
  10189. if (!this._done) {
  10190. if (this.index + 1 < this.iterations) {
  10191. ++this.index;
  10192. this._fn(this);
  10193. }
  10194. else {
  10195. this.breakLoop();
  10196. }
  10197. }
  10198. };
  10199. /**
  10200. * Break the loop and run the success callback.
  10201. */
  10202. AsyncLoop.prototype.breakLoop = function () {
  10203. this._done = true;
  10204. this._successCallback();
  10205. };
  10206. /**
  10207. * Helper function
  10208. */
  10209. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10210. if (offset === void 0) { offset = 0; }
  10211. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10212. loop.executeNext();
  10213. return loop;
  10214. };
  10215. /**
  10216. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10217. * @param iterations total number of iterations
  10218. * @param syncedIterations number of synchronous iterations in each async iteration.
  10219. * @param fn the function to call each iteration.
  10220. * @param callback a success call back that will be called when iterating stops.
  10221. * @param breakFunction a break condition (optional)
  10222. * @param timeout timeout settings for the setTimeout function. default - 0.
  10223. * @constructor
  10224. */
  10225. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10226. if (timeout === void 0) { timeout = 0; }
  10227. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10228. if (breakFunction && breakFunction())
  10229. loop.breakLoop();
  10230. else {
  10231. setTimeout(function () {
  10232. for (var i = 0; i < syncedIterations; ++i) {
  10233. var iteration = (loop.index * syncedIterations) + i;
  10234. if (iteration >= iterations)
  10235. break;
  10236. fn(iteration);
  10237. if (breakFunction && breakFunction()) {
  10238. loop.breakLoop();
  10239. break;
  10240. }
  10241. }
  10242. loop.executeNext();
  10243. }, timeout);
  10244. }
  10245. }, callback);
  10246. };
  10247. return AsyncLoop;
  10248. }());
  10249. BABYLON.AsyncLoop = AsyncLoop;
  10250. })(BABYLON || (BABYLON = {}));
  10251. //# sourceMappingURL=babylon.tools.js.map
  10252. var BABYLON;
  10253. (function (BABYLON) {
  10254. var PromiseStates;
  10255. (function (PromiseStates) {
  10256. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10257. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10258. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10259. })(PromiseStates || (PromiseStates = {}));
  10260. var FulFillmentAgregator = /** @class */ (function () {
  10261. function FulFillmentAgregator() {
  10262. this.count = 0;
  10263. this.target = 0;
  10264. this.results = [];
  10265. }
  10266. return FulFillmentAgregator;
  10267. }());
  10268. var InternalPromise = /** @class */ (function () {
  10269. function InternalPromise(resolver) {
  10270. var _this = this;
  10271. this._state = PromiseStates.Pending;
  10272. this._children = new Array();
  10273. this._rejectWasConsumed = false;
  10274. if (!resolver) {
  10275. return;
  10276. }
  10277. try {
  10278. resolver(function (value) {
  10279. _this._resolve(value);
  10280. }, function (reason) {
  10281. _this._reject(reason);
  10282. });
  10283. }
  10284. catch (e) {
  10285. this._reject(e);
  10286. }
  10287. }
  10288. Object.defineProperty(InternalPromise.prototype, "_result", {
  10289. get: function () {
  10290. return this._resultValue;
  10291. },
  10292. set: function (value) {
  10293. this._resultValue = value;
  10294. if (this._parent && this._parent._result === undefined) {
  10295. this._parent._result = value;
  10296. }
  10297. },
  10298. enumerable: true,
  10299. configurable: true
  10300. });
  10301. InternalPromise.prototype.catch = function (onRejected) {
  10302. return this.then(undefined, onRejected);
  10303. };
  10304. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10305. var _this = this;
  10306. var newPromise = new InternalPromise();
  10307. newPromise._onFulfilled = onFulfilled;
  10308. newPromise._onRejected = onRejected;
  10309. // Composition
  10310. this._children.push(newPromise);
  10311. newPromise._parent = this;
  10312. if (this._state !== PromiseStates.Pending) {
  10313. BABYLON.Tools.SetImmediate(function () {
  10314. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10315. var returnedValue = newPromise._resolve(_this._result);
  10316. if (returnedValue !== undefined && returnedValue !== null) {
  10317. if (returnedValue._state !== undefined) {
  10318. var returnedPromise = returnedValue;
  10319. newPromise._children.push(returnedPromise);
  10320. returnedPromise._parent = newPromise;
  10321. newPromise = returnedPromise;
  10322. }
  10323. else {
  10324. newPromise._result = returnedValue;
  10325. }
  10326. }
  10327. }
  10328. else {
  10329. newPromise._reject(_this._reason);
  10330. }
  10331. });
  10332. }
  10333. return newPromise;
  10334. };
  10335. InternalPromise.prototype._moveChildren = function (children) {
  10336. var _this = this;
  10337. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10338. this._children.forEach(function (child) {
  10339. child._parent = _this;
  10340. });
  10341. if (this._state === PromiseStates.Fulfilled) {
  10342. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10343. var child = _b[_i];
  10344. child._resolve(this._result);
  10345. }
  10346. }
  10347. else if (this._state === PromiseStates.Rejected) {
  10348. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10349. var child = _d[_c];
  10350. child._reject(this._reason);
  10351. }
  10352. }
  10353. var _a;
  10354. };
  10355. InternalPromise.prototype._resolve = function (value) {
  10356. try {
  10357. this._state = PromiseStates.Fulfilled;
  10358. var returnedValue = null;
  10359. if (this._onFulfilled) {
  10360. returnedValue = this._onFulfilled(value);
  10361. }
  10362. if (returnedValue !== undefined && returnedValue !== null) {
  10363. if (returnedValue._state !== undefined) {
  10364. // Transmit children
  10365. var returnedPromise = returnedValue;
  10366. returnedPromise._parent = this;
  10367. returnedPromise._moveChildren(this._children);
  10368. value = returnedPromise._result;
  10369. }
  10370. else {
  10371. value = returnedValue;
  10372. }
  10373. }
  10374. this._result = value;
  10375. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10376. var child = _a[_i];
  10377. child._resolve(value);
  10378. }
  10379. this._children.length = 0;
  10380. delete this._onFulfilled;
  10381. delete this._onRejected;
  10382. }
  10383. catch (e) {
  10384. this._reject(e, true);
  10385. }
  10386. };
  10387. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10388. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10389. this._state = PromiseStates.Rejected;
  10390. this._reason = reason;
  10391. if (this._onRejected && !onLocalThrow) {
  10392. try {
  10393. this._onRejected(reason);
  10394. this._rejectWasConsumed = true;
  10395. }
  10396. catch (e) {
  10397. reason = e;
  10398. }
  10399. }
  10400. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10401. var child = _a[_i];
  10402. if (this._rejectWasConsumed) {
  10403. child._resolve(null);
  10404. }
  10405. else {
  10406. child._reject(reason);
  10407. }
  10408. }
  10409. this._children.length = 0;
  10410. delete this._onFulfilled;
  10411. delete this._onRejected;
  10412. };
  10413. InternalPromise.resolve = function (value) {
  10414. var newPromise = new InternalPromise();
  10415. newPromise._resolve(value);
  10416. return newPromise;
  10417. };
  10418. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10419. promise.then(function (value) {
  10420. agregator.results[index] = value;
  10421. agregator.count++;
  10422. if (agregator.count === agregator.target) {
  10423. agregator.rootPromise._resolve(agregator.results);
  10424. }
  10425. return null;
  10426. }, function (reason) {
  10427. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10428. agregator.rootPromise._reject(reason);
  10429. }
  10430. });
  10431. };
  10432. InternalPromise.all = function (promises) {
  10433. var newPromise = new InternalPromise();
  10434. var agregator = new FulFillmentAgregator();
  10435. agregator.target = promises.length;
  10436. agregator.rootPromise = newPromise;
  10437. if (promises.length) {
  10438. for (var index = 0; index < promises.length; index++) {
  10439. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10440. }
  10441. }
  10442. else {
  10443. newPromise._resolve([]);
  10444. }
  10445. return newPromise;
  10446. };
  10447. InternalPromise.race = function (promises) {
  10448. var newPromise = new InternalPromise();
  10449. if (promises.length) {
  10450. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10451. var promise = promises_1[_i];
  10452. promise.then(function (value) {
  10453. if (newPromise) {
  10454. newPromise._resolve(value);
  10455. newPromise = null;
  10456. }
  10457. return null;
  10458. }, function (reason) {
  10459. if (newPromise) {
  10460. newPromise._reject(reason);
  10461. newPromise = null;
  10462. }
  10463. });
  10464. }
  10465. }
  10466. return newPromise;
  10467. };
  10468. return InternalPromise;
  10469. }());
  10470. /**
  10471. * Helper class that provides a small promise polyfill
  10472. */
  10473. var PromisePolyfill = /** @class */ (function () {
  10474. function PromisePolyfill() {
  10475. }
  10476. /**
  10477. * Static function used to check if the polyfill is required
  10478. * If this is the case then the function will inject the polyfill to window.Promise
  10479. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10480. */
  10481. PromisePolyfill.Apply = function (force) {
  10482. if (force === void 0) { force = false; }
  10483. if (force || typeof Promise === 'undefined') {
  10484. var root = window;
  10485. root.Promise = InternalPromise;
  10486. }
  10487. };
  10488. return PromisePolyfill;
  10489. }());
  10490. BABYLON.PromisePolyfill = PromisePolyfill;
  10491. })(BABYLON || (BABYLON = {}));
  10492. //# sourceMappingURL=babylon.promise.js.map
  10493. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10494. var BABYLON;
  10495. (function (BABYLON) {
  10496. /**
  10497. * Helper class to push actions to a pool of workers.
  10498. */
  10499. var WorkerPool = /** @class */ (function () {
  10500. /**
  10501. * Constructor
  10502. * @param workers Array of workers to use for actions
  10503. */
  10504. function WorkerPool(workers) {
  10505. this._pendingActions = new Array();
  10506. this._workerInfos = workers.map(function (worker) { return ({
  10507. worker: worker,
  10508. active: false
  10509. }); });
  10510. }
  10511. /**
  10512. * Terminates all workers and clears any pending actions.
  10513. */
  10514. WorkerPool.prototype.dispose = function () {
  10515. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10516. var workerInfo = _a[_i];
  10517. workerInfo.worker.terminate();
  10518. }
  10519. delete this._workerInfos;
  10520. delete this._pendingActions;
  10521. };
  10522. /**
  10523. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10524. * pended until a worker has completed its action.
  10525. * @param action The action to perform. Call onComplete when the action is complete.
  10526. */
  10527. WorkerPool.prototype.push = function (action) {
  10528. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10529. var workerInfo = _a[_i];
  10530. if (!workerInfo.active) {
  10531. this._execute(workerInfo, action);
  10532. return;
  10533. }
  10534. }
  10535. this._pendingActions.push(action);
  10536. };
  10537. WorkerPool.prototype._execute = function (workerInfo, action) {
  10538. var _this = this;
  10539. workerInfo.active = true;
  10540. action(workerInfo.worker, function () {
  10541. workerInfo.active = false;
  10542. var nextAction = _this._pendingActions.shift();
  10543. if (nextAction) {
  10544. _this._execute(workerInfo, nextAction);
  10545. }
  10546. });
  10547. };
  10548. return WorkerPool;
  10549. }());
  10550. BABYLON.WorkerPool = WorkerPool;
  10551. })(BABYLON || (BABYLON = {}));
  10552. //# sourceMappingURL=babylon.workerPool.js.map
  10553. var BABYLON;
  10554. (function (BABYLON) {
  10555. /**
  10556. * @hidden
  10557. **/
  10558. var _AlphaState = /** @class */ (function () {
  10559. /**
  10560. * Initializes the state.
  10561. */
  10562. function _AlphaState() {
  10563. this._isAlphaBlendDirty = false;
  10564. this._isBlendFunctionParametersDirty = false;
  10565. this._isBlendEquationParametersDirty = false;
  10566. this._isBlendConstantsDirty = false;
  10567. this._alphaBlend = false;
  10568. this._blendFunctionParameters = new Array(4);
  10569. this._blendEquationParameters = new Array(2);
  10570. this._blendConstants = new Array(4);
  10571. this.reset();
  10572. }
  10573. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10574. get: function () {
  10575. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10576. },
  10577. enumerable: true,
  10578. configurable: true
  10579. });
  10580. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10581. get: function () {
  10582. return this._alphaBlend;
  10583. },
  10584. set: function (value) {
  10585. if (this._alphaBlend === value) {
  10586. return;
  10587. }
  10588. this._alphaBlend = value;
  10589. this._isAlphaBlendDirty = true;
  10590. },
  10591. enumerable: true,
  10592. configurable: true
  10593. });
  10594. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10595. if (this._blendConstants[0] === r &&
  10596. this._blendConstants[1] === g &&
  10597. this._blendConstants[2] === b &&
  10598. this._blendConstants[3] === a) {
  10599. return;
  10600. }
  10601. this._blendConstants[0] = r;
  10602. this._blendConstants[1] = g;
  10603. this._blendConstants[2] = b;
  10604. this._blendConstants[3] = a;
  10605. this._isBlendConstantsDirty = true;
  10606. };
  10607. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10608. if (this._blendFunctionParameters[0] === value0 &&
  10609. this._blendFunctionParameters[1] === value1 &&
  10610. this._blendFunctionParameters[2] === value2 &&
  10611. this._blendFunctionParameters[3] === value3) {
  10612. return;
  10613. }
  10614. this._blendFunctionParameters[0] = value0;
  10615. this._blendFunctionParameters[1] = value1;
  10616. this._blendFunctionParameters[2] = value2;
  10617. this._blendFunctionParameters[3] = value3;
  10618. this._isBlendFunctionParametersDirty = true;
  10619. };
  10620. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10621. if (this._blendEquationParameters[0] === rgb &&
  10622. this._blendEquationParameters[1] === alpha) {
  10623. return;
  10624. }
  10625. this._blendEquationParameters[0] = rgb;
  10626. this._blendEquationParameters[1] = alpha;
  10627. this._isBlendEquationParametersDirty = true;
  10628. };
  10629. _AlphaState.prototype.reset = function () {
  10630. this._alphaBlend = false;
  10631. this._blendFunctionParameters[0] = null;
  10632. this._blendFunctionParameters[1] = null;
  10633. this._blendFunctionParameters[2] = null;
  10634. this._blendFunctionParameters[3] = null;
  10635. this._blendEquationParameters[0] = null;
  10636. this._blendEquationParameters[1] = null;
  10637. this._blendConstants[0] = null;
  10638. this._blendConstants[1] = null;
  10639. this._blendConstants[2] = null;
  10640. this._blendConstants[3] = null;
  10641. this._isAlphaBlendDirty = true;
  10642. this._isBlendFunctionParametersDirty = false;
  10643. this._isBlendEquationParametersDirty = false;
  10644. this._isBlendConstantsDirty = false;
  10645. };
  10646. _AlphaState.prototype.apply = function (gl) {
  10647. if (!this.isDirty) {
  10648. return;
  10649. }
  10650. // Alpha blend
  10651. if (this._isAlphaBlendDirty) {
  10652. if (this._alphaBlend) {
  10653. gl.enable(gl.BLEND);
  10654. }
  10655. else {
  10656. gl.disable(gl.BLEND);
  10657. }
  10658. this._isAlphaBlendDirty = false;
  10659. }
  10660. // Alpha function
  10661. if (this._isBlendFunctionParametersDirty) {
  10662. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10663. this._isBlendFunctionParametersDirty = false;
  10664. }
  10665. // Alpha equation
  10666. if (this._isBlendEquationParametersDirty) {
  10667. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10668. this._isBlendEquationParametersDirty = false;
  10669. }
  10670. // Constants
  10671. if (this._isBlendConstantsDirty) {
  10672. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10673. this._isBlendConstantsDirty = false;
  10674. }
  10675. };
  10676. return _AlphaState;
  10677. }());
  10678. BABYLON._AlphaState = _AlphaState;
  10679. })(BABYLON || (BABYLON = {}));
  10680. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10681. var BABYLON;
  10682. (function (BABYLON) {
  10683. /**
  10684. * @hidden
  10685. **/
  10686. var _DepthCullingState = /** @class */ (function () {
  10687. /**
  10688. * Initializes the state.
  10689. */
  10690. function _DepthCullingState() {
  10691. this._isDepthTestDirty = false;
  10692. this._isDepthMaskDirty = false;
  10693. this._isDepthFuncDirty = false;
  10694. this._isCullFaceDirty = false;
  10695. this._isCullDirty = false;
  10696. this._isZOffsetDirty = false;
  10697. this._isFrontFaceDirty = false;
  10698. this.reset();
  10699. }
  10700. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10701. get: function () {
  10702. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10703. },
  10704. enumerable: true,
  10705. configurable: true
  10706. });
  10707. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10708. get: function () {
  10709. return this._zOffset;
  10710. },
  10711. set: function (value) {
  10712. if (this._zOffset === value) {
  10713. return;
  10714. }
  10715. this._zOffset = value;
  10716. this._isZOffsetDirty = true;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10722. get: function () {
  10723. return this._cullFace;
  10724. },
  10725. set: function (value) {
  10726. if (this._cullFace === value) {
  10727. return;
  10728. }
  10729. this._cullFace = value;
  10730. this._isCullFaceDirty = true;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10736. get: function () {
  10737. return this._cull;
  10738. },
  10739. set: function (value) {
  10740. if (this._cull === value) {
  10741. return;
  10742. }
  10743. this._cull = value;
  10744. this._isCullDirty = true;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10750. get: function () {
  10751. return this._depthFunc;
  10752. },
  10753. set: function (value) {
  10754. if (this._depthFunc === value) {
  10755. return;
  10756. }
  10757. this._depthFunc = value;
  10758. this._isDepthFuncDirty = true;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10764. get: function () {
  10765. return this._depthMask;
  10766. },
  10767. set: function (value) {
  10768. if (this._depthMask === value) {
  10769. return;
  10770. }
  10771. this._depthMask = value;
  10772. this._isDepthMaskDirty = true;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10778. get: function () {
  10779. return this._depthTest;
  10780. },
  10781. set: function (value) {
  10782. if (this._depthTest === value) {
  10783. return;
  10784. }
  10785. this._depthTest = value;
  10786. this._isDepthTestDirty = true;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10792. get: function () {
  10793. return this._frontFace;
  10794. },
  10795. set: function (value) {
  10796. if (this._frontFace === value) {
  10797. return;
  10798. }
  10799. this._frontFace = value;
  10800. this._isFrontFaceDirty = true;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. _DepthCullingState.prototype.reset = function () {
  10806. this._depthMask = true;
  10807. this._depthTest = true;
  10808. this._depthFunc = null;
  10809. this._cullFace = null;
  10810. this._cull = null;
  10811. this._zOffset = 0;
  10812. this._frontFace = null;
  10813. this._isDepthTestDirty = true;
  10814. this._isDepthMaskDirty = true;
  10815. this._isDepthFuncDirty = false;
  10816. this._isCullFaceDirty = false;
  10817. this._isCullDirty = false;
  10818. this._isZOffsetDirty = false;
  10819. this._isFrontFaceDirty = false;
  10820. };
  10821. _DepthCullingState.prototype.apply = function (gl) {
  10822. if (!this.isDirty) {
  10823. return;
  10824. }
  10825. // Cull
  10826. if (this._isCullDirty) {
  10827. if (this.cull) {
  10828. gl.enable(gl.CULL_FACE);
  10829. }
  10830. else {
  10831. gl.disable(gl.CULL_FACE);
  10832. }
  10833. this._isCullDirty = false;
  10834. }
  10835. // Cull face
  10836. if (this._isCullFaceDirty) {
  10837. gl.cullFace(this.cullFace);
  10838. this._isCullFaceDirty = false;
  10839. }
  10840. // Depth mask
  10841. if (this._isDepthMaskDirty) {
  10842. gl.depthMask(this.depthMask);
  10843. this._isDepthMaskDirty = false;
  10844. }
  10845. // Depth test
  10846. if (this._isDepthTestDirty) {
  10847. if (this.depthTest) {
  10848. gl.enable(gl.DEPTH_TEST);
  10849. }
  10850. else {
  10851. gl.disable(gl.DEPTH_TEST);
  10852. }
  10853. this._isDepthTestDirty = false;
  10854. }
  10855. // Depth func
  10856. if (this._isDepthFuncDirty) {
  10857. gl.depthFunc(this.depthFunc);
  10858. this._isDepthFuncDirty = false;
  10859. }
  10860. // zOffset
  10861. if (this._isZOffsetDirty) {
  10862. if (this.zOffset) {
  10863. gl.enable(gl.POLYGON_OFFSET_FILL);
  10864. gl.polygonOffset(this.zOffset, 0);
  10865. }
  10866. else {
  10867. gl.disable(gl.POLYGON_OFFSET_FILL);
  10868. }
  10869. this._isZOffsetDirty = false;
  10870. }
  10871. // Front face
  10872. if (this._isFrontFaceDirty) {
  10873. gl.frontFace(this.frontFace);
  10874. this._isFrontFaceDirty = false;
  10875. }
  10876. };
  10877. return _DepthCullingState;
  10878. }());
  10879. BABYLON._DepthCullingState = _DepthCullingState;
  10880. })(BABYLON || (BABYLON = {}));
  10881. //# sourceMappingURL=babylon.depthCullingState.js.map
  10882. var BABYLON;
  10883. (function (BABYLON) {
  10884. /**
  10885. * @hidden
  10886. **/
  10887. var _StencilState = /** @class */ (function () {
  10888. function _StencilState() {
  10889. this._isStencilTestDirty = false;
  10890. this._isStencilMaskDirty = false;
  10891. this._isStencilFuncDirty = false;
  10892. this._isStencilOpDirty = false;
  10893. this.reset();
  10894. }
  10895. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10896. get: function () {
  10897. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10903. get: function () {
  10904. return this._stencilFunc;
  10905. },
  10906. set: function (value) {
  10907. if (this._stencilFunc === value) {
  10908. return;
  10909. }
  10910. this._stencilFunc = value;
  10911. this._isStencilFuncDirty = true;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10917. get: function () {
  10918. return this._stencilFuncRef;
  10919. },
  10920. set: function (value) {
  10921. if (this._stencilFuncRef === value) {
  10922. return;
  10923. }
  10924. this._stencilFuncRef = value;
  10925. this._isStencilFuncDirty = true;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10931. get: function () {
  10932. return this._stencilFuncMask;
  10933. },
  10934. set: function (value) {
  10935. if (this._stencilFuncMask === value) {
  10936. return;
  10937. }
  10938. this._stencilFuncMask = value;
  10939. this._isStencilFuncDirty = true;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10945. get: function () {
  10946. return this._stencilOpStencilFail;
  10947. },
  10948. set: function (value) {
  10949. if (this._stencilOpStencilFail === value) {
  10950. return;
  10951. }
  10952. this._stencilOpStencilFail = value;
  10953. this._isStencilOpDirty = true;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10959. get: function () {
  10960. return this._stencilOpDepthFail;
  10961. },
  10962. set: function (value) {
  10963. if (this._stencilOpDepthFail === value) {
  10964. return;
  10965. }
  10966. this._stencilOpDepthFail = value;
  10967. this._isStencilOpDirty = true;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10973. get: function () {
  10974. return this._stencilOpStencilDepthPass;
  10975. },
  10976. set: function (value) {
  10977. if (this._stencilOpStencilDepthPass === value) {
  10978. return;
  10979. }
  10980. this._stencilOpStencilDepthPass = value;
  10981. this._isStencilOpDirty = true;
  10982. },
  10983. enumerable: true,
  10984. configurable: true
  10985. });
  10986. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10987. get: function () {
  10988. return this._stencilMask;
  10989. },
  10990. set: function (value) {
  10991. if (this._stencilMask === value) {
  10992. return;
  10993. }
  10994. this._stencilMask = value;
  10995. this._isStencilMaskDirty = true;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11001. get: function () {
  11002. return this._stencilTest;
  11003. },
  11004. set: function (value) {
  11005. if (this._stencilTest === value) {
  11006. return;
  11007. }
  11008. this._stencilTest = value;
  11009. this._isStencilTestDirty = true;
  11010. },
  11011. enumerable: true,
  11012. configurable: true
  11013. });
  11014. _StencilState.prototype.reset = function () {
  11015. this._stencilTest = false;
  11016. this._stencilMask = 0xFF;
  11017. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11018. this._stencilFuncRef = 1;
  11019. this._stencilFuncMask = 0xFF;
  11020. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11021. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11022. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11023. this._isStencilTestDirty = true;
  11024. this._isStencilMaskDirty = true;
  11025. this._isStencilFuncDirty = true;
  11026. this._isStencilOpDirty = true;
  11027. };
  11028. _StencilState.prototype.apply = function (gl) {
  11029. if (!this.isDirty) {
  11030. return;
  11031. }
  11032. // Stencil test
  11033. if (this._isStencilTestDirty) {
  11034. if (this.stencilTest) {
  11035. gl.enable(gl.STENCIL_TEST);
  11036. }
  11037. else {
  11038. gl.disable(gl.STENCIL_TEST);
  11039. }
  11040. this._isStencilTestDirty = false;
  11041. }
  11042. // Stencil mask
  11043. if (this._isStencilMaskDirty) {
  11044. gl.stencilMask(this.stencilMask);
  11045. this._isStencilMaskDirty = false;
  11046. }
  11047. // Stencil func
  11048. if (this._isStencilFuncDirty) {
  11049. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11050. this._isStencilFuncDirty = false;
  11051. }
  11052. // Stencil op
  11053. if (this._isStencilOpDirty) {
  11054. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11055. this._isStencilOpDirty = false;
  11056. }
  11057. };
  11058. return _StencilState;
  11059. }());
  11060. BABYLON._StencilState = _StencilState;
  11061. })(BABYLON || (BABYLON = {}));
  11062. //# sourceMappingURL=babylon.stencilState.js.map
  11063. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11064. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11065. s = arguments[i];
  11066. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11067. t[p] = s[p];
  11068. }
  11069. return t;
  11070. };
  11071. var BABYLON;
  11072. (function (BABYLON) {
  11073. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11074. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11075. };
  11076. var compileRawShader = function (gl, source, type) {
  11077. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11078. gl.shaderSource(shader, source);
  11079. gl.compileShader(shader);
  11080. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11081. var log = gl.getShaderInfoLog(shader);
  11082. if (log) {
  11083. throw new Error(log);
  11084. }
  11085. }
  11086. if (!shader) {
  11087. throw new Error("Something went wrong while compile the shader.");
  11088. }
  11089. return shader;
  11090. };
  11091. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11092. var magFilter = gl.NEAREST;
  11093. var minFilter = gl.NEAREST;
  11094. switch (samplingMode) {
  11095. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11096. magFilter = gl.LINEAR;
  11097. if (generateMipMaps) {
  11098. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11099. }
  11100. else {
  11101. minFilter = gl.LINEAR;
  11102. }
  11103. break;
  11104. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11105. magFilter = gl.LINEAR;
  11106. if (generateMipMaps) {
  11107. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11108. }
  11109. else {
  11110. minFilter = gl.LINEAR;
  11111. }
  11112. break;
  11113. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11114. magFilter = gl.NEAREST;
  11115. if (generateMipMaps) {
  11116. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11117. }
  11118. else {
  11119. minFilter = gl.NEAREST;
  11120. }
  11121. break;
  11122. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11123. magFilter = gl.NEAREST;
  11124. if (generateMipMaps) {
  11125. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11126. }
  11127. else {
  11128. minFilter = gl.NEAREST;
  11129. }
  11130. break;
  11131. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11132. magFilter = gl.NEAREST;
  11133. if (generateMipMaps) {
  11134. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11135. }
  11136. else {
  11137. minFilter = gl.LINEAR;
  11138. }
  11139. break;
  11140. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11141. magFilter = gl.NEAREST;
  11142. if (generateMipMaps) {
  11143. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11144. }
  11145. else {
  11146. minFilter = gl.LINEAR;
  11147. }
  11148. break;
  11149. case BABYLON.Texture.NEAREST_LINEAR:
  11150. magFilter = gl.NEAREST;
  11151. minFilter = gl.LINEAR;
  11152. break;
  11153. case BABYLON.Texture.NEAREST_NEAREST:
  11154. magFilter = gl.NEAREST;
  11155. minFilter = gl.NEAREST;
  11156. break;
  11157. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11158. magFilter = gl.LINEAR;
  11159. if (generateMipMaps) {
  11160. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11161. }
  11162. else {
  11163. minFilter = gl.NEAREST;
  11164. }
  11165. break;
  11166. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11167. magFilter = gl.LINEAR;
  11168. if (generateMipMaps) {
  11169. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11170. }
  11171. else {
  11172. minFilter = gl.NEAREST;
  11173. }
  11174. break;
  11175. case BABYLON.Texture.LINEAR_LINEAR:
  11176. magFilter = gl.LINEAR;
  11177. minFilter = gl.LINEAR;
  11178. break;
  11179. case BABYLON.Texture.LINEAR_NEAREST:
  11180. magFilter = gl.LINEAR;
  11181. minFilter = gl.NEAREST;
  11182. break;
  11183. }
  11184. return {
  11185. min: minFilter,
  11186. mag: magFilter
  11187. };
  11188. };
  11189. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11190. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11191. var img;
  11192. var onload = function () {
  11193. loadedImages[index] = img;
  11194. loadedImages._internalCount++;
  11195. if (scene) {
  11196. scene._removePendingData(img);
  11197. }
  11198. if (loadedImages._internalCount === 6) {
  11199. onfinish(loadedImages);
  11200. }
  11201. };
  11202. var onerror = function (message, exception) {
  11203. if (scene) {
  11204. scene._removePendingData(img);
  11205. }
  11206. if (onErrorCallBack) {
  11207. onErrorCallBack(message, exception);
  11208. }
  11209. };
  11210. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11211. if (scene) {
  11212. scene._addPendingData(img);
  11213. }
  11214. };
  11215. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11216. if (onError === void 0) { onError = null; }
  11217. var loadedImages = [];
  11218. loadedImages._internalCount = 0;
  11219. for (var index = 0; index < 6; index++) {
  11220. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11221. }
  11222. };
  11223. var BufferPointer = /** @class */ (function () {
  11224. function BufferPointer() {
  11225. }
  11226. return BufferPointer;
  11227. }());
  11228. /**
  11229. * Interface for attribute information associated with buffer instanciation
  11230. */
  11231. var InstancingAttributeInfo = /** @class */ (function () {
  11232. function InstancingAttributeInfo() {
  11233. }
  11234. return InstancingAttributeInfo;
  11235. }());
  11236. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11237. /**
  11238. * Define options used to create a render target texture
  11239. */
  11240. var RenderTargetCreationOptions = /** @class */ (function () {
  11241. function RenderTargetCreationOptions() {
  11242. }
  11243. return RenderTargetCreationOptions;
  11244. }());
  11245. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11246. /**
  11247. * Define options used to create a depth texture
  11248. */
  11249. var DepthTextureCreationOptions = /** @class */ (function () {
  11250. function DepthTextureCreationOptions() {
  11251. }
  11252. return DepthTextureCreationOptions;
  11253. }());
  11254. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11255. /**
  11256. * Class used to describe the capabilities of the engine relatively to the current browser
  11257. */
  11258. var EngineCapabilities = /** @class */ (function () {
  11259. function EngineCapabilities() {
  11260. }
  11261. return EngineCapabilities;
  11262. }());
  11263. BABYLON.EngineCapabilities = EngineCapabilities;
  11264. /**
  11265. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11266. */
  11267. var Engine = /** @class */ (function () {
  11268. /**
  11269. * Creates a new engine
  11270. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11271. * @param antialias defines enable antialiasing (default: false)
  11272. * @param options defines further options to be sent to the getContext() function
  11273. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11274. */
  11275. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11276. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11277. var _this = this;
  11278. // Public members
  11279. /**
  11280. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11281. */
  11282. this.forcePOTTextures = false;
  11283. /**
  11284. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11285. */
  11286. this.isFullscreen = false;
  11287. /**
  11288. * Gets a boolean indicating if the pointer is currently locked
  11289. */
  11290. this.isPointerLock = false;
  11291. /**
  11292. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11293. */
  11294. this.cullBackFaces = true;
  11295. /**
  11296. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11297. */
  11298. this.renderEvenInBackground = true;
  11299. /**
  11300. * Gets or sets a boolean indicating that cache can be kept between frames
  11301. */
  11302. this.preventCacheWipeBetweenFrames = false;
  11303. /**
  11304. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11305. **/
  11306. this.enableOfflineSupport = false;
  11307. /**
  11308. * 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)
  11309. **/
  11310. this.disableManifestCheck = false;
  11311. /**
  11312. * Gets the list of created scenes
  11313. */
  11314. this.scenes = new Array();
  11315. /**
  11316. * Gets the list of created postprocesses
  11317. */
  11318. this.postProcesses = new Array();
  11319. // Observables
  11320. /**
  11321. * Observable event triggered each time the rendering canvas is resized
  11322. */
  11323. this.onResizeObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable event triggered each time the canvas loses focus
  11326. */
  11327. this.onCanvasBlurObservable = new BABYLON.Observable();
  11328. /**
  11329. * Observable event triggered each time the canvas gains focus
  11330. */
  11331. this.onCanvasFocusObservable = new BABYLON.Observable();
  11332. /**
  11333. * Observable event triggered each time the canvas receives pointerout event
  11334. */
  11335. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11336. /**
  11337. * Observable event triggered before each texture is initialized
  11338. */
  11339. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11340. //WebVR
  11341. this._vrDisplay = undefined;
  11342. this._vrSupported = false;
  11343. this._vrExclusivePointerMode = false;
  11344. // Uniform buffers list
  11345. /**
  11346. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11347. */
  11348. this.disableUniformBuffers = false;
  11349. /** @hidden */
  11350. this._uniformBuffers = new Array();
  11351. // Observables
  11352. /**
  11353. * Observable raised when the engine begins a new frame
  11354. */
  11355. this.onBeginFrameObservable = new BABYLON.Observable();
  11356. /**
  11357. * Observable raised when the engine ends the current frame
  11358. */
  11359. this.onEndFrameObservable = new BABYLON.Observable();
  11360. /**
  11361. * Observable raised when the engine is about to compile a shader
  11362. */
  11363. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11364. /**
  11365. * Observable raised when the engine has jsut compiled a shader
  11366. */
  11367. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11368. this._windowIsBackground = false;
  11369. this._webGLVersion = 1.0;
  11370. /** @hidden */
  11371. this._badOS = false;
  11372. /** @hidden */
  11373. this._badDesktopOS = false;
  11374. /**
  11375. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11376. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11377. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11378. */
  11379. this.disableTextureBindingOptimization = false;
  11380. /**
  11381. * Observable signaled when VR display mode changes
  11382. */
  11383. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable signaled when VR request present is complete
  11386. */
  11387. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11388. /**
  11389. * Observable signaled when VR request present starts
  11390. */
  11391. this.onVRRequestPresentStart = new BABYLON.Observable();
  11392. this._colorWrite = true;
  11393. /** @hidden */
  11394. this._drawCalls = new BABYLON.PerfCounter();
  11395. /** @hidden */
  11396. this._textureCollisions = new BABYLON.PerfCounter();
  11397. this._renderingQueueLaunched = false;
  11398. this._activeRenderLoops = new Array();
  11399. // Deterministic lockstepMaxSteps
  11400. this._deterministicLockstep = false;
  11401. this._lockstepMaxSteps = 4;
  11402. // Lost context
  11403. /**
  11404. * Observable signaled when a context lost event is raised
  11405. */
  11406. this.onContextLostObservable = new BABYLON.Observable();
  11407. /**
  11408. * Observable signaled when a context restored event is raised
  11409. */
  11410. this.onContextRestoredObservable = new BABYLON.Observable();
  11411. this._contextWasLost = false;
  11412. this._doNotHandleContextLost = false;
  11413. // FPS
  11414. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11415. this._fps = 60;
  11416. this._deltaTime = 0;
  11417. /**
  11418. * Turn this value on if you want to pause FPS computation when in background
  11419. */
  11420. this.disablePerformanceMonitorInBackground = false;
  11421. // States
  11422. /** @hidden */
  11423. this._depthCullingState = new BABYLON._DepthCullingState();
  11424. /** @hidden */
  11425. this._stencilState = new BABYLON._StencilState();
  11426. /** @hidden */
  11427. this._alphaState = new BABYLON._AlphaState();
  11428. /** @hidden */
  11429. this._alphaMode = Engine.ALPHA_DISABLE;
  11430. // Cache
  11431. this._internalTexturesCache = new Array();
  11432. /** @hidden */
  11433. this._activeChannel = 0;
  11434. this._currentTextureChannel = -1;
  11435. /** @hidden */
  11436. this._boundTexturesCache = {};
  11437. this._compiledEffects = {};
  11438. this._vertexAttribArraysEnabled = [];
  11439. this._uintIndicesCurrentlySet = false;
  11440. this._currentBoundBuffer = new Array();
  11441. this._currentBufferPointers = new Array();
  11442. this._currentInstanceLocations = new Array();
  11443. this._currentInstanceBuffers = new Array();
  11444. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11445. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11446. this._vaoRecordInProgress = false;
  11447. this._mustWipeVertexAttributes = false;
  11448. this._nextFreeTextureSlots = new Array();
  11449. this._maxSimultaneousTextures = 0;
  11450. this._activeRequests = new Array();
  11451. // Hardware supported Compressed Textures
  11452. this._texturesSupported = new Array();
  11453. this._onVRFullScreenTriggered = function () {
  11454. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11455. //get the old size before we change
  11456. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11457. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11458. //get the width and height, change the render size
  11459. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11460. _this.setHardwareScalingLevel(1);
  11461. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11462. }
  11463. else {
  11464. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11465. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11466. }
  11467. };
  11468. this._boundUniforms = {};
  11469. // Register promises
  11470. BABYLON.PromisePolyfill.Apply();
  11471. var canvas = null;
  11472. Engine.Instances.push(this);
  11473. if (!canvasOrContext) {
  11474. return;
  11475. }
  11476. options = options || {};
  11477. if (canvasOrContext.getContext) {
  11478. canvas = canvasOrContext;
  11479. this._renderingCanvas = canvas;
  11480. if (antialias != null) {
  11481. options.antialias = antialias;
  11482. }
  11483. if (options.deterministicLockstep === undefined) {
  11484. options.deterministicLockstep = false;
  11485. }
  11486. if (options.lockstepMaxSteps === undefined) {
  11487. options.lockstepMaxSteps = 4;
  11488. }
  11489. if (options.preserveDrawingBuffer === undefined) {
  11490. options.preserveDrawingBuffer = false;
  11491. }
  11492. if (options.audioEngine === undefined) {
  11493. options.audioEngine = true;
  11494. }
  11495. if (options.stencil === undefined) {
  11496. options.stencil = true;
  11497. }
  11498. this._deterministicLockstep = options.deterministicLockstep;
  11499. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11500. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11501. // Exceptions
  11502. if (navigator && navigator.userAgent) {
  11503. var ua = navigator.userAgent;
  11504. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11505. var exception = _a[_i];
  11506. var key = exception.key;
  11507. var targets = exception.targets;
  11508. if (ua.indexOf(key) > -1) {
  11509. if (exception.capture && exception.captureConstraint) {
  11510. var capture = exception.capture;
  11511. var constraint = exception.captureConstraint;
  11512. var regex = new RegExp(capture);
  11513. var matches = regex.exec(ua);
  11514. if (matches && matches.length > 0) {
  11515. var capturedValue = parseInt(matches[matches.length - 1]);
  11516. if (capturedValue >= constraint) {
  11517. continue;
  11518. }
  11519. }
  11520. }
  11521. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11522. var target = targets_1[_b];
  11523. switch (target) {
  11524. case "uniformBuffer":
  11525. this.disableUniformBuffers = true;
  11526. break;
  11527. case "textureBindingOptimization":
  11528. this.disableTextureBindingOptimization = true;
  11529. break;
  11530. }
  11531. }
  11532. }
  11533. }
  11534. }
  11535. // GL
  11536. if (!options.disableWebGL2Support) {
  11537. try {
  11538. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11539. if (this._gl) {
  11540. this._webGLVersion = 2.0;
  11541. }
  11542. }
  11543. catch (e) {
  11544. // Do nothing
  11545. }
  11546. }
  11547. if (!this._gl) {
  11548. if (!canvas) {
  11549. throw new Error("The provided canvas is null or undefined.");
  11550. }
  11551. try {
  11552. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11553. }
  11554. catch (e) {
  11555. throw new Error("WebGL not supported");
  11556. }
  11557. }
  11558. if (!this._gl) {
  11559. throw new Error("WebGL not supported");
  11560. }
  11561. this._onCanvasFocus = function () {
  11562. _this.onCanvasFocusObservable.notifyObservers(_this);
  11563. };
  11564. this._onCanvasBlur = function () {
  11565. _this.onCanvasBlurObservable.notifyObservers(_this);
  11566. };
  11567. canvas.addEventListener("focus", this._onCanvasFocus);
  11568. canvas.addEventListener("blur", this._onCanvasBlur);
  11569. this._onBlur = function () {
  11570. if (_this.disablePerformanceMonitorInBackground) {
  11571. _this._performanceMonitor.disable();
  11572. }
  11573. _this._windowIsBackground = true;
  11574. };
  11575. this._onFocus = function () {
  11576. if (_this.disablePerformanceMonitorInBackground) {
  11577. _this._performanceMonitor.enable();
  11578. }
  11579. _this._windowIsBackground = false;
  11580. };
  11581. this._onCanvasPointerOut = function (ev) {
  11582. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11583. };
  11584. window.addEventListener("blur", this._onBlur);
  11585. window.addEventListener("focus", this._onFocus);
  11586. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11587. // Context lost
  11588. if (!this._doNotHandleContextLost) {
  11589. this._onContextLost = function (evt) {
  11590. evt.preventDefault();
  11591. _this._contextWasLost = true;
  11592. BABYLON.Tools.Warn("WebGL context lost.");
  11593. _this.onContextLostObservable.notifyObservers(_this);
  11594. };
  11595. this._onContextRestored = function (evt) {
  11596. // Adding a timeout to avoid race condition at browser level
  11597. setTimeout(function () {
  11598. // Rebuild gl context
  11599. _this._initGLContext();
  11600. // Rebuild effects
  11601. _this._rebuildEffects();
  11602. // Rebuild textures
  11603. _this._rebuildInternalTextures();
  11604. // Rebuild buffers
  11605. _this._rebuildBuffers();
  11606. // Cache
  11607. _this.wipeCaches(true);
  11608. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11609. _this.onContextRestoredObservable.notifyObservers(_this);
  11610. _this._contextWasLost = false;
  11611. }, 0);
  11612. };
  11613. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11614. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11615. }
  11616. }
  11617. else {
  11618. this._gl = canvasOrContext;
  11619. this._renderingCanvas = this._gl.canvas;
  11620. if (this._gl.renderbufferStorageMultisample) {
  11621. this._webGLVersion = 2.0;
  11622. }
  11623. options.stencil = this._gl.getContextAttributes().stencil;
  11624. }
  11625. // Viewport
  11626. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11627. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11628. this.resize();
  11629. this._isStencilEnable = options.stencil ? true : false;
  11630. this._initGLContext();
  11631. if (canvas) {
  11632. // Fullscreen
  11633. this._onFullscreenChange = function () {
  11634. if (document.fullscreen !== undefined) {
  11635. _this.isFullscreen = document.fullscreen;
  11636. }
  11637. else if (document.mozFullScreen !== undefined) {
  11638. _this.isFullscreen = document.mozFullScreen;
  11639. }
  11640. else if (document.webkitIsFullScreen !== undefined) {
  11641. _this.isFullscreen = document.webkitIsFullScreen;
  11642. }
  11643. else if (document.msIsFullScreen !== undefined) {
  11644. _this.isFullscreen = document.msIsFullScreen;
  11645. }
  11646. // Pointer lock
  11647. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11648. canvas.requestPointerLock = canvas.requestPointerLock ||
  11649. canvas.msRequestPointerLock ||
  11650. canvas.mozRequestPointerLock ||
  11651. canvas.webkitRequestPointerLock;
  11652. if (canvas.requestPointerLock) {
  11653. canvas.requestPointerLock();
  11654. }
  11655. }
  11656. };
  11657. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11658. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11659. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11660. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11661. // Pointer lock
  11662. this._onPointerLockChange = function () {
  11663. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11664. document.webkitPointerLockElement === canvas ||
  11665. document.msPointerLockElement === canvas ||
  11666. document.pointerLockElement === canvas);
  11667. };
  11668. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11669. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11670. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11671. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11672. this._onVRDisplayPointerRestricted = function () {
  11673. if (canvas) {
  11674. canvas.requestPointerLock();
  11675. }
  11676. };
  11677. this._onVRDisplayPointerUnrestricted = function () {
  11678. document.exitPointerLock();
  11679. };
  11680. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11681. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11682. }
  11683. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11684. Engine.audioEngine = new BABYLON.AudioEngine();
  11685. }
  11686. // Prepare buffer pointers
  11687. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11688. this._currentBufferPointers[i] = new BufferPointer();
  11689. }
  11690. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11691. // Load WebVR Devices
  11692. if (options.autoEnableWebVR) {
  11693. this.initWebVR();
  11694. }
  11695. // Detect if we are running on a faulty buggy OS.
  11696. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11697. // Detect if we are running on a faulty buggy desktop OS.
  11698. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11699. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11700. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11701. }
  11702. Object.defineProperty(Engine, "LastCreatedEngine", {
  11703. /**
  11704. * Gets the latest created engine
  11705. */
  11706. get: function () {
  11707. if (Engine.Instances.length === 0) {
  11708. return null;
  11709. }
  11710. return Engine.Instances[Engine.Instances.length - 1];
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "LastCreatedScene", {
  11716. /**
  11717. * Gets the latest created scene
  11718. */
  11719. get: function () {
  11720. var lastCreatedEngine = Engine.LastCreatedEngine;
  11721. if (!lastCreatedEngine) {
  11722. return null;
  11723. }
  11724. if (lastCreatedEngine.scenes.length === 0) {
  11725. return null;
  11726. }
  11727. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11728. },
  11729. enumerable: true,
  11730. configurable: true
  11731. });
  11732. /**
  11733. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11734. * @param flag defines which part of the materials must be marked as dirty
  11735. * @param predicate defines a predicate used to filter which materials should be affected
  11736. */
  11737. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11738. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11739. var engine = Engine.Instances[engineIndex];
  11740. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11741. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11742. }
  11743. }
  11744. };
  11745. Object.defineProperty(Engine, "NEVER", {
  11746. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11747. get: function () {
  11748. return Engine._NEVER;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "ALWAYS", {
  11754. /** 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 */
  11755. get: function () {
  11756. return Engine._ALWAYS;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "LESS", {
  11762. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11763. get: function () {
  11764. return Engine._LESS;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "EQUAL", {
  11770. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11771. get: function () {
  11772. return Engine._EQUAL;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "LEQUAL", {
  11778. /** 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 */
  11779. get: function () {
  11780. return Engine._LEQUAL;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "GREATER", {
  11786. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11787. get: function () {
  11788. return Engine._GREATER;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "GEQUAL", {
  11794. /** 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 */
  11795. get: function () {
  11796. return Engine._GEQUAL;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "NOTEQUAL", {
  11802. /** 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 */
  11803. get: function () {
  11804. return Engine._NOTEQUAL;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "KEEP", {
  11810. /** Passed to stencilOperation to specify that stencil value must be kept */
  11811. get: function () {
  11812. return Engine._KEEP;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "REPLACE", {
  11818. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11819. get: function () {
  11820. return Engine._REPLACE;
  11821. },
  11822. enumerable: true,
  11823. configurable: true
  11824. });
  11825. Object.defineProperty(Engine, "INCR", {
  11826. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11827. get: function () {
  11828. return Engine._INCR;
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine, "DECR", {
  11834. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11835. get: function () {
  11836. return Engine._DECR;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. Object.defineProperty(Engine, "INVERT", {
  11842. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11843. get: function () {
  11844. return Engine._INVERT;
  11845. },
  11846. enumerable: true,
  11847. configurable: true
  11848. });
  11849. Object.defineProperty(Engine, "INCR_WRAP", {
  11850. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11851. get: function () {
  11852. return Engine._INCR_WRAP;
  11853. },
  11854. enumerable: true,
  11855. configurable: true
  11856. });
  11857. Object.defineProperty(Engine, "DECR_WRAP", {
  11858. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11859. get: function () {
  11860. return Engine._DECR_WRAP;
  11861. },
  11862. enumerable: true,
  11863. configurable: true
  11864. });
  11865. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11866. // Alpha
  11867. /** Defines that alpha blending is disabled */
  11868. get: function () {
  11869. return Engine._ALPHA_DISABLE;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11875. /** Defines that alpha blending to SRC + DEST */
  11876. get: function () {
  11877. return Engine._ALPHA_ONEONE;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "ALPHA_ADD", {
  11883. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11884. get: function () {
  11885. return Engine._ALPHA_ADD;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11891. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11892. get: function () {
  11893. return Engine._ALPHA_COMBINE;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11899. /** Defines that alpha blending to DEST - SRC * DEST */
  11900. get: function () {
  11901. return Engine._ALPHA_SUBTRACT;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11907. /** Defines that alpha blending to SRC * DEST */
  11908. get: function () {
  11909. return Engine._ALPHA_MULTIPLY;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11915. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11916. get: function () {
  11917. return Engine._ALPHA_MAXIMIZED;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11923. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11924. get: function () {
  11925. return Engine._ALPHA_PREMULTIPLIED;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11931. /**
  11932. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11933. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11934. */
  11935. get: function () {
  11936. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11942. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11943. get: function () {
  11944. return Engine._ALPHA_INTERPOLATE;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11950. /**
  11951. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11952. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11953. */
  11954. get: function () {
  11955. return Engine._ALPHA_SCREENMODE;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11961. // Delays
  11962. /** Defines that the ressource is not delayed*/
  11963. get: function () {
  11964. return Engine._DELAYLOADSTATE_NONE;
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11970. /** Defines that the ressource was successfully delay loaded */
  11971. get: function () {
  11972. return Engine._DELAYLOADSTATE_LOADED;
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11978. /** Defines that the ressource is currently delay loading */
  11979. get: function () {
  11980. return Engine._DELAYLOADSTATE_LOADING;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11986. /** Defines that the ressource is delayed and has not started loading */
  11987. get: function () {
  11988. return Engine._DELAYLOADSTATE_NOTLOADED;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11994. /** ALPHA */
  11995. get: function () {
  11996. return Engine._TEXTUREFORMAT_ALPHA;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12002. /** LUMINANCE */
  12003. get: function () {
  12004. return Engine._TEXTUREFORMAT_LUMINANCE;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12010. /**
  12011. * R
  12012. */
  12013. get: function () {
  12014. return Engine._TEXTUREFORMAT_R;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12020. /**
  12021. * RG
  12022. */
  12023. get: function () {
  12024. return Engine._TEXTUREFORMAT_RG;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12030. /** LUMINANCE_ALPHA */
  12031. get: function () {
  12032. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12038. /** RGB */
  12039. get: function () {
  12040. return Engine._TEXTUREFORMAT_RGB;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12046. /** RGBA */
  12047. get: function () {
  12048. return Engine._TEXTUREFORMAT_RGBA;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12054. /** UNSIGNED_INT */
  12055. get: function () {
  12056. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12057. },
  12058. enumerable: true,
  12059. configurable: true
  12060. });
  12061. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12062. /** FLOAT */
  12063. get: function () {
  12064. return Engine._TEXTURETYPE_FLOAT;
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12070. /** HALF_FLOAT */
  12071. get: function () {
  12072. return Engine._TEXTURETYPE_HALF_FLOAT;
  12073. },
  12074. enumerable: true,
  12075. configurable: true
  12076. });
  12077. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12078. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12079. get: function () {
  12080. return Engine._SCALEMODE_FLOOR;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12086. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12087. get: function () {
  12088. return Engine._SCALEMODE_NEAREST;
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12094. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12095. get: function () {
  12096. return Engine._SCALEMODE_CEILING;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Object.defineProperty(Engine, "Version", {
  12102. /**
  12103. * Returns the current version of the framework
  12104. */
  12105. get: function () {
  12106. return "3.3.0-alpha.3";
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12112. /**
  12113. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12114. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12115. */
  12116. get: function () {
  12117. return this._vrExclusivePointerMode;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12123. /**
  12124. * Gets a boolean indicating that the engine supports uniform buffers
  12125. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12126. */
  12127. get: function () {
  12128. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12134. /**
  12135. * Gets a boolean indicating that only power of 2 textures are supported
  12136. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12137. */
  12138. get: function () {
  12139. return this._webGLVersion < 2 || this.forcePOTTextures;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12145. /**
  12146. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12147. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12148. */
  12149. get: function () {
  12150. return this._doNotHandleContextLost;
  12151. },
  12152. set: function (value) {
  12153. this._doNotHandleContextLost = value;
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12159. /**
  12160. * Gets the performance monitor attached to this engine
  12161. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12162. */
  12163. get: function () {
  12164. return this._performanceMonitor;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12170. /**
  12171. * Gets the list of texture formats supported
  12172. */
  12173. get: function () {
  12174. return this._texturesSupported;
  12175. },
  12176. enumerable: true,
  12177. configurable: true
  12178. });
  12179. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12180. /**
  12181. * Gets the list of texture formats in use
  12182. */
  12183. get: function () {
  12184. return this._textureFormatInUse;
  12185. },
  12186. enumerable: true,
  12187. configurable: true
  12188. });
  12189. Object.defineProperty(Engine.prototype, "currentViewport", {
  12190. /**
  12191. * Gets the current viewport
  12192. */
  12193. get: function () {
  12194. return this._cachedViewport;
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12200. /**
  12201. * Gets the default empty texture
  12202. */
  12203. get: function () {
  12204. if (!this._emptyTexture) {
  12205. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12206. }
  12207. return this._emptyTexture;
  12208. },
  12209. enumerable: true,
  12210. configurable: true
  12211. });
  12212. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12213. /**
  12214. * Gets the default empty 3D texture
  12215. */
  12216. get: function () {
  12217. if (!this._emptyTexture3D) {
  12218. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12219. }
  12220. return this._emptyTexture3D;
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12226. /**
  12227. * Gets the default empty cube texture
  12228. */
  12229. get: function () {
  12230. if (!this._emptyCubeTexture) {
  12231. var faceData = new Uint8Array(4);
  12232. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12233. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12234. }
  12235. return this._emptyCubeTexture;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Engine.prototype._rebuildInternalTextures = function () {
  12241. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12242. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12243. var internalTexture = currentState_1[_i];
  12244. internalTexture._rebuild();
  12245. }
  12246. };
  12247. Engine.prototype._rebuildEffects = function () {
  12248. for (var key in this._compiledEffects) {
  12249. var effect = this._compiledEffects[key];
  12250. effect._prepareEffect();
  12251. }
  12252. BABYLON.Effect.ResetCache();
  12253. };
  12254. Engine.prototype._rebuildBuffers = function () {
  12255. // Index / Vertex
  12256. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12257. var scene = _a[_i];
  12258. scene.resetCachedMaterial();
  12259. scene._rebuildGeometries();
  12260. scene._rebuildTextures();
  12261. }
  12262. // Uniforms
  12263. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12264. var uniformBuffer = _c[_b];
  12265. uniformBuffer._rebuild();
  12266. }
  12267. };
  12268. Engine.prototype._initGLContext = function () {
  12269. // Caps
  12270. this._caps = new EngineCapabilities();
  12271. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12272. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12273. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12274. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12275. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12276. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12277. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12278. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12279. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12280. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12281. // Infos
  12282. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12283. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12284. if (rendererInfo != null) {
  12285. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12286. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12287. }
  12288. if (!this._glVendor) {
  12289. this._glVendor = "Unknown vendor";
  12290. }
  12291. if (!this._glRenderer) {
  12292. this._glRenderer = "Unknown renderer";
  12293. }
  12294. // Constants
  12295. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12296. if (this._gl.RGBA16F !== 0x881A) {
  12297. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12298. }
  12299. if (this._gl.RGBA32F !== 0x8814) {
  12300. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12301. }
  12302. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12303. this._gl.DEPTH24_STENCIL8 = 35056;
  12304. }
  12305. // Extensions
  12306. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12307. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12308. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12309. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12310. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12311. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12312. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12313. 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');
  12314. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12315. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12316. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12317. this._caps.highPrecisionShaderSupported = true;
  12318. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12319. if (this._caps.timerQuery) {
  12320. if (this._webGLVersion === 1) {
  12321. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12322. }
  12323. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12324. }
  12325. // Checks if some of the format renders first to allow the use of webgl inspector.
  12326. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12327. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12328. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12329. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12330. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12331. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12332. if (this._webGLVersion > 1) {
  12333. this._gl.HALF_FLOAT_OES = 0x140B;
  12334. }
  12335. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12336. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12337. // Draw buffers
  12338. if (this._webGLVersion > 1) {
  12339. this._caps.drawBuffersExtension = true;
  12340. }
  12341. else {
  12342. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12343. if (drawBuffersExtension !== null) {
  12344. this._caps.drawBuffersExtension = true;
  12345. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12346. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12347. for (var i = 0; i < 16; i++) {
  12348. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12349. }
  12350. }
  12351. else {
  12352. this._caps.drawBuffersExtension = false;
  12353. }
  12354. }
  12355. // Depth Texture
  12356. if (this._webGLVersion > 1) {
  12357. this._caps.depthTextureExtension = true;
  12358. }
  12359. else {
  12360. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12361. if (depthTextureExtension != null) {
  12362. this._caps.depthTextureExtension = true;
  12363. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12364. }
  12365. }
  12366. // Vertex array object
  12367. if (this._webGLVersion > 1) {
  12368. this._caps.vertexArrayObject = true;
  12369. }
  12370. else {
  12371. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12372. if (vertexArrayObjectExtension != null) {
  12373. this._caps.vertexArrayObject = true;
  12374. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12375. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12376. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12377. }
  12378. else {
  12379. this._caps.vertexArrayObject = false;
  12380. }
  12381. }
  12382. // Instances count
  12383. if (this._webGLVersion > 1) {
  12384. this._caps.instancedArrays = true;
  12385. }
  12386. else {
  12387. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12388. if (instanceExtension != null) {
  12389. this._caps.instancedArrays = true;
  12390. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12391. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12392. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12393. }
  12394. else {
  12395. this._caps.instancedArrays = false;
  12396. }
  12397. }
  12398. // Intelligently add supported compressed formats in order to check for.
  12399. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12400. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12401. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12402. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12403. if (this._caps.astc)
  12404. this.texturesSupported.push('-astc.ktx');
  12405. if (this._caps.s3tc)
  12406. this.texturesSupported.push('-dxt.ktx');
  12407. if (this._caps.pvrtc)
  12408. this.texturesSupported.push('-pvrtc.ktx');
  12409. if (this._caps.etc2)
  12410. this.texturesSupported.push('-etc2.ktx');
  12411. if (this._caps.etc1)
  12412. this.texturesSupported.push('-etc1.ktx');
  12413. if (this._gl.getShaderPrecisionFormat) {
  12414. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12415. if (highp) {
  12416. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12417. }
  12418. }
  12419. // Depth buffer
  12420. this.setDepthBuffer(true);
  12421. this.setDepthFunctionToLessOrEqual();
  12422. this.setDepthWrite(true);
  12423. // Texture maps
  12424. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12425. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12426. this._nextFreeTextureSlots.push(slot);
  12427. }
  12428. };
  12429. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12430. /**
  12431. * Gets version of the current webGL context
  12432. */
  12433. get: function () {
  12434. return this._webGLVersion;
  12435. },
  12436. enumerable: true,
  12437. configurable: true
  12438. });
  12439. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12440. /**
  12441. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12442. */
  12443. get: function () {
  12444. return this._isStencilEnable;
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. Engine.prototype._prepareWorkingCanvas = function () {
  12450. if (this._workingCanvas) {
  12451. return;
  12452. }
  12453. this._workingCanvas = document.createElement("canvas");
  12454. var context = this._workingCanvas.getContext("2d");
  12455. if (context) {
  12456. this._workingContext = context;
  12457. }
  12458. };
  12459. /**
  12460. * Reset the texture cache to empty state
  12461. */
  12462. Engine.prototype.resetTextureCache = function () {
  12463. for (var key in this._boundTexturesCache) {
  12464. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12465. continue;
  12466. }
  12467. var boundTexture = this._boundTexturesCache[key];
  12468. if (boundTexture) {
  12469. this._removeDesignatedSlot(boundTexture);
  12470. }
  12471. this._boundTexturesCache[key] = null;
  12472. }
  12473. if (!this.disableTextureBindingOptimization) {
  12474. this._nextFreeTextureSlots = [];
  12475. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12476. this._nextFreeTextureSlots.push(slot);
  12477. }
  12478. }
  12479. this._currentTextureChannel = -1;
  12480. };
  12481. /**
  12482. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12483. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12484. * @returns true if engine is in deterministic lock step mode
  12485. */
  12486. Engine.prototype.isDeterministicLockStep = function () {
  12487. return this._deterministicLockstep;
  12488. };
  12489. /**
  12490. * Gets the max steps when engine is running in deterministic lock step
  12491. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12492. * @returns the max steps
  12493. */
  12494. Engine.prototype.getLockstepMaxSteps = function () {
  12495. return this._lockstepMaxSteps;
  12496. };
  12497. /**
  12498. * Gets an object containing information about the current webGL context
  12499. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12500. */
  12501. Engine.prototype.getGlInfo = function () {
  12502. return {
  12503. vendor: this._glVendor,
  12504. renderer: this._glRenderer,
  12505. version: this._glVersion
  12506. };
  12507. };
  12508. /**
  12509. * Gets current aspect ratio
  12510. * @param camera defines the camera to use to get the aspect ratio
  12511. * @param useScreen defines if screen size must be used (or the current render target if any)
  12512. * @returns a number defining the aspect ratio
  12513. */
  12514. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12515. if (useScreen === void 0) { useScreen = false; }
  12516. var viewport = camera.viewport;
  12517. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12518. };
  12519. /**
  12520. * Gets current screen aspect ratio
  12521. * @returns a number defining the aspect ratio
  12522. */
  12523. Engine.prototype.getScreenAspectRatio = function () {
  12524. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12525. };
  12526. /**
  12527. * Gets the current render width
  12528. * @param useScreen defines if screen size must be used (or the current render target if any)
  12529. * @returns a number defining the current render width
  12530. */
  12531. Engine.prototype.getRenderWidth = function (useScreen) {
  12532. if (useScreen === void 0) { useScreen = false; }
  12533. if (!useScreen && this._currentRenderTarget) {
  12534. return this._currentRenderTarget.width;
  12535. }
  12536. return this._gl.drawingBufferWidth;
  12537. };
  12538. /**
  12539. * Gets the current render height
  12540. * @param useScreen defines if screen size must be used (or the current render target if any)
  12541. * @returns a number defining the current render height
  12542. */
  12543. Engine.prototype.getRenderHeight = function (useScreen) {
  12544. if (useScreen === void 0) { useScreen = false; }
  12545. if (!useScreen && this._currentRenderTarget) {
  12546. return this._currentRenderTarget.height;
  12547. }
  12548. return this._gl.drawingBufferHeight;
  12549. };
  12550. /**
  12551. * Gets the HTML canvas attached with the current webGL context
  12552. * @returns a HTML canvas
  12553. */
  12554. Engine.prototype.getRenderingCanvas = function () {
  12555. return this._renderingCanvas;
  12556. };
  12557. /**
  12558. * Gets the client rect of the HTML canvas attached with the current webGL context
  12559. * @returns a client rectanglee
  12560. */
  12561. Engine.prototype.getRenderingCanvasClientRect = function () {
  12562. if (!this._renderingCanvas) {
  12563. return null;
  12564. }
  12565. return this._renderingCanvas.getBoundingClientRect();
  12566. };
  12567. /**
  12568. * Defines the hardware scaling level.
  12569. * By default the hardware scaling level is computed from the window device ratio.
  12570. * 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.
  12571. * @param level defines the level to use
  12572. */
  12573. Engine.prototype.setHardwareScalingLevel = function (level) {
  12574. this._hardwareScalingLevel = level;
  12575. this.resize();
  12576. };
  12577. /**
  12578. * Gets the current hardware scaling level.
  12579. * By default the hardware scaling level is computed from the window device ratio.
  12580. * 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.
  12581. * @returns a number indicating the current hardware scaling level
  12582. */
  12583. Engine.prototype.getHardwareScalingLevel = function () {
  12584. return this._hardwareScalingLevel;
  12585. };
  12586. /**
  12587. * Gets the list of loaded textures
  12588. * @returns an array containing all loaded textures
  12589. */
  12590. Engine.prototype.getLoadedTexturesCache = function () {
  12591. return this._internalTexturesCache;
  12592. };
  12593. /**
  12594. * Gets the object containing all engine capabilities
  12595. * @returns the EngineCapabilities object
  12596. */
  12597. Engine.prototype.getCaps = function () {
  12598. return this._caps;
  12599. };
  12600. Object.defineProperty(Engine.prototype, "drawCalls", {
  12601. /** @hidden */
  12602. get: function () {
  12603. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12604. return 0;
  12605. },
  12606. enumerable: true,
  12607. configurable: true
  12608. });
  12609. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12610. /** @hidden */
  12611. get: function () {
  12612. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12613. return null;
  12614. },
  12615. enumerable: true,
  12616. configurable: true
  12617. });
  12618. /**
  12619. * Gets the current depth function
  12620. * @returns a number defining the depth function
  12621. */
  12622. Engine.prototype.getDepthFunction = function () {
  12623. return this._depthCullingState.depthFunc;
  12624. };
  12625. /**
  12626. * Sets the current depth function
  12627. * @param depthFunc defines the function to use
  12628. */
  12629. Engine.prototype.setDepthFunction = function (depthFunc) {
  12630. this._depthCullingState.depthFunc = depthFunc;
  12631. };
  12632. /**
  12633. * Sets the current depth function to GREATER
  12634. */
  12635. Engine.prototype.setDepthFunctionToGreater = function () {
  12636. this._depthCullingState.depthFunc = this._gl.GREATER;
  12637. };
  12638. /**
  12639. * Sets the current depth function to GEQUAL
  12640. */
  12641. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12642. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12643. };
  12644. /**
  12645. * Sets the current depth function to LESS
  12646. */
  12647. Engine.prototype.setDepthFunctionToLess = function () {
  12648. this._depthCullingState.depthFunc = this._gl.LESS;
  12649. };
  12650. /**
  12651. * Sets the current depth function to LEQUAL
  12652. */
  12653. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12654. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12655. };
  12656. /**
  12657. * Gets a boolean indicating if stencil buffer is enabled
  12658. * @returns the current stencil buffer state
  12659. */
  12660. Engine.prototype.getStencilBuffer = function () {
  12661. return this._stencilState.stencilTest;
  12662. };
  12663. /**
  12664. * Enable or disable the stencil buffer
  12665. * @param enable defines if the stencil buffer must be enabled or disabled
  12666. */
  12667. Engine.prototype.setStencilBuffer = function (enable) {
  12668. this._stencilState.stencilTest = enable;
  12669. };
  12670. /**
  12671. * Gets the current stencil mask
  12672. * @returns a number defining the new stencil mask to use
  12673. */
  12674. Engine.prototype.getStencilMask = function () {
  12675. return this._stencilState.stencilMask;
  12676. };
  12677. /**
  12678. * Sets the current stencil mask
  12679. * @param mask defines the new stencil mask to use
  12680. */
  12681. Engine.prototype.setStencilMask = function (mask) {
  12682. this._stencilState.stencilMask = mask;
  12683. };
  12684. /**
  12685. * Gets the current stencil function
  12686. * @returns a number defining the stencil function to use
  12687. */
  12688. Engine.prototype.getStencilFunction = function () {
  12689. return this._stencilState.stencilFunc;
  12690. };
  12691. /**
  12692. * Gets the current stencil reference value
  12693. * @returns a number defining the stencil reference value to use
  12694. */
  12695. Engine.prototype.getStencilFunctionReference = function () {
  12696. return this._stencilState.stencilFuncRef;
  12697. };
  12698. /**
  12699. * Gets the current stencil mask
  12700. * @returns a number defining the stencil mask to use
  12701. */
  12702. Engine.prototype.getStencilFunctionMask = function () {
  12703. return this._stencilState.stencilFuncMask;
  12704. };
  12705. /**
  12706. * Sets the current stencil function
  12707. * @param stencilFunc defines the new stencil function to use
  12708. */
  12709. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12710. this._stencilState.stencilFunc = stencilFunc;
  12711. };
  12712. /**
  12713. * Sets the current stencil reference
  12714. * @param reference defines the new stencil reference to use
  12715. */
  12716. Engine.prototype.setStencilFunctionReference = function (reference) {
  12717. this._stencilState.stencilFuncRef = reference;
  12718. };
  12719. /**
  12720. * Sets the current stencil mask
  12721. * @param mask defines the new stencil mask to use
  12722. */
  12723. Engine.prototype.setStencilFunctionMask = function (mask) {
  12724. this._stencilState.stencilFuncMask = mask;
  12725. };
  12726. /**
  12727. * Gets the current stencil operation when stencil fails
  12728. * @returns a number defining stencil operation to use when stencil fails
  12729. */
  12730. Engine.prototype.getStencilOperationFail = function () {
  12731. return this._stencilState.stencilOpStencilFail;
  12732. };
  12733. /**
  12734. * Gets the current stencil operation when depth fails
  12735. * @returns a number defining stencil operation to use when depth fails
  12736. */
  12737. Engine.prototype.getStencilOperationDepthFail = function () {
  12738. return this._stencilState.stencilOpDepthFail;
  12739. };
  12740. /**
  12741. * Gets the current stencil operation when stencil passes
  12742. * @returns a number defining stencil operation to use when stencil passes
  12743. */
  12744. Engine.prototype.getStencilOperationPass = function () {
  12745. return this._stencilState.stencilOpStencilDepthPass;
  12746. };
  12747. /**
  12748. * Sets the stencil operation to use when stencil fails
  12749. * @param operation defines the stencil operation to use when stencil fails
  12750. */
  12751. Engine.prototype.setStencilOperationFail = function (operation) {
  12752. this._stencilState.stencilOpStencilFail = operation;
  12753. };
  12754. /**
  12755. * Sets the stencil operation to use when depth fails
  12756. * @param operation defines the stencil operation to use when depth fails
  12757. */
  12758. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12759. this._stencilState.stencilOpDepthFail = operation;
  12760. };
  12761. /**
  12762. * Sets the stencil operation to use when stencil passes
  12763. * @param operation defines the stencil operation to use when stencil passes
  12764. */
  12765. Engine.prototype.setStencilOperationPass = function (operation) {
  12766. this._stencilState.stencilOpStencilDepthPass = operation;
  12767. };
  12768. /**
  12769. * Sets a boolean indicating if the dithering state is enabled or disabled
  12770. * @param value defines the dithering state
  12771. */
  12772. Engine.prototype.setDitheringState = function (value) {
  12773. if (value) {
  12774. this._gl.enable(this._gl.DITHER);
  12775. }
  12776. else {
  12777. this._gl.disable(this._gl.DITHER);
  12778. }
  12779. };
  12780. /**
  12781. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12782. * @param value defines the rasterizer state
  12783. */
  12784. Engine.prototype.setRasterizerState = function (value) {
  12785. if (value) {
  12786. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12787. }
  12788. else {
  12789. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12790. }
  12791. };
  12792. /**
  12793. * stop executing a render loop function and remove it from the execution array
  12794. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12795. */
  12796. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12797. if (!renderFunction) {
  12798. this._activeRenderLoops = [];
  12799. return;
  12800. }
  12801. var index = this._activeRenderLoops.indexOf(renderFunction);
  12802. if (index >= 0) {
  12803. this._activeRenderLoops.splice(index, 1);
  12804. }
  12805. };
  12806. /** @hidden */
  12807. Engine.prototype._renderLoop = function () {
  12808. if (!this._contextWasLost) {
  12809. var shouldRender = true;
  12810. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12811. shouldRender = false;
  12812. }
  12813. if (shouldRender) {
  12814. // Start new frame
  12815. this.beginFrame();
  12816. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12817. var renderFunction = this._activeRenderLoops[index];
  12818. renderFunction();
  12819. }
  12820. // Present
  12821. this.endFrame();
  12822. }
  12823. }
  12824. if (this._activeRenderLoops.length > 0) {
  12825. // Register new frame
  12826. var requester = null;
  12827. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12828. requester = this._vrDisplay;
  12829. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12830. }
  12831. else {
  12832. this._renderingQueueLaunched = false;
  12833. }
  12834. };
  12835. /**
  12836. * Register and execute a render loop. The engine can have more than one render function
  12837. * @param renderFunction defines the function to continuously execute
  12838. */
  12839. Engine.prototype.runRenderLoop = function (renderFunction) {
  12840. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12841. return;
  12842. }
  12843. this._activeRenderLoops.push(renderFunction);
  12844. if (!this._renderingQueueLaunched) {
  12845. this._renderingQueueLaunched = true;
  12846. this._bindedRenderFunction = this._renderLoop.bind(this);
  12847. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12848. }
  12849. };
  12850. /**
  12851. * Toggle full screen mode
  12852. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12853. * @param options defines an option object to be sent to the requestFullscreen function
  12854. */
  12855. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12856. if (this.isFullscreen) {
  12857. BABYLON.Tools.ExitFullscreen();
  12858. }
  12859. else {
  12860. this._pointerLockRequested = requestPointerLock;
  12861. if (this._renderingCanvas) {
  12862. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12863. }
  12864. }
  12865. };
  12866. /**
  12867. * Clear the current render buffer or the current render target (if any is set up)
  12868. * @param color defines the color to use
  12869. * @param backBuffer defines if the back buffer must be cleared
  12870. * @param depth defines if the depth buffer must be cleared
  12871. * @param stencil defines if the stencil buffer must be cleared
  12872. */
  12873. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12874. if (stencil === void 0) { stencil = false; }
  12875. this.applyStates();
  12876. var mode = 0;
  12877. if (backBuffer && color) {
  12878. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12879. mode |= this._gl.COLOR_BUFFER_BIT;
  12880. }
  12881. if (depth) {
  12882. this._gl.clearDepth(1.0);
  12883. mode |= this._gl.DEPTH_BUFFER_BIT;
  12884. }
  12885. if (stencil) {
  12886. this._gl.clearStencil(0);
  12887. mode |= this._gl.STENCIL_BUFFER_BIT;
  12888. }
  12889. this._gl.clear(mode);
  12890. };
  12891. /**
  12892. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12893. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12894. * @param y defines the y-coordinate of the corner of the clear rectangle
  12895. * @param width defines the width of the clear rectangle
  12896. * @param height defines the height of the clear rectangle
  12897. * @param clearColor defines the clear color
  12898. */
  12899. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12900. var gl = this._gl;
  12901. // Save state
  12902. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12903. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12904. // Change state
  12905. gl.enable(gl.SCISSOR_TEST);
  12906. gl.scissor(x, y, width, height);
  12907. // Clear
  12908. this.clear(clearColor, true, true, true);
  12909. // Restore state
  12910. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12911. if (curScissor === true) {
  12912. gl.enable(gl.SCISSOR_TEST);
  12913. }
  12914. else {
  12915. gl.disable(gl.SCISSOR_TEST);
  12916. }
  12917. };
  12918. /**
  12919. * Set the WebGL's viewport
  12920. * @param viewport defines the viewport element to be used
  12921. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12922. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12923. */
  12924. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12925. var width = requiredWidth || this.getRenderWidth();
  12926. var height = requiredHeight || this.getRenderHeight();
  12927. var x = viewport.x || 0;
  12928. var y = viewport.y || 0;
  12929. this._cachedViewport = viewport;
  12930. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12931. };
  12932. /**
  12933. * Directly set the WebGL Viewport
  12934. * @param x defines the x coordinate of the viewport (in screen space)
  12935. * @param y defines the y coordinate of the viewport (in screen space)
  12936. * @param width defines the width of the viewport (in screen space)
  12937. * @param height defines the height of the viewport (in screen space)
  12938. * @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
  12939. */
  12940. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12941. var currentViewport = this._cachedViewport;
  12942. this._cachedViewport = null;
  12943. this._gl.viewport(x, y, width, height);
  12944. return currentViewport;
  12945. };
  12946. /**
  12947. * Begin a new frame
  12948. */
  12949. Engine.prototype.beginFrame = function () {
  12950. this.onBeginFrameObservable.notifyObservers(this);
  12951. this._measureFps();
  12952. };
  12953. /**
  12954. * Enf the current frame
  12955. */
  12956. Engine.prototype.endFrame = function () {
  12957. // Force a flush in case we are using a bad OS.
  12958. if (this._badOS) {
  12959. this.flushFramebuffer();
  12960. }
  12961. // Submit frame to the vr device, if enabled
  12962. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12963. // TODO: We should only submit the frame if we read frameData successfully.
  12964. this._vrDisplay.submitFrame();
  12965. }
  12966. this.onEndFrameObservable.notifyObservers(this);
  12967. };
  12968. /**
  12969. * Resize the view according to the canvas' size
  12970. */
  12971. Engine.prototype.resize = function () {
  12972. // We're not resizing the size of the canvas while in VR mode & presenting
  12973. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12974. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12975. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12976. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12977. }
  12978. };
  12979. /**
  12980. * Force a specific size of the canvas
  12981. * @param width defines the new canvas' width
  12982. * @param height defines the new canvas' height
  12983. */
  12984. Engine.prototype.setSize = function (width, height) {
  12985. if (!this._renderingCanvas) {
  12986. return;
  12987. }
  12988. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12989. return;
  12990. }
  12991. this._renderingCanvas.width = width;
  12992. this._renderingCanvas.height = height;
  12993. for (var index = 0; index < this.scenes.length; index++) {
  12994. var scene = this.scenes[index];
  12995. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12996. var cam = scene.cameras[camIndex];
  12997. cam._currentRenderId = 0;
  12998. }
  12999. }
  13000. if (this.onResizeObservable.hasObservers) {
  13001. this.onResizeObservable.notifyObservers(this);
  13002. }
  13003. };
  13004. // WebVR functions
  13005. /**
  13006. * Gets a boolean indicating if a webVR device was detected
  13007. * @returns true if a webVR device was detected
  13008. */
  13009. Engine.prototype.isVRDevicePresent = function () {
  13010. return !!this._vrDisplay;
  13011. };
  13012. /**
  13013. * Gets the current webVR device
  13014. * @returns the current webVR device (or null)
  13015. */
  13016. Engine.prototype.getVRDevice = function () {
  13017. return this._vrDisplay;
  13018. };
  13019. /**
  13020. * Initializes a webVR display and starts listening to display change events
  13021. * The onVRDisplayChangedObservable will be notified upon these changes
  13022. * @returns The onVRDisplayChangedObservable
  13023. */
  13024. Engine.prototype.initWebVR = function () {
  13025. this.initWebVRAsync();
  13026. return this.onVRDisplayChangedObservable;
  13027. };
  13028. /**
  13029. * Initializes a webVR display and starts listening to display change events
  13030. * The onVRDisplayChangedObservable will be notified upon these changes
  13031. * @returns A promise containing a VRDisplay and if vr is supported
  13032. */
  13033. Engine.prototype.initWebVRAsync = function () {
  13034. var _this = this;
  13035. var notifyObservers = function () {
  13036. var eventArgs = {
  13037. vrDisplay: _this._vrDisplay,
  13038. vrSupported: _this._vrSupported
  13039. };
  13040. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13041. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13042. };
  13043. if (!this._onVrDisplayConnect) {
  13044. this._onVrDisplayConnect = function (event) {
  13045. _this._vrDisplay = event.display;
  13046. notifyObservers();
  13047. };
  13048. this._onVrDisplayDisconnect = function () {
  13049. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13050. _this._vrDisplay = undefined;
  13051. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13052. notifyObservers();
  13053. };
  13054. this._onVrDisplayPresentChange = function () {
  13055. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13056. };
  13057. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13058. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13059. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13060. }
  13061. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13062. this._webVRInitPromise.then(notifyObservers);
  13063. return this._webVRInitPromise;
  13064. };
  13065. /**
  13066. * Call this function to switch to webVR mode
  13067. * Will do nothing if webVR is not supported or if there is no webVR device
  13068. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13069. */
  13070. Engine.prototype.enableVR = function () {
  13071. var _this = this;
  13072. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13073. var onResolved = function () {
  13074. _this.onVRRequestPresentComplete.notifyObservers(true);
  13075. _this._onVRFullScreenTriggered();
  13076. };
  13077. var onRejected = function () {
  13078. _this.onVRRequestPresentComplete.notifyObservers(false);
  13079. };
  13080. this.onVRRequestPresentStart.notifyObservers(this);
  13081. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13082. }
  13083. };
  13084. /**
  13085. * Call this function to leave webVR mode
  13086. * Will do nothing if webVR is not supported or if there is no webVR device
  13087. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13088. */
  13089. Engine.prototype.disableVR = function () {
  13090. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13091. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13092. }
  13093. };
  13094. Engine.prototype._getVRDisplaysAsync = function () {
  13095. var _this = this;
  13096. return new Promise(function (res, rej) {
  13097. if (navigator.getVRDisplays) {
  13098. navigator.getVRDisplays().then(function (devices) {
  13099. _this._vrSupported = true;
  13100. // note that devices may actually be an empty array. This is fine;
  13101. // we expect this._vrDisplay to be undefined in this case.
  13102. _this._vrDisplay = devices[0];
  13103. res({
  13104. vrDisplay: _this._vrDisplay,
  13105. vrSupported: _this._vrSupported
  13106. });
  13107. });
  13108. }
  13109. else {
  13110. _this._vrDisplay = undefined;
  13111. _this._vrSupported = false;
  13112. res({
  13113. vrDisplay: _this._vrDisplay,
  13114. vrSupported: _this._vrSupported
  13115. });
  13116. }
  13117. });
  13118. };
  13119. /**
  13120. * Binds the frame buffer to the specified texture.
  13121. * @param texture The texture to render to or null for the default canvas
  13122. * @param faceIndex The face of the texture to render to in case of cube texture
  13123. * @param requiredWidth The width of the target to render to
  13124. * @param requiredHeight The height of the target to render to
  13125. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13126. * @param depthStencilTexture The depth stencil texture to use to render
  13127. */
  13128. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13129. if (this._currentRenderTarget) {
  13130. this.unBindFramebuffer(this._currentRenderTarget);
  13131. }
  13132. this._currentRenderTarget = texture;
  13133. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13134. var gl = this._gl;
  13135. if (texture.isCube) {
  13136. if (faceIndex === undefined) {
  13137. faceIndex = 0;
  13138. }
  13139. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13140. if (depthStencilTexture) {
  13141. if (depthStencilTexture._generateStencilBuffer) {
  13142. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13143. }
  13144. else {
  13145. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13146. }
  13147. }
  13148. }
  13149. if (this._cachedViewport && !forceFullscreenViewport) {
  13150. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13151. }
  13152. else {
  13153. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13154. }
  13155. this.wipeCaches();
  13156. };
  13157. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13158. if (this._currentFramebuffer !== framebuffer) {
  13159. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13160. this._currentFramebuffer = framebuffer;
  13161. }
  13162. };
  13163. /**
  13164. * Unbind the current render target texture from the webGL context
  13165. * @param texture defines the render target texture to unbind
  13166. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13167. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13168. */
  13169. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13170. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13171. this._currentRenderTarget = null;
  13172. // If MSAA, we need to bitblt back to main texture
  13173. var gl = this._gl;
  13174. if (texture._MSAAFramebuffer) {
  13175. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13176. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13177. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13178. }
  13179. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13180. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13181. gl.generateMipmap(gl.TEXTURE_2D);
  13182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13183. }
  13184. if (onBeforeUnbind) {
  13185. if (texture._MSAAFramebuffer) {
  13186. // Bind the correct framebuffer
  13187. this.bindUnboundFramebuffer(texture._framebuffer);
  13188. }
  13189. onBeforeUnbind();
  13190. }
  13191. this.bindUnboundFramebuffer(null);
  13192. };
  13193. /**
  13194. * Unbind a list of render target textures from the webGL context
  13195. * This is used only when drawBuffer extension or webGL2 are active
  13196. * @param textures defines the render target textures to unbind
  13197. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13198. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13199. */
  13200. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13201. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13202. this._currentRenderTarget = null;
  13203. // If MSAA, we need to bitblt back to main texture
  13204. var gl = this._gl;
  13205. if (textures[0]._MSAAFramebuffer) {
  13206. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13207. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13208. var attachments = textures[0]._attachments;
  13209. if (!attachments) {
  13210. attachments = new Array(textures.length);
  13211. textures[0]._attachments = attachments;
  13212. }
  13213. for (var i = 0; i < textures.length; i++) {
  13214. var texture = textures[i];
  13215. for (var j = 0; j < attachments.length; j++) {
  13216. attachments[j] = gl.NONE;
  13217. }
  13218. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13219. gl.readBuffer(attachments[i]);
  13220. gl.drawBuffers(attachments);
  13221. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13222. }
  13223. for (var i = 0; i < attachments.length; i++) {
  13224. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13225. }
  13226. gl.drawBuffers(attachments);
  13227. }
  13228. for (var i = 0; i < textures.length; i++) {
  13229. var texture = textures[i];
  13230. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13231. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13232. gl.generateMipmap(gl.TEXTURE_2D);
  13233. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13234. }
  13235. }
  13236. if (onBeforeUnbind) {
  13237. if (textures[0]._MSAAFramebuffer) {
  13238. // Bind the correct framebuffer
  13239. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13240. }
  13241. onBeforeUnbind();
  13242. }
  13243. this.bindUnboundFramebuffer(null);
  13244. };
  13245. /**
  13246. * Force the mipmap generation for the given render target texture
  13247. * @param texture defines the render target texture to use
  13248. */
  13249. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13250. if (texture.generateMipMaps) {
  13251. var gl = this._gl;
  13252. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13253. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13254. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13255. }
  13256. };
  13257. /**
  13258. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13259. */
  13260. Engine.prototype.flushFramebuffer = function () {
  13261. this._gl.flush();
  13262. };
  13263. /**
  13264. * Unbind the current render target and bind the default framebuffer
  13265. */
  13266. Engine.prototype.restoreDefaultFramebuffer = function () {
  13267. if (this._currentRenderTarget) {
  13268. this.unBindFramebuffer(this._currentRenderTarget);
  13269. }
  13270. else {
  13271. this.bindUnboundFramebuffer(null);
  13272. }
  13273. if (this._cachedViewport) {
  13274. this.setViewport(this._cachedViewport);
  13275. }
  13276. this.wipeCaches();
  13277. };
  13278. // UBOs
  13279. /**
  13280. * Create an uniform buffer
  13281. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13282. * @param elements defines the content of the uniform buffer
  13283. * @returns the webGL uniform buffer
  13284. */
  13285. Engine.prototype.createUniformBuffer = function (elements) {
  13286. var ubo = this._gl.createBuffer();
  13287. if (!ubo) {
  13288. throw new Error("Unable to create uniform buffer");
  13289. }
  13290. this.bindUniformBuffer(ubo);
  13291. if (elements instanceof Float32Array) {
  13292. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13293. }
  13294. else {
  13295. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13296. }
  13297. this.bindUniformBuffer(null);
  13298. ubo.references = 1;
  13299. return ubo;
  13300. };
  13301. /**
  13302. * Create a dynamic uniform buffer
  13303. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13304. * @param elements defines the content of the uniform buffer
  13305. * @returns the webGL uniform buffer
  13306. */
  13307. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13308. var ubo = this._gl.createBuffer();
  13309. if (!ubo) {
  13310. throw new Error("Unable to create dynamic uniform buffer");
  13311. }
  13312. this.bindUniformBuffer(ubo);
  13313. if (elements instanceof Float32Array) {
  13314. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13315. }
  13316. else {
  13317. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13318. }
  13319. this.bindUniformBuffer(null);
  13320. ubo.references = 1;
  13321. return ubo;
  13322. };
  13323. /**
  13324. * Update an existing uniform buffer
  13325. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13326. * @param uniformBuffer defines the target uniform buffer
  13327. * @param elements defines the content to update
  13328. * @param offset defines the offset in the uniform buffer where update should start
  13329. * @param count defines the size of the data to update
  13330. */
  13331. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13332. this.bindUniformBuffer(uniformBuffer);
  13333. if (offset === undefined) {
  13334. offset = 0;
  13335. }
  13336. if (count === undefined) {
  13337. if (elements instanceof Float32Array) {
  13338. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13339. }
  13340. else {
  13341. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13342. }
  13343. }
  13344. else {
  13345. if (elements instanceof Float32Array) {
  13346. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13347. }
  13348. else {
  13349. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13350. }
  13351. }
  13352. this.bindUniformBuffer(null);
  13353. };
  13354. // VBOs
  13355. Engine.prototype._resetVertexBufferBinding = function () {
  13356. this.bindArrayBuffer(null);
  13357. this._cachedVertexBuffers = null;
  13358. };
  13359. /**
  13360. * Creates a vertex buffer
  13361. * @param data the data for the vertex buffer
  13362. * @returns the new WebGL static buffer
  13363. */
  13364. Engine.prototype.createVertexBuffer = function (data) {
  13365. var vbo = this._gl.createBuffer();
  13366. if (!vbo) {
  13367. throw new Error("Unable to create vertex buffer");
  13368. }
  13369. this.bindArrayBuffer(vbo);
  13370. if (data instanceof Array) {
  13371. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13372. }
  13373. else {
  13374. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13375. }
  13376. this._resetVertexBufferBinding();
  13377. vbo.references = 1;
  13378. return vbo;
  13379. };
  13380. /**
  13381. * Creates a dynamic vertex buffer
  13382. * @param data the data for the dynamic vertex buffer
  13383. * @returns the new WebGL dynamic buffer
  13384. */
  13385. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13386. var vbo = this._gl.createBuffer();
  13387. if (!vbo) {
  13388. throw new Error("Unable to create dynamic vertex buffer");
  13389. }
  13390. this.bindArrayBuffer(vbo);
  13391. if (data instanceof Array) {
  13392. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13393. }
  13394. else {
  13395. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13396. }
  13397. this._resetVertexBufferBinding();
  13398. vbo.references = 1;
  13399. return vbo;
  13400. };
  13401. /**
  13402. * Update a dynamic index buffer
  13403. * @param indexBuffer defines the target index buffer
  13404. * @param indices defines the data to update
  13405. * @param offset defines the offset in the target index buffer where update should start
  13406. */
  13407. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13408. if (offset === void 0) { offset = 0; }
  13409. // Force cache update
  13410. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13411. this.bindIndexBuffer(indexBuffer);
  13412. var arrayBuffer;
  13413. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13414. arrayBuffer = indices;
  13415. }
  13416. else {
  13417. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13418. }
  13419. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13420. this._resetIndexBufferBinding();
  13421. };
  13422. /**
  13423. * Updates a dynamic vertex buffer.
  13424. * @param vertexBuffer the vertex buffer to update
  13425. * @param data the data used to update the vertex buffer
  13426. * @param byteOffset the byte offset of the data
  13427. * @param byteLength the byte length of the data
  13428. */
  13429. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13430. this.bindArrayBuffer(vertexBuffer);
  13431. if (byteOffset === undefined) {
  13432. byteOffset = 0;
  13433. }
  13434. if (byteLength === undefined) {
  13435. if (data instanceof Array) {
  13436. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13437. }
  13438. else {
  13439. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13440. }
  13441. }
  13442. else {
  13443. if (data instanceof Array) {
  13444. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13445. }
  13446. else {
  13447. if (data instanceof ArrayBuffer) {
  13448. data = new Uint8Array(data, byteOffset, byteLength);
  13449. }
  13450. else {
  13451. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13452. }
  13453. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13454. }
  13455. }
  13456. this._resetVertexBufferBinding();
  13457. };
  13458. Engine.prototype._resetIndexBufferBinding = function () {
  13459. this.bindIndexBuffer(null);
  13460. this._cachedIndexBuffer = null;
  13461. };
  13462. /**
  13463. * Creates a new index buffer
  13464. * @param indices defines the content of the index buffer
  13465. * @param updatable defines if the index buffer must be updatable
  13466. * @returns a new webGL buffer
  13467. */
  13468. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13469. var vbo = this._gl.createBuffer();
  13470. if (!vbo) {
  13471. throw new Error("Unable to create index buffer");
  13472. }
  13473. this.bindIndexBuffer(vbo);
  13474. // Check for 32 bits indices
  13475. var arrayBuffer;
  13476. var need32Bits = false;
  13477. if (indices instanceof Uint16Array) {
  13478. arrayBuffer = indices;
  13479. }
  13480. else {
  13481. //check 32 bit support
  13482. if (this._caps.uintIndices) {
  13483. if (indices instanceof Uint32Array) {
  13484. arrayBuffer = indices;
  13485. need32Bits = true;
  13486. }
  13487. else {
  13488. //number[] or Int32Array, check if 32 bit is necessary
  13489. for (var index = 0; index < indices.length; index++) {
  13490. if (indices[index] > 65535) {
  13491. need32Bits = true;
  13492. break;
  13493. }
  13494. }
  13495. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13496. }
  13497. }
  13498. else {
  13499. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13500. arrayBuffer = new Uint16Array(indices);
  13501. }
  13502. }
  13503. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13504. this._resetIndexBufferBinding();
  13505. vbo.references = 1;
  13506. vbo.is32Bits = need32Bits;
  13507. return vbo;
  13508. };
  13509. /**
  13510. * Bind a webGL buffer to the webGL context
  13511. * @param buffer defines the buffer to bind
  13512. */
  13513. Engine.prototype.bindArrayBuffer = function (buffer) {
  13514. if (!this._vaoRecordInProgress) {
  13515. this._unbindVertexArrayObject();
  13516. }
  13517. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13518. };
  13519. /**
  13520. * Bind an uniform buffer to the current webGL context
  13521. * @param buffer defines the buffer to bind
  13522. */
  13523. Engine.prototype.bindUniformBuffer = function (buffer) {
  13524. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13525. };
  13526. /**
  13527. * Bind a buffer to the current webGL context at a given location
  13528. * @param buffer defines the buffer to bind
  13529. * @param location defines the index where to bind the buffer
  13530. */
  13531. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13532. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13533. };
  13534. /**
  13535. * Bind a specific block at a given index in a specific shader program
  13536. * @param shaderProgram defines the shader program
  13537. * @param blockName defines the block name
  13538. * @param index defines the index where to bind the block
  13539. */
  13540. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13541. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13542. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13543. };
  13544. ;
  13545. Engine.prototype.bindIndexBuffer = function (buffer) {
  13546. if (!this._vaoRecordInProgress) {
  13547. this._unbindVertexArrayObject();
  13548. }
  13549. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13550. };
  13551. Engine.prototype.bindBuffer = function (buffer, target) {
  13552. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13553. this._gl.bindBuffer(target, buffer);
  13554. this._currentBoundBuffer[target] = buffer;
  13555. }
  13556. };
  13557. /**
  13558. * update the bound buffer with the given data
  13559. * @param data defines the data to update
  13560. */
  13561. Engine.prototype.updateArrayBuffer = function (data) {
  13562. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13563. };
  13564. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13565. var pointer = this._currentBufferPointers[indx];
  13566. var changed = false;
  13567. if (!pointer.active) {
  13568. changed = true;
  13569. pointer.active = true;
  13570. pointer.index = indx;
  13571. pointer.size = size;
  13572. pointer.type = type;
  13573. pointer.normalized = normalized;
  13574. pointer.stride = stride;
  13575. pointer.offset = offset;
  13576. pointer.buffer = buffer;
  13577. }
  13578. else {
  13579. if (pointer.buffer !== buffer) {
  13580. pointer.buffer = buffer;
  13581. changed = true;
  13582. }
  13583. if (pointer.size !== size) {
  13584. pointer.size = size;
  13585. changed = true;
  13586. }
  13587. if (pointer.type !== type) {
  13588. pointer.type = type;
  13589. changed = true;
  13590. }
  13591. if (pointer.normalized !== normalized) {
  13592. pointer.normalized = normalized;
  13593. changed = true;
  13594. }
  13595. if (pointer.stride !== stride) {
  13596. pointer.stride = stride;
  13597. changed = true;
  13598. }
  13599. if (pointer.offset !== offset) {
  13600. pointer.offset = offset;
  13601. changed = true;
  13602. }
  13603. }
  13604. if (changed || this._vaoRecordInProgress) {
  13605. this.bindArrayBuffer(buffer);
  13606. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13607. }
  13608. };
  13609. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13610. if (indexBuffer == null) {
  13611. return;
  13612. }
  13613. if (this._cachedIndexBuffer !== indexBuffer) {
  13614. this._cachedIndexBuffer = indexBuffer;
  13615. this.bindIndexBuffer(indexBuffer);
  13616. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13617. }
  13618. };
  13619. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13620. var attributes = effect.getAttributesNames();
  13621. if (!this._vaoRecordInProgress) {
  13622. this._unbindVertexArrayObject();
  13623. }
  13624. this.unbindAllAttributes();
  13625. for (var index = 0; index < attributes.length; index++) {
  13626. var order = effect.getAttributeLocation(index);
  13627. if (order >= 0) {
  13628. var vertexBuffer = vertexBuffers[attributes[index]];
  13629. if (!vertexBuffer) {
  13630. continue;
  13631. }
  13632. this._gl.enableVertexAttribArray(order);
  13633. if (!this._vaoRecordInProgress) {
  13634. this._vertexAttribArraysEnabled[order] = true;
  13635. }
  13636. var buffer = vertexBuffer.getBuffer();
  13637. if (buffer) {
  13638. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13639. if (vertexBuffer.getIsInstanced()) {
  13640. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13641. if (!this._vaoRecordInProgress) {
  13642. this._currentInstanceLocations.push(order);
  13643. this._currentInstanceBuffers.push(buffer);
  13644. }
  13645. }
  13646. }
  13647. }
  13648. }
  13649. };
  13650. /**
  13651. * Records a vertex array object
  13652. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13653. * @param vertexBuffers defines the list of vertex buffers to store
  13654. * @param indexBuffer defines the index buffer to store
  13655. * @param effect defines the effect to store
  13656. * @returns the new vertex array object
  13657. */
  13658. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13659. var vao = this._gl.createVertexArray();
  13660. this._vaoRecordInProgress = true;
  13661. this._gl.bindVertexArray(vao);
  13662. this._mustWipeVertexAttributes = true;
  13663. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13664. this.bindIndexBuffer(indexBuffer);
  13665. this._vaoRecordInProgress = false;
  13666. this._gl.bindVertexArray(null);
  13667. return vao;
  13668. };
  13669. /**
  13670. * Bind a specific vertex array object
  13671. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13672. * @param vertexArrayObject defines the vertex array object to bind
  13673. * @param indexBuffer defines the index buffer to bind
  13674. */
  13675. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13676. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13677. this._cachedVertexArrayObject = vertexArrayObject;
  13678. this._gl.bindVertexArray(vertexArrayObject);
  13679. this._cachedVertexBuffers = null;
  13680. this._cachedIndexBuffer = null;
  13681. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13682. this._mustWipeVertexAttributes = true;
  13683. }
  13684. };
  13685. /**
  13686. * Bind webGl buffers directly to the webGL context
  13687. * @param vertexBuffer defines the vertex buffer to bind
  13688. * @param indexBuffer defines the index buffer to bind
  13689. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13690. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13691. * @param effect defines the effect associated with the vertex buffer
  13692. */
  13693. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13694. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13695. this._cachedVertexBuffers = vertexBuffer;
  13696. this._cachedEffectForVertexBuffers = effect;
  13697. var attributesCount = effect.getAttributesCount();
  13698. this._unbindVertexArrayObject();
  13699. this.unbindAllAttributes();
  13700. var offset = 0;
  13701. for (var index = 0; index < attributesCount; index++) {
  13702. if (index < vertexDeclaration.length) {
  13703. var order = effect.getAttributeLocation(index);
  13704. if (order >= 0) {
  13705. this._gl.enableVertexAttribArray(order);
  13706. this._vertexAttribArraysEnabled[order] = true;
  13707. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13708. }
  13709. offset += vertexDeclaration[index] * 4;
  13710. }
  13711. }
  13712. }
  13713. this._bindIndexBufferWithCache(indexBuffer);
  13714. };
  13715. Engine.prototype._unbindVertexArrayObject = function () {
  13716. if (!this._cachedVertexArrayObject) {
  13717. return;
  13718. }
  13719. this._cachedVertexArrayObject = null;
  13720. this._gl.bindVertexArray(null);
  13721. };
  13722. /**
  13723. * Bind a list of vertex buffers to the webGL context
  13724. * @param vertexBuffers defines the list of vertex buffers to bind
  13725. * @param indexBuffer defines the index buffer to bind
  13726. * @param effect defines the effect associated with the vertex buffers
  13727. */
  13728. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13729. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13730. this._cachedVertexBuffers = vertexBuffers;
  13731. this._cachedEffectForVertexBuffers = effect;
  13732. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13733. }
  13734. this._bindIndexBufferWithCache(indexBuffer);
  13735. };
  13736. /**
  13737. * Unbind all instance attributes
  13738. */
  13739. Engine.prototype.unbindInstanceAttributes = function () {
  13740. var boundBuffer;
  13741. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13742. var instancesBuffer = this._currentInstanceBuffers[i];
  13743. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13744. boundBuffer = instancesBuffer;
  13745. this.bindArrayBuffer(instancesBuffer);
  13746. }
  13747. var offsetLocation = this._currentInstanceLocations[i];
  13748. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13749. }
  13750. this._currentInstanceBuffers.length = 0;
  13751. this._currentInstanceLocations.length = 0;
  13752. };
  13753. /**
  13754. * Release and free the memory of a vertex array object
  13755. * @param vao defines the vertex array object to delete
  13756. */
  13757. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13758. this._gl.deleteVertexArray(vao);
  13759. };
  13760. /** @hidden */
  13761. Engine.prototype._releaseBuffer = function (buffer) {
  13762. buffer.references--;
  13763. if (buffer.references === 0) {
  13764. this._gl.deleteBuffer(buffer);
  13765. return true;
  13766. }
  13767. return false;
  13768. };
  13769. /**
  13770. * Creates a webGL buffer to use with instanciation
  13771. * @param capacity defines the size of the buffer
  13772. * @returns the webGL buffer
  13773. */
  13774. Engine.prototype.createInstancesBuffer = function (capacity) {
  13775. var buffer = this._gl.createBuffer();
  13776. if (!buffer) {
  13777. throw new Error("Unable to create instance buffer");
  13778. }
  13779. buffer.capacity = capacity;
  13780. this.bindArrayBuffer(buffer);
  13781. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13782. return buffer;
  13783. };
  13784. /**
  13785. * Delete a webGL buffer used with instanciation
  13786. * @param buffer defines the webGL buffer to delete
  13787. */
  13788. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13789. this._gl.deleteBuffer(buffer);
  13790. };
  13791. /**
  13792. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13793. * @param instancesBuffer defines the webGL buffer to update and bind
  13794. * @param data defines the data to store in the buffer
  13795. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13796. */
  13797. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13798. this.bindArrayBuffer(instancesBuffer);
  13799. if (data) {
  13800. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13801. }
  13802. if (offsetLocations[0].index !== undefined) {
  13803. var stride = 0;
  13804. for (var i = 0; i < offsetLocations.length; i++) {
  13805. var ai = offsetLocations[i];
  13806. stride += ai.attributeSize * 4;
  13807. }
  13808. for (var i = 0; i < offsetLocations.length; i++) {
  13809. var ai = offsetLocations[i];
  13810. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13811. this._gl.enableVertexAttribArray(ai.index);
  13812. this._vertexAttribArraysEnabled[ai.index] = true;
  13813. }
  13814. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13815. this._gl.vertexAttribDivisor(ai.index, 1);
  13816. this._currentInstanceLocations.push(ai.index);
  13817. this._currentInstanceBuffers.push(instancesBuffer);
  13818. }
  13819. }
  13820. else {
  13821. for (var index = 0; index < 4; index++) {
  13822. var offsetLocation = offsetLocations[index];
  13823. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13824. this._gl.enableVertexAttribArray(offsetLocation);
  13825. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13826. }
  13827. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13828. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13829. this._currentInstanceLocations.push(offsetLocation);
  13830. this._currentInstanceBuffers.push(instancesBuffer);
  13831. }
  13832. }
  13833. };
  13834. /**
  13835. * Apply all cached states (depth, culling, stencil and alpha)
  13836. */
  13837. Engine.prototype.applyStates = function () {
  13838. this._depthCullingState.apply(this._gl);
  13839. this._stencilState.apply(this._gl);
  13840. this._alphaState.apply(this._gl);
  13841. };
  13842. /**
  13843. * Send a draw order
  13844. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13845. * @param indexStart defines the starting index
  13846. * @param indexCount defines the number of index to draw
  13847. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13848. */
  13849. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13850. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13851. };
  13852. /**
  13853. * Draw a list of points
  13854. * @param verticesStart defines the index of first vertex to draw
  13855. * @param verticesCount defines the count of vertices to draw
  13856. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13857. */
  13858. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13859. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13860. };
  13861. /**
  13862. * Draw a list of unindexed primitives
  13863. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13864. * @param verticesStart defines the index of first vertex to draw
  13865. * @param verticesCount defines the count of vertices to draw
  13866. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13867. */
  13868. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13869. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13870. };
  13871. /**
  13872. * Draw a list of indexed primitives
  13873. * @param fillMode defines the primitive to use
  13874. * @param indexStart defines the starting index
  13875. * @param indexCount defines the number of index to draw
  13876. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13877. */
  13878. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13879. // Apply states
  13880. this.applyStates();
  13881. this._drawCalls.addCount(1, false);
  13882. // Render
  13883. var drawMode = this._drawMode(fillMode);
  13884. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13885. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13886. if (instancesCount) {
  13887. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13888. }
  13889. else {
  13890. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13891. }
  13892. };
  13893. /**
  13894. * Draw a list of unindexed primitives
  13895. * @param fillMode defines the primitive to use
  13896. * @param verticesStart defines the index of first vertex to draw
  13897. * @param verticesCount defines the count of vertices to draw
  13898. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13899. */
  13900. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13901. // Apply states
  13902. this.applyStates();
  13903. this._drawCalls.addCount(1, false);
  13904. var drawMode = this._drawMode(fillMode);
  13905. if (instancesCount) {
  13906. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13907. }
  13908. else {
  13909. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13910. }
  13911. };
  13912. Engine.prototype._drawMode = function (fillMode) {
  13913. switch (fillMode) {
  13914. // Triangle views
  13915. case BABYLON.Material.TriangleFillMode:
  13916. return this._gl.TRIANGLES;
  13917. case BABYLON.Material.PointFillMode:
  13918. return this._gl.POINTS;
  13919. case BABYLON.Material.WireFrameFillMode:
  13920. return this._gl.LINES;
  13921. // Draw modes
  13922. case BABYLON.Material.PointListDrawMode:
  13923. return this._gl.POINTS;
  13924. case BABYLON.Material.LineListDrawMode:
  13925. return this._gl.LINES;
  13926. case BABYLON.Material.LineLoopDrawMode:
  13927. return this._gl.LINE_LOOP;
  13928. case BABYLON.Material.LineStripDrawMode:
  13929. return this._gl.LINE_STRIP;
  13930. case BABYLON.Material.TriangleStripDrawMode:
  13931. return this._gl.TRIANGLE_STRIP;
  13932. case BABYLON.Material.TriangleFanDrawMode:
  13933. return this._gl.TRIANGLE_FAN;
  13934. default:
  13935. return this._gl.TRIANGLES;
  13936. }
  13937. };
  13938. // Shaders
  13939. /** @hidden */
  13940. Engine.prototype._releaseEffect = function (effect) {
  13941. if (this._compiledEffects[effect._key]) {
  13942. delete this._compiledEffects[effect._key];
  13943. this._deleteProgram(effect.getProgram());
  13944. }
  13945. };
  13946. /** @hidden */
  13947. Engine.prototype._deleteProgram = function (program) {
  13948. if (program) {
  13949. program.__SPECTOR_rebuildProgram = null;
  13950. if (program.transformFeedback) {
  13951. this.deleteTransformFeedback(program.transformFeedback);
  13952. program.transformFeedback = null;
  13953. }
  13954. this._gl.deleteProgram(program);
  13955. }
  13956. };
  13957. /**
  13958. * Create a new effect (used to store vertex/fragment shaders)
  13959. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13960. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13961. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13962. * @param samplers defines an array of string used to represent textures
  13963. * @param defines defines the string containing the defines to use to compile the shaders
  13964. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13965. * @param onCompiled defines a function to call when the effect creation is successful
  13966. * @param onError defines a function to call when the effect creation has failed
  13967. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13968. * @returns the new Effect
  13969. */
  13970. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13971. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13972. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13973. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13974. if (this._compiledEffects[name]) {
  13975. var compiledEffect = this._compiledEffects[name];
  13976. if (onCompiled && compiledEffect.isReady()) {
  13977. onCompiled(compiledEffect);
  13978. }
  13979. return compiledEffect;
  13980. }
  13981. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13982. effect._key = name;
  13983. this._compiledEffects[name] = effect;
  13984. return effect;
  13985. };
  13986. /**
  13987. * Create an effect to use with particle systems
  13988. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13989. * @param uniformsNames defines a list of attribute names
  13990. * @param samplers defines an array of string used to represent textures
  13991. * @param defines defines the string containing the defines to use to compile the shaders
  13992. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13993. * @param onCompiled defines a function to call when the effect creation is successful
  13994. * @param onError defines a function to call when the effect creation has failed
  13995. * @returns the new Effect
  13996. */
  13997. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13998. if (uniformsNames === void 0) { uniformsNames = []; }
  13999. if (samplers === void 0) { samplers = []; }
  14000. if (defines === void 0) { defines = ""; }
  14001. return this.createEffect({
  14002. vertex: "particles",
  14003. fragmentElement: fragmentName
  14004. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  14005. };
  14006. /**
  14007. * Directly creates a webGL program
  14008. * @param vertexCode defines the vertex shader code to use
  14009. * @param fragmentCode defines the fragment shader code to use
  14010. * @param context defines the webGL context to use (if not set, the current one will be used)
  14011. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14012. * @returns the new webGL program
  14013. */
  14014. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14015. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14016. context = context || this._gl;
  14017. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14018. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14019. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14020. };
  14021. /**
  14022. * Creates a webGL program
  14023. * @param vertexCode defines the vertex shader code to use
  14024. * @param fragmentCode defines the fragment shader code to use
  14025. * @param defines defines the string containing the defines to use to compile the shaders
  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.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14031. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14032. context = context || this._gl;
  14033. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14034. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14035. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14036. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14037. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14038. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14039. return program;
  14040. };
  14041. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14042. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14043. var shaderProgram = context.createProgram();
  14044. if (!shaderProgram) {
  14045. throw new Error("Unable to create program");
  14046. }
  14047. context.attachShader(shaderProgram, vertexShader);
  14048. context.attachShader(shaderProgram, fragmentShader);
  14049. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14050. var transformFeedback = this.createTransformFeedback();
  14051. this.bindTransformFeedback(transformFeedback);
  14052. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14053. shaderProgram.transformFeedback = transformFeedback;
  14054. }
  14055. context.linkProgram(shaderProgram);
  14056. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14057. this.bindTransformFeedback(null);
  14058. }
  14059. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14060. if (!linked) {
  14061. context.validateProgram(shaderProgram);
  14062. var error = context.getProgramInfoLog(shaderProgram);
  14063. if (error) {
  14064. throw new Error(error);
  14065. }
  14066. }
  14067. context.deleteShader(vertexShader);
  14068. context.deleteShader(fragmentShader);
  14069. return shaderProgram;
  14070. };
  14071. /**
  14072. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14073. * @param shaderProgram defines the webGL program to use
  14074. * @param uniformsNames defines the list of uniform names
  14075. * @returns an array of webGL uniform locations
  14076. */
  14077. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14078. var results = new Array();
  14079. for (var index = 0; index < uniformsNames.length; index++) {
  14080. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14081. }
  14082. return results;
  14083. };
  14084. /**
  14085. * Gets the lsit of active attributes for a given webGL program
  14086. * @param shaderProgram defines the webGL program to use
  14087. * @param attributesNames defines the list of attribute names to get
  14088. * @returns an array of indices indicating the offset of each attribute
  14089. */
  14090. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14091. var results = [];
  14092. for (var index = 0; index < attributesNames.length; index++) {
  14093. try {
  14094. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14095. }
  14096. catch (e) {
  14097. results.push(-1);
  14098. }
  14099. }
  14100. return results;
  14101. };
  14102. /**
  14103. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14104. * @param effect defines the effect to activate
  14105. */
  14106. Engine.prototype.enableEffect = function (effect) {
  14107. if (!effect) {
  14108. return;
  14109. }
  14110. // Use program
  14111. this.bindSamplers(effect);
  14112. this._currentEffect = effect;
  14113. if (effect.onBind) {
  14114. effect.onBind(effect);
  14115. }
  14116. effect.onBindObservable.notifyObservers(effect);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to an array of int32
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param array defines the array of int32 to store
  14122. */
  14123. Engine.prototype.setIntArray = function (uniform, array) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniform1iv(uniform, array);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to an array of int32 (stored as vec2)
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param array defines the array of int32 to store
  14132. */
  14133. Engine.prototype.setIntArray2 = function (uniform, array) {
  14134. if (!uniform || array.length % 2 !== 0)
  14135. return;
  14136. this._gl.uniform2iv(uniform, array);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to an array of int32 (stored as vec3)
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param array defines the array of int32 to store
  14142. */
  14143. Engine.prototype.setIntArray3 = function (uniform, array) {
  14144. if (!uniform || array.length % 3 !== 0)
  14145. return;
  14146. this._gl.uniform3iv(uniform, array);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of int32 (stored as vec4)
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of int32 to store
  14152. */
  14153. Engine.prototype.setIntArray4 = function (uniform, array) {
  14154. if (!uniform || array.length % 4 !== 0)
  14155. return;
  14156. this._gl.uniform4iv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of float32
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of float32 to store
  14162. */
  14163. Engine.prototype.setFloatArray = function (uniform, array) {
  14164. if (!uniform)
  14165. return;
  14166. this._gl.uniform1fv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of float32 (stored as vec2)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of float32 to store
  14172. */
  14173. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14174. if (!uniform || array.length % 2 !== 0)
  14175. return;
  14176. this._gl.uniform2fv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of float32 (stored as vec3)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of float32 to store
  14182. */
  14183. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14184. if (!uniform || array.length % 3 !== 0)
  14185. return;
  14186. this._gl.uniform3fv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of float32 (stored as vec4)
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of float32 to store
  14192. */
  14193. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14194. if (!uniform || array.length % 4 !== 0)
  14195. return;
  14196. this._gl.uniform4fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of number
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of number to store
  14202. */
  14203. Engine.prototype.setArray = function (uniform, array) {
  14204. if (!uniform)
  14205. return;
  14206. this._gl.uniform1fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of number (stored as vec2)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of number to store
  14212. */
  14213. Engine.prototype.setArray2 = function (uniform, array) {
  14214. if (!uniform || array.length % 2 !== 0)
  14215. return;
  14216. this._gl.uniform2fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of number (stored as vec3)
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of number to store
  14222. */
  14223. Engine.prototype.setArray3 = function (uniform, array) {
  14224. if (!uniform || array.length % 3 !== 0)
  14225. return;
  14226. this._gl.uniform3fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of number (stored as vec4)
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of number to store
  14232. */
  14233. Engine.prototype.setArray4 = function (uniform, array) {
  14234. if (!uniform || array.length % 4 !== 0)
  14235. return;
  14236. this._gl.uniform4fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of float32 (stored as matrices)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param matrices defines the array of float32 to store
  14242. */
  14243. Engine.prototype.setMatrices = function (uniform, matrices) {
  14244. if (!uniform)
  14245. return;
  14246. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to a matrix
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param matrix defines the matrix to store
  14252. */
  14253. Engine.prototype.setMatrix = function (uniform, matrix) {
  14254. if (!uniform)
  14255. return;
  14256. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14257. };
  14258. /**
  14259. * Set the value of an uniform to a matrix (3x3)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14262. */
  14263. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14264. if (!uniform)
  14265. return;
  14266. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to a matrix (2x2)
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14272. */
  14273. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a number (int)
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param value defines the int number to store
  14282. */
  14283. Engine.prototype.setInt = function (uniform, value) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniform1i(uniform, value);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a number (float)
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param value defines the float number to store
  14292. */
  14293. Engine.prototype.setFloat = function (uniform, value) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniform1f(uniform, value);
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a vec2
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param x defines the 1st component of the value
  14302. * @param y defines the 2nd component of the value
  14303. */
  14304. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14305. if (!uniform)
  14306. return;
  14307. this._gl.uniform2f(uniform, x, y);
  14308. };
  14309. /**
  14310. * Set the value of an uniform to a vec3
  14311. * @param uniform defines the webGL uniform location where to store the value
  14312. * @param x defines the 1st component of the value
  14313. * @param y defines the 2nd component of the value
  14314. * @param z defines the 3rd component of the value
  14315. */
  14316. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14317. if (!uniform)
  14318. return;
  14319. this._gl.uniform3f(uniform, x, y, z);
  14320. };
  14321. /**
  14322. * Set the value of an uniform to a boolean
  14323. * @param uniform defines the webGL uniform location where to store the value
  14324. * @param bool defines the boolean to store
  14325. */
  14326. Engine.prototype.setBool = function (uniform, bool) {
  14327. if (!uniform)
  14328. return;
  14329. this._gl.uniform1i(uniform, bool);
  14330. };
  14331. /**
  14332. * Set the value of an uniform to a vec4
  14333. * @param uniform defines the webGL uniform location where to store the value
  14334. * @param x defines the 1st component of the value
  14335. * @param y defines the 2nd component of the value
  14336. * @param z defines the 3rd component of the value
  14337. * @param w defines the 4th component of the value
  14338. */
  14339. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14340. if (!uniform)
  14341. return;
  14342. this._gl.uniform4f(uniform, x, y, z, w);
  14343. };
  14344. /**
  14345. * Set the value of an uniform to a Color3
  14346. * @param uniform defines the webGL uniform location where to store the value
  14347. * @param color3 defines the color to store
  14348. */
  14349. Engine.prototype.setColor3 = function (uniform, color3) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14353. };
  14354. /**
  14355. * Set the value of an uniform to a Color3 and an alpha value
  14356. * @param uniform defines the webGL uniform location where to store the value
  14357. * @param color3 defines the color to store
  14358. * @param alpha defines the alpha component to store
  14359. */
  14360. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14361. if (!uniform)
  14362. return;
  14363. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14364. };
  14365. /**
  14366. * Sets a Color4 on a uniform variable
  14367. * @param uniform defines the uniform location
  14368. * @param color4 defines the value to be set
  14369. */
  14370. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14371. if (!uniform)
  14372. return;
  14373. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14374. };
  14375. // States
  14376. /**
  14377. * Set various states to the webGL context
  14378. * @param culling defines backface culling state
  14379. * @param zOffset defines the value to apply to zOffset (0 by default)
  14380. * @param force defines if states must be applied even if cache is up to date
  14381. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14382. */
  14383. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14384. if (zOffset === void 0) { zOffset = 0; }
  14385. if (reverseSide === void 0) { reverseSide = false; }
  14386. // Culling
  14387. if (this._depthCullingState.cull !== culling || force) {
  14388. this._depthCullingState.cull = culling;
  14389. }
  14390. // Cull face
  14391. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14392. if (this._depthCullingState.cullFace !== cullFace || force) {
  14393. this._depthCullingState.cullFace = cullFace;
  14394. }
  14395. // Z offset
  14396. this.setZOffset(zOffset);
  14397. // Front face
  14398. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14399. if (this._depthCullingState.frontFace !== frontFace || force) {
  14400. this._depthCullingState.frontFace = frontFace;
  14401. }
  14402. };
  14403. /**
  14404. * Set the z offset to apply to current rendering
  14405. * @param value defines the offset to apply
  14406. */
  14407. Engine.prototype.setZOffset = function (value) {
  14408. this._depthCullingState.zOffset = value;
  14409. };
  14410. /**
  14411. * Gets the current value of the zOffset
  14412. * @returns the current zOffset state
  14413. */
  14414. Engine.prototype.getZOffset = function () {
  14415. return this._depthCullingState.zOffset;
  14416. };
  14417. /**
  14418. * Enable or disable depth buffering
  14419. * @param enable defines the state to set
  14420. */
  14421. Engine.prototype.setDepthBuffer = function (enable) {
  14422. this._depthCullingState.depthTest = enable;
  14423. };
  14424. /**
  14425. * Gets a boolean indicating if depth writing is enabled
  14426. * @returns the current depth writing state
  14427. */
  14428. Engine.prototype.getDepthWrite = function () {
  14429. return this._depthCullingState.depthMask;
  14430. };
  14431. /**
  14432. * Enable or disable depth writing
  14433. * @param enable defines the state to set
  14434. */
  14435. Engine.prototype.setDepthWrite = function (enable) {
  14436. this._depthCullingState.depthMask = enable;
  14437. };
  14438. /**
  14439. * Enable or disable color writing
  14440. * @param enable defines the state to set
  14441. */
  14442. Engine.prototype.setColorWrite = function (enable) {
  14443. this._gl.colorMask(enable, enable, enable, enable);
  14444. this._colorWrite = enable;
  14445. };
  14446. /**
  14447. * Gets a boolean indicating if color writing is enabled
  14448. * @returns the current color writing state
  14449. */
  14450. Engine.prototype.getColorWrite = function () {
  14451. return this._colorWrite;
  14452. };
  14453. /**
  14454. * Sets alpha constants used by some alpha blending modes
  14455. * @param r defines the red component
  14456. * @param g defines the green component
  14457. * @param b defines the blue component
  14458. * @param a defines the alpha component
  14459. */
  14460. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14461. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14462. };
  14463. /**
  14464. * Sets the current alpha mode
  14465. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14466. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14467. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14468. */
  14469. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14470. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14471. if (this._alphaMode === mode) {
  14472. return;
  14473. }
  14474. switch (mode) {
  14475. case Engine.ALPHA_DISABLE:
  14476. this._alphaState.alphaBlend = false;
  14477. break;
  14478. case Engine.ALPHA_PREMULTIPLIED:
  14479. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14480. this._alphaState.alphaBlend = true;
  14481. break;
  14482. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14483. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14484. this._alphaState.alphaBlend = true;
  14485. break;
  14486. case Engine.ALPHA_COMBINE:
  14487. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14488. this._alphaState.alphaBlend = true;
  14489. break;
  14490. case Engine.ALPHA_ONEONE:
  14491. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14492. this._alphaState.alphaBlend = true;
  14493. break;
  14494. case Engine.ALPHA_ADD:
  14495. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14496. this._alphaState.alphaBlend = true;
  14497. break;
  14498. case Engine.ALPHA_SUBTRACT:
  14499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14500. this._alphaState.alphaBlend = true;
  14501. break;
  14502. case Engine.ALPHA_MULTIPLY:
  14503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14504. this._alphaState.alphaBlend = true;
  14505. break;
  14506. case Engine.ALPHA_MAXIMIZED:
  14507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14508. this._alphaState.alphaBlend = true;
  14509. break;
  14510. case Engine.ALPHA_INTERPOLATE:
  14511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14512. this._alphaState.alphaBlend = true;
  14513. break;
  14514. case Engine.ALPHA_SCREENMODE:
  14515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14516. this._alphaState.alphaBlend = true;
  14517. break;
  14518. }
  14519. if (!noDepthWriteChange) {
  14520. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14521. }
  14522. this._alphaMode = mode;
  14523. };
  14524. /**
  14525. * Gets the current alpha mode
  14526. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14527. * @returns the current alpha mode
  14528. */
  14529. Engine.prototype.getAlphaMode = function () {
  14530. return this._alphaMode;
  14531. };
  14532. // Textures
  14533. /**
  14534. * Force the entire cache to be cleared
  14535. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14536. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14537. */
  14538. Engine.prototype.wipeCaches = function (bruteForce) {
  14539. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14540. return;
  14541. }
  14542. this._currentEffect = null;
  14543. if (bruteForce) {
  14544. this.resetTextureCache();
  14545. this._currentProgram = null;
  14546. this._stencilState.reset();
  14547. this._depthCullingState.reset();
  14548. this.setDepthFunctionToLessOrEqual();
  14549. this._alphaState.reset();
  14550. }
  14551. this._resetVertexBufferBinding();
  14552. this._cachedIndexBuffer = null;
  14553. this._cachedEffectForVertexBuffers = null;
  14554. this._unbindVertexArrayObject();
  14555. this.bindIndexBuffer(null);
  14556. };
  14557. /**
  14558. * Set the compressed texture format to use, based on the formats you have, and the formats
  14559. * supported by the hardware / browser.
  14560. *
  14561. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14562. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14563. * to API arguments needed to compressed textures. This puts the burden on the container
  14564. * generator to house the arcane code for determining these for current & future formats.
  14565. *
  14566. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14567. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14568. *
  14569. * Note: The result of this call is not taken into account when a texture is base64.
  14570. *
  14571. * @param formatsAvailable defines the list of those format families you have created
  14572. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14573. *
  14574. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14575. * @returns The extension selected.
  14576. */
  14577. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14578. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14579. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14580. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14581. return this._textureFormatInUse = this._texturesSupported[i];
  14582. }
  14583. }
  14584. }
  14585. // actively set format to nothing, to allow this to be called more than once
  14586. // and possibly fail the 2nd time
  14587. this._textureFormatInUse = null;
  14588. return null;
  14589. };
  14590. /** @hidden */
  14591. Engine.prototype._createTexture = function () {
  14592. var texture = this._gl.createTexture();
  14593. if (!texture) {
  14594. throw new Error("Unable to create texture");
  14595. }
  14596. return texture;
  14597. };
  14598. /**
  14599. * Usually called from BABYLON.Texture.ts.
  14600. * Passed information to create a WebGLTexture
  14601. * @param urlArg defines a value which contains one of the following:
  14602. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14603. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14604. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14605. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14606. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14607. * @param scene needed for loading to the correct scene
  14608. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14609. * @param onLoad optional callback to be called upon successful completion
  14610. * @param onError optional callback to be called upon failure
  14611. * @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
  14612. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14613. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14614. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14615. */
  14616. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14617. var _this = this;
  14618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14619. if (onLoad === void 0) { onLoad = null; }
  14620. if (onError === void 0) { onError = null; }
  14621. if (buffer === void 0) { buffer = null; }
  14622. if (fallback === void 0) { fallback = null; }
  14623. if (format === void 0) { format = null; }
  14624. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14625. var fromData = url.substr(0, 5) === "data:";
  14626. var fromBlob = url.substr(0, 5) === "blob:";
  14627. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14628. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14629. // establish the file extension, if possible
  14630. var lastDot = url.lastIndexOf('.');
  14631. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14632. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14633. var isTGA = (extension.indexOf(".tga") === 0);
  14634. // determine if a ktx file should be substituted
  14635. var isKTX = false;
  14636. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14637. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14638. isKTX = true;
  14639. }
  14640. if (scene) {
  14641. scene._addPendingData(texture);
  14642. }
  14643. texture.url = url;
  14644. texture.generateMipMaps = !noMipmap;
  14645. texture.samplingMode = samplingMode;
  14646. texture.invertY = invertY;
  14647. if (!this._doNotHandleContextLost) {
  14648. // Keep a link to the buffer only if we plan to handle context lost
  14649. texture._buffer = buffer;
  14650. }
  14651. var onLoadObserver = null;
  14652. if (onLoad && !fallback) {
  14653. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14654. }
  14655. if (!fallback)
  14656. this._internalTexturesCache.push(texture);
  14657. var onerror = function (message, exception) {
  14658. if (scene) {
  14659. scene._removePendingData(texture);
  14660. }
  14661. if (onLoadObserver) {
  14662. texture.onLoadedObservable.remove(onLoadObserver);
  14663. }
  14664. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14665. if (isKTX) {
  14666. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14667. }
  14668. else if (BABYLON.Tools.UseFallbackTexture) {
  14669. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14670. }
  14671. if (onError) {
  14672. onError(message || "Unknown error", exception);
  14673. }
  14674. };
  14675. var callback = null;
  14676. // processing for non-image formats
  14677. if (isKTX || isTGA || isDDS) {
  14678. if (isKTX) {
  14679. callback = function (data) {
  14680. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14681. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14682. ktx.uploadLevels(_this._gl, !noMipmap);
  14683. return false;
  14684. }, samplingMode);
  14685. };
  14686. }
  14687. else if (isTGA) {
  14688. callback = function (arrayBuffer) {
  14689. var data = new Uint8Array(arrayBuffer);
  14690. var header = BABYLON.TGATools.GetTGAHeader(data);
  14691. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14692. BABYLON.TGATools.UploadContent(_this._gl, data);
  14693. return false;
  14694. }, samplingMode);
  14695. };
  14696. }
  14697. else if (isDDS) {
  14698. callback = function (data) {
  14699. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14700. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14701. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14702. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14703. return false;
  14704. }, samplingMode);
  14705. };
  14706. }
  14707. if (!buffer) {
  14708. this._loadFile(url, function (data) {
  14709. if (callback) {
  14710. callback(data);
  14711. }
  14712. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14713. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14714. });
  14715. }
  14716. else {
  14717. if (callback) {
  14718. callback(buffer);
  14719. }
  14720. }
  14721. // image format processing
  14722. }
  14723. else {
  14724. var onload = function (img) {
  14725. if (fromBlob && !_this._doNotHandleContextLost) {
  14726. // We need to store the image if we need to rebuild the texture
  14727. // in case of a webgl context lost
  14728. texture._buffer = img;
  14729. }
  14730. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14731. var gl = _this._gl;
  14732. var isPot = (img.width === potWidth && img.height === potHeight);
  14733. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14734. if (isPot) {
  14735. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14736. return false;
  14737. }
  14738. // Using shaders to rescale because canvas.drawImage is lossy
  14739. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14740. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14741. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14746. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14747. _this._releaseTexture(source);
  14748. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14749. continuationCallback();
  14750. });
  14751. return true;
  14752. }, samplingMode);
  14753. };
  14754. if (!fromData || isBase64) {
  14755. if (buffer instanceof HTMLImageElement) {
  14756. onload(buffer);
  14757. }
  14758. else {
  14759. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14760. }
  14761. }
  14762. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14763. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14764. }
  14765. else {
  14766. onload(buffer);
  14767. }
  14768. }
  14769. return texture;
  14770. };
  14771. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14772. var _this = this;
  14773. var rtt = this.createRenderTargetTexture({
  14774. width: destination.width,
  14775. height: destination.height,
  14776. }, {
  14777. generateMipMaps: false,
  14778. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14779. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14780. generateDepthBuffer: false,
  14781. generateStencilBuffer: false
  14782. });
  14783. if (!this._rescalePostProcess) {
  14784. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14785. }
  14786. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14787. _this._rescalePostProcess.onApply = function (effect) {
  14788. effect._bindTexture("textureSampler", source);
  14789. };
  14790. var hostingScene = scene;
  14791. if (!hostingScene) {
  14792. hostingScene = _this.scenes[_this.scenes.length - 1];
  14793. }
  14794. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14795. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14796. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14797. _this.unBindFramebuffer(rtt);
  14798. _this._releaseTexture(rtt);
  14799. if (onComplete) {
  14800. onComplete();
  14801. }
  14802. });
  14803. };
  14804. /**
  14805. * Update a raw texture
  14806. * @param texture defines the texture to update
  14807. * @param data defines the data to store in the texture
  14808. * @param format defines the format of the data
  14809. * @param invertY defines if data must be stored with Y axis inverted
  14810. * @param compression defines the compression used (null by default)
  14811. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14812. */
  14813. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14814. if (compression === void 0) { compression = null; }
  14815. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14816. if (!texture) {
  14817. return;
  14818. }
  14819. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14820. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14821. // babylon's internalFormat but gl's texImage2D format
  14822. var internalFormat = this._getInternalFormat(format);
  14823. var textureType = this._getWebGLTextureType(type);
  14824. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14825. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14826. if (!this._doNotHandleContextLost) {
  14827. texture._bufferView = data;
  14828. texture.format = format;
  14829. texture.type = type;
  14830. texture.invertY = invertY;
  14831. texture._compression = compression;
  14832. }
  14833. if (texture.width % 4 !== 0) {
  14834. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14835. }
  14836. if (compression && data) {
  14837. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14838. }
  14839. else {
  14840. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14841. }
  14842. if (texture.generateMipMaps) {
  14843. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14844. }
  14845. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14846. // this.resetTextureCache();
  14847. texture.isReady = true;
  14848. };
  14849. /**
  14850. * Creates a raw texture
  14851. * @param data defines the data to store in the texture
  14852. * @param width defines the width of the texture
  14853. * @param height defines the height of the texture
  14854. * @param format defines the format of the data
  14855. * @param generateMipMaps defines if the engine should generate the mip levels
  14856. * @param invertY defines if data must be stored with Y axis inverted
  14857. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14858. * @param compression defines the compression used (null by default)
  14859. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14860. * @returns the raw texture inside an InternalTexture
  14861. */
  14862. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14863. if (compression === void 0) { compression = null; }
  14864. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14865. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14866. texture.baseWidth = width;
  14867. texture.baseHeight = height;
  14868. texture.width = width;
  14869. texture.height = height;
  14870. texture.format = format;
  14871. texture.generateMipMaps = generateMipMaps;
  14872. texture.samplingMode = samplingMode;
  14873. texture.invertY = invertY;
  14874. texture._compression = compression;
  14875. texture.type = type;
  14876. if (!this._doNotHandleContextLost) {
  14877. texture._bufferView = data;
  14878. }
  14879. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14880. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14881. // Filters
  14882. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14883. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14885. if (generateMipMaps) {
  14886. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14887. }
  14888. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14889. this._internalTexturesCache.push(texture);
  14890. return texture;
  14891. };
  14892. /**
  14893. * Creates a dynamic texture
  14894. * @param width defines the width of the texture
  14895. * @param height defines the height of the texture
  14896. * @param generateMipMaps defines if the engine should generate the mip levels
  14897. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14898. * @returns the dynamic texture inside an InternalTexture
  14899. */
  14900. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14901. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14902. texture.baseWidth = width;
  14903. texture.baseHeight = height;
  14904. if (generateMipMaps) {
  14905. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14906. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14907. }
  14908. // this.resetTextureCache();
  14909. texture.width = width;
  14910. texture.height = height;
  14911. texture.isReady = false;
  14912. texture.generateMipMaps = generateMipMaps;
  14913. texture.samplingMode = samplingMode;
  14914. this.updateTextureSamplingMode(samplingMode, texture);
  14915. this._internalTexturesCache.push(texture);
  14916. return texture;
  14917. };
  14918. /**
  14919. * Update the sampling mode of a given texture
  14920. * @param samplingMode defines the required sampling mode
  14921. * @param texture defines the texture to update
  14922. */
  14923. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14924. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14925. if (texture.isCube) {
  14926. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14927. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14928. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14929. }
  14930. else if (texture.is3D) {
  14931. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14932. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14933. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14934. }
  14935. else {
  14936. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14937. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14938. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14939. }
  14940. texture.samplingMode = samplingMode;
  14941. };
  14942. /**
  14943. * Update the content of a dynamic texture
  14944. * @param texture defines the texture to update
  14945. * @param canvas defines the canvas containing the source
  14946. * @param invertY defines if data must be stored with Y axis inverted
  14947. * @param premulAlpha defines if alpha is stored as premultiplied
  14948. * @param format defines the format of the data
  14949. */
  14950. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14951. if (premulAlpha === void 0) { premulAlpha = false; }
  14952. if (!texture) {
  14953. return;
  14954. }
  14955. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14956. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14957. if (premulAlpha) {
  14958. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14959. }
  14960. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14961. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14962. if (texture.generateMipMaps) {
  14963. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14964. }
  14965. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14966. if (premulAlpha) {
  14967. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14968. }
  14969. texture.isReady = true;
  14970. };
  14971. /**
  14972. * Update a video texture
  14973. * @param texture defines the texture to update
  14974. * @param video defines the video element to use
  14975. * @param invertY defines if data must be stored with Y axis inverted
  14976. */
  14977. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14978. if (!texture || texture._isDisabled) {
  14979. return;
  14980. }
  14981. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14982. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14983. try {
  14984. // Testing video texture support
  14985. if (this._videoTextureSupported === undefined) {
  14986. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14987. if (this._gl.getError() !== 0) {
  14988. this._videoTextureSupported = false;
  14989. }
  14990. else {
  14991. this._videoTextureSupported = true;
  14992. }
  14993. }
  14994. // Copy video through the current working canvas if video texture is not supported
  14995. if (!this._videoTextureSupported) {
  14996. if (!texture._workingCanvas) {
  14997. texture._workingCanvas = document.createElement("canvas");
  14998. var context = texture._workingCanvas.getContext("2d");
  14999. if (!context) {
  15000. throw new Error("Unable to get 2d context");
  15001. }
  15002. texture._workingContext = context;
  15003. texture._workingCanvas.width = texture.width;
  15004. texture._workingCanvas.height = texture.height;
  15005. }
  15006. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15007. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15008. }
  15009. else {
  15010. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15011. }
  15012. if (texture.generateMipMaps) {
  15013. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15014. }
  15015. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15016. // this.resetTextureCache();
  15017. texture.isReady = true;
  15018. }
  15019. catch (ex) {
  15020. // Something unexpected
  15021. // Let's disable the texture
  15022. texture._isDisabled = true;
  15023. }
  15024. };
  15025. /**
  15026. * Updates a depth texture Comparison Mode and Function.
  15027. * If the comparison Function is equal to 0, the mode will be set to none.
  15028. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15029. * @param texture The texture to set the comparison function for
  15030. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15031. */
  15032. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15033. if (this.webGLVersion === 1) {
  15034. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15035. return;
  15036. }
  15037. var gl = this._gl;
  15038. if (texture.isCube) {
  15039. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15040. if (comparisonFunction === 0) {
  15041. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15043. }
  15044. else {
  15045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15047. }
  15048. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15049. }
  15050. else {
  15051. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15052. if (comparisonFunction === 0) {
  15053. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15054. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15055. }
  15056. else {
  15057. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15058. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15059. }
  15060. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15061. }
  15062. texture._comparisonFunction = comparisonFunction;
  15063. };
  15064. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15065. var width = size.width || size;
  15066. var height = size.height || size;
  15067. internalTexture.baseWidth = width;
  15068. internalTexture.baseHeight = height;
  15069. internalTexture.width = width;
  15070. internalTexture.height = height;
  15071. internalTexture.isReady = true;
  15072. internalTexture.samples = 1;
  15073. internalTexture.generateMipMaps = false;
  15074. internalTexture._generateDepthBuffer = true;
  15075. internalTexture._generateStencilBuffer = generateStencil;
  15076. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15077. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15078. internalTexture._comparisonFunction = comparisonFunction;
  15079. var gl = this._gl;
  15080. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15081. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15082. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15083. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15084. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15085. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15086. if (comparisonFunction === 0) {
  15087. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15088. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15089. }
  15090. else {
  15091. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15092. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15093. }
  15094. };
  15095. /**
  15096. * Creates a depth stencil texture.
  15097. * This is only available in WebGL 2 or with the depth texture extension available.
  15098. * @param size The size of face edge in the texture.
  15099. * @param options The options defining the texture.
  15100. * @returns The texture
  15101. */
  15102. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15103. if (options.isCube) {
  15104. var width = size.width || size;
  15105. return this._createDepthStencilCubeTexture(width, options);
  15106. }
  15107. else {
  15108. return this._createDepthStencilTexture(size, options);
  15109. }
  15110. };
  15111. /**
  15112. * Creates a depth stencil texture.
  15113. * This is only available in WebGL 2 or with the depth texture extension available.
  15114. * @param size The size of face edge in the texture.
  15115. * @param options The options defining the texture.
  15116. * @returns The texture
  15117. */
  15118. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15119. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15120. if (!this._caps.depthTextureExtension) {
  15121. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15122. return internalTexture;
  15123. }
  15124. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15125. var gl = this._gl;
  15126. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15127. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15128. if (this.webGLVersion > 1) {
  15129. if (internalOptions.generateStencil) {
  15130. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15131. }
  15132. else {
  15133. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15134. }
  15135. }
  15136. else {
  15137. if (internalOptions.generateStencil) {
  15138. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15139. }
  15140. else {
  15141. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15142. }
  15143. }
  15144. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15145. return internalTexture;
  15146. };
  15147. /**
  15148. * Creates a depth stencil cube texture.
  15149. * This is only available in WebGL 2.
  15150. * @param size The size of face edge in the cube texture.
  15151. * @param options The options defining the cube texture.
  15152. * @returns The cube texture
  15153. */
  15154. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15155. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15156. internalTexture.isCube = true;
  15157. if (this.webGLVersion === 1) {
  15158. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15159. return internalTexture;
  15160. }
  15161. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15162. var gl = this._gl;
  15163. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15164. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15165. // Create the depth/stencil buffer
  15166. for (var face = 0; face < 6; face++) {
  15167. if (internalOptions.generateStencil) {
  15168. 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);
  15169. }
  15170. else {
  15171. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15172. }
  15173. }
  15174. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15175. return internalTexture;
  15176. };
  15177. /**
  15178. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15179. * @param renderTarget The render target to set the frame buffer for
  15180. */
  15181. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15182. // Create the framebuffer
  15183. var internalTexture = renderTarget.getInternalTexture();
  15184. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15185. return;
  15186. }
  15187. var gl = this._gl;
  15188. var depthStencilTexture = renderTarget.depthStencilTexture;
  15189. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15190. if (depthStencilTexture.isCube) {
  15191. if (depthStencilTexture._generateStencilBuffer) {
  15192. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15193. }
  15194. else {
  15195. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15196. }
  15197. }
  15198. else {
  15199. if (depthStencilTexture._generateStencilBuffer) {
  15200. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15201. }
  15202. else {
  15203. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15204. }
  15205. }
  15206. this.bindUnboundFramebuffer(null);
  15207. };
  15208. /**
  15209. * Creates a new render target texture
  15210. * @param size defines the size of the texture
  15211. * @param options defines the options used to create the texture
  15212. * @returns a new render target texture stored in an InternalTexture
  15213. */
  15214. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15215. var fullOptions = new RenderTargetCreationOptions();
  15216. if (options !== undefined && typeof options === "object") {
  15217. fullOptions.generateMipMaps = options.generateMipMaps;
  15218. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15219. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15220. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15221. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15222. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15223. }
  15224. else {
  15225. fullOptions.generateMipMaps = options;
  15226. fullOptions.generateDepthBuffer = true;
  15227. fullOptions.generateStencilBuffer = false;
  15228. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15229. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15230. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15231. }
  15232. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15233. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15234. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15235. }
  15236. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15237. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15238. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15239. }
  15240. var gl = this._gl;
  15241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15242. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15243. var width = size.width || size;
  15244. var height = size.height || size;
  15245. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15246. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15247. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15248. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15249. }
  15250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15254. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15255. // Create the framebuffer
  15256. var currentFrameBuffer = this._currentFramebuffer;
  15257. var framebuffer = gl.createFramebuffer();
  15258. this.bindUnboundFramebuffer(framebuffer);
  15259. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15260. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15261. if (fullOptions.generateMipMaps) {
  15262. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15263. }
  15264. // Unbind
  15265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15266. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15267. this.bindUnboundFramebuffer(currentFrameBuffer);
  15268. texture._framebuffer = framebuffer;
  15269. texture.baseWidth = width;
  15270. texture.baseHeight = height;
  15271. texture.width = width;
  15272. texture.height = height;
  15273. texture.isReady = true;
  15274. texture.samples = 1;
  15275. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15276. texture.samplingMode = fullOptions.samplingMode;
  15277. texture.type = fullOptions.type;
  15278. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15279. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15280. // this.resetTextureCache();
  15281. this._internalTexturesCache.push(texture);
  15282. return texture;
  15283. };
  15284. /**
  15285. * Create a multi render target texture
  15286. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15287. * @param size defines the size of the texture
  15288. * @param options defines the creation options
  15289. * @returns the cube texture as an InternalTexture
  15290. */
  15291. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15292. var generateMipMaps = false;
  15293. var generateDepthBuffer = true;
  15294. var generateStencilBuffer = false;
  15295. var generateDepthTexture = false;
  15296. var textureCount = 1;
  15297. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15298. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15299. var types = new Array();
  15300. var samplingModes = new Array();
  15301. if (options !== undefined) {
  15302. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15303. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15304. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15305. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15306. textureCount = options.textureCount || 1;
  15307. if (options.types) {
  15308. types = options.types;
  15309. }
  15310. if (options.samplingModes) {
  15311. samplingModes = options.samplingModes;
  15312. }
  15313. }
  15314. var gl = this._gl;
  15315. // Create the framebuffer
  15316. var framebuffer = gl.createFramebuffer();
  15317. this.bindUnboundFramebuffer(framebuffer);
  15318. var width = size.width || size;
  15319. var height = size.height || size;
  15320. var textures = [];
  15321. var attachments = [];
  15322. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15323. for (var i = 0; i < textureCount; i++) {
  15324. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15325. var type = types[i] || defaultType;
  15326. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15327. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15328. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15329. }
  15330. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15331. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15332. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15333. }
  15334. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15335. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15336. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15337. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15338. }
  15339. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15340. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15341. textures.push(texture);
  15342. attachments.push(attachment);
  15343. gl.activeTexture(gl["TEXTURE" + i]);
  15344. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15345. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15349. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15350. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15351. if (generateMipMaps) {
  15352. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15353. }
  15354. // Unbind
  15355. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15356. texture._framebuffer = framebuffer;
  15357. texture._depthStencilBuffer = depthStencilBuffer;
  15358. texture.baseWidth = width;
  15359. texture.baseHeight = height;
  15360. texture.width = width;
  15361. texture.height = height;
  15362. texture.isReady = true;
  15363. texture.samples = 1;
  15364. texture.generateMipMaps = generateMipMaps;
  15365. texture.samplingMode = samplingMode;
  15366. texture.type = type;
  15367. texture._generateDepthBuffer = generateDepthBuffer;
  15368. texture._generateStencilBuffer = generateStencilBuffer;
  15369. texture._attachments = attachments;
  15370. this._internalTexturesCache.push(texture);
  15371. }
  15372. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15373. // Depth texture
  15374. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15375. gl.activeTexture(gl.TEXTURE0);
  15376. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15381. 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);
  15382. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15383. depthTexture._framebuffer = framebuffer;
  15384. depthTexture.baseWidth = width;
  15385. depthTexture.baseHeight = height;
  15386. depthTexture.width = width;
  15387. depthTexture.height = height;
  15388. depthTexture.isReady = true;
  15389. depthTexture.samples = 1;
  15390. depthTexture.generateMipMaps = generateMipMaps;
  15391. depthTexture.samplingMode = gl.NEAREST;
  15392. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15393. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15394. textures.push(depthTexture);
  15395. this._internalTexturesCache.push(depthTexture);
  15396. }
  15397. gl.drawBuffers(attachments);
  15398. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15399. this.bindUnboundFramebuffer(null);
  15400. this.resetTextureCache();
  15401. return textures;
  15402. };
  15403. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15404. if (samples === void 0) { samples = 1; }
  15405. var depthStencilBuffer = null;
  15406. var gl = this._gl;
  15407. // Create the depth/stencil buffer
  15408. if (generateStencilBuffer) {
  15409. depthStencilBuffer = gl.createRenderbuffer();
  15410. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15411. if (samples > 1) {
  15412. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15413. }
  15414. else {
  15415. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15416. }
  15417. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15418. }
  15419. else if (generateDepthBuffer) {
  15420. depthStencilBuffer = gl.createRenderbuffer();
  15421. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15422. if (samples > 1) {
  15423. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15424. }
  15425. else {
  15426. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15427. }
  15428. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15429. }
  15430. return depthStencilBuffer;
  15431. };
  15432. /**
  15433. * Updates the sample count of a render target texture
  15434. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15435. * @param texture defines the texture to update
  15436. * @param samples defines the sample count to set
  15437. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15438. */
  15439. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15440. if (this.webGLVersion < 2 || !texture) {
  15441. return 1;
  15442. }
  15443. if (texture.samples === samples) {
  15444. return samples;
  15445. }
  15446. var gl = this._gl;
  15447. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15448. // Dispose previous render buffers
  15449. if (texture._depthStencilBuffer) {
  15450. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15451. texture._depthStencilBuffer = null;
  15452. }
  15453. if (texture._MSAAFramebuffer) {
  15454. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15455. texture._MSAAFramebuffer = null;
  15456. }
  15457. if (texture._MSAARenderBuffer) {
  15458. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15459. texture._MSAARenderBuffer = null;
  15460. }
  15461. if (samples > 1) {
  15462. var framebuffer = gl.createFramebuffer();
  15463. if (!framebuffer) {
  15464. throw new Error("Unable to create multi sampled framebuffer");
  15465. }
  15466. texture._MSAAFramebuffer = framebuffer;
  15467. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15468. var colorRenderbuffer = gl.createRenderbuffer();
  15469. if (!colorRenderbuffer) {
  15470. throw new Error("Unable to create multi sampled framebuffer");
  15471. }
  15472. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15473. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15474. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15475. texture._MSAARenderBuffer = colorRenderbuffer;
  15476. }
  15477. else {
  15478. this.bindUnboundFramebuffer(texture._framebuffer);
  15479. }
  15480. texture.samples = samples;
  15481. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15482. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15483. this.bindUnboundFramebuffer(null);
  15484. return samples;
  15485. };
  15486. /**
  15487. * Update the sample count for a given multiple render target texture
  15488. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15489. * @param textures defines the textures to update
  15490. * @param samples defines the sample count to set
  15491. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15492. */
  15493. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15494. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15495. return 1;
  15496. }
  15497. if (textures[0].samples === samples) {
  15498. return samples;
  15499. }
  15500. var gl = this._gl;
  15501. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15502. // Dispose previous render buffers
  15503. if (textures[0]._depthStencilBuffer) {
  15504. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15505. textures[0]._depthStencilBuffer = null;
  15506. }
  15507. if (textures[0]._MSAAFramebuffer) {
  15508. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15509. textures[0]._MSAAFramebuffer = null;
  15510. }
  15511. for (var i = 0; i < textures.length; i++) {
  15512. if (textures[i]._MSAARenderBuffer) {
  15513. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15514. textures[i]._MSAARenderBuffer = null;
  15515. }
  15516. }
  15517. if (samples > 1) {
  15518. var framebuffer = gl.createFramebuffer();
  15519. if (!framebuffer) {
  15520. throw new Error("Unable to create multi sampled framebuffer");
  15521. }
  15522. this.bindUnboundFramebuffer(framebuffer);
  15523. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15524. var attachments = [];
  15525. for (var i = 0; i < textures.length; i++) {
  15526. var texture = textures[i];
  15527. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15528. var colorRenderbuffer = gl.createRenderbuffer();
  15529. if (!colorRenderbuffer) {
  15530. throw new Error("Unable to create multi sampled framebuffer");
  15531. }
  15532. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15533. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15534. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15535. texture._MSAAFramebuffer = framebuffer;
  15536. texture._MSAARenderBuffer = colorRenderbuffer;
  15537. texture.samples = samples;
  15538. texture._depthStencilBuffer = depthStencilBuffer;
  15539. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15540. attachments.push(attachment);
  15541. }
  15542. gl.drawBuffers(attachments);
  15543. }
  15544. else {
  15545. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15546. }
  15547. this.bindUnboundFramebuffer(null);
  15548. return samples;
  15549. };
  15550. /** @hidden */
  15551. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15552. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15553. };
  15554. /** @hidden */
  15555. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15556. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15557. };
  15558. /**
  15559. * Creates a new render target cube texture
  15560. * @param size defines the size of the texture
  15561. * @param options defines the options used to create the texture
  15562. * @returns a new render target cube texture stored in an InternalTexture
  15563. */
  15564. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15565. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15566. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15567. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15568. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15569. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15570. }
  15571. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15572. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15573. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15574. }
  15575. var gl = this._gl;
  15576. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15577. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15578. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15579. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15580. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15581. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15582. }
  15583. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15584. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15585. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15587. for (var face = 0; face < 6; face++) {
  15588. 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);
  15589. }
  15590. // Create the framebuffer
  15591. var framebuffer = gl.createFramebuffer();
  15592. this.bindUnboundFramebuffer(framebuffer);
  15593. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15594. // MipMaps
  15595. if (fullOptions.generateMipMaps) {
  15596. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15597. }
  15598. // Unbind
  15599. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15600. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15601. this.bindUnboundFramebuffer(null);
  15602. texture._framebuffer = framebuffer;
  15603. texture.width = size;
  15604. texture.height = size;
  15605. texture.isReady = true;
  15606. texture.isCube = true;
  15607. texture.samples = 1;
  15608. texture.generateMipMaps = fullOptions.generateMipMaps;
  15609. texture.samplingMode = fullOptions.samplingMode;
  15610. texture.type = fullOptions.type;
  15611. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15612. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15613. this._internalTexturesCache.push(texture);
  15614. return texture;
  15615. };
  15616. /**
  15617. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15618. * @param rootUrl defines the url where the file to load is located
  15619. * @param scene defines the current scene
  15620. * @param scale defines scale to apply to the mip map selection
  15621. * @param offset defines offset to apply to the mip map selection
  15622. * @param onLoad defines an optional callback raised when the texture is loaded
  15623. * @param onError defines an optional callback raised if there is an issue to load the texture
  15624. * @param format defines the format of the data
  15625. * @param forcedExtension defines the extension to use to pick the right loader
  15626. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15627. * @returns the cube texture as an InternalTexture
  15628. */
  15629. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15630. var _this = this;
  15631. if (onLoad === void 0) { onLoad = null; }
  15632. if (onError === void 0) { onError = null; }
  15633. if (forcedExtension === void 0) { forcedExtension = null; }
  15634. if (createPolynomials === void 0) { createPolynomials = true; }
  15635. var callback = function (loadData) {
  15636. if (!loadData) {
  15637. if (onLoad) {
  15638. onLoad(null);
  15639. }
  15640. return;
  15641. }
  15642. var texture = loadData.texture;
  15643. if (!createPolynomials) {
  15644. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15645. }
  15646. else if (loadData.info.sphericalPolynomial) {
  15647. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15648. }
  15649. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15650. texture._lodGenerationScale = scale;
  15651. texture._lodGenerationOffset = offset;
  15652. if (_this._caps.textureLOD) {
  15653. // Do not add extra process if texture lod is supported.
  15654. if (onLoad) {
  15655. onLoad(texture);
  15656. }
  15657. return;
  15658. }
  15659. var mipSlices = 3;
  15660. var gl = _this._gl;
  15661. var width = loadData.width;
  15662. if (!width) {
  15663. return;
  15664. }
  15665. var textures = [];
  15666. for (var i = 0; i < mipSlices; i++) {
  15667. //compute LOD from even spacing in smoothness (matching shader calculation)
  15668. var smoothness = i / (mipSlices - 1);
  15669. var roughness = 1 - smoothness;
  15670. var minLODIndex = offset; // roughness = 0
  15671. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15672. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15673. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15674. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15675. glTextureFromLod.isCube = true;
  15676. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15681. if (loadData.isDDS) {
  15682. var info = loadData.info;
  15683. var data = loadData.data;
  15684. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15685. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15686. }
  15687. else {
  15688. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15689. }
  15690. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15691. // Wrap in a base texture for easy binding.
  15692. var lodTexture = new BABYLON.BaseTexture(scene);
  15693. lodTexture.isCube = true;
  15694. lodTexture._texture = glTextureFromLod;
  15695. glTextureFromLod.isReady = true;
  15696. textures.push(lodTexture);
  15697. }
  15698. texture._lodTextureHigh = textures[2];
  15699. texture._lodTextureMid = textures[1];
  15700. texture._lodTextureLow = textures[0];
  15701. if (onLoad) {
  15702. onLoad(texture);
  15703. }
  15704. };
  15705. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  15706. };
  15707. /**
  15708. * Creates a cube texture
  15709. * @param rootUrl defines the url where the files to load is located
  15710. * @param scene defines the current scene
  15711. * @param files defines the list of files to load (1 per face)
  15712. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15713. * @param onLoad defines an optional callback raised when the texture is loaded
  15714. * @param onError defines an optional callback raised if there is an issue to load the texture
  15715. * @param format defines the format of the data
  15716. * @param forcedExtension defines the extension to use to pick the right loader
  15717. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15718. * @returns the cube texture as an InternalTexture
  15719. */
  15720. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15721. var _this = this;
  15722. if (onLoad === void 0) { onLoad = null; }
  15723. if (onError === void 0) { onError = null; }
  15724. if (forcedExtension === void 0) { forcedExtension = null; }
  15725. if (createPolynomials === void 0) { createPolynomials = false; }
  15726. var gl = this._gl;
  15727. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15728. texture.isCube = true;
  15729. texture.url = rootUrl;
  15730. texture.generateMipMaps = !noMipmap;
  15731. if (!this._doNotHandleContextLost) {
  15732. texture._extension = forcedExtension;
  15733. texture._files = files;
  15734. }
  15735. var isKTX = false;
  15736. var isDDS = false;
  15737. var lastDot = rootUrl.lastIndexOf('.');
  15738. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15739. if (this._textureFormatInUse) {
  15740. extension = this._textureFormatInUse;
  15741. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15742. isKTX = true;
  15743. }
  15744. else {
  15745. isDDS = (extension === ".dds");
  15746. }
  15747. var onerror = function (request, exception) {
  15748. if (onError && request) {
  15749. onError(request.status + " " + request.statusText, exception);
  15750. }
  15751. };
  15752. if (isKTX) {
  15753. this._loadFile(rootUrl, function (data) {
  15754. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15755. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15756. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15757. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15758. ktx.uploadLevels(_this._gl, !noMipmap);
  15759. _this.setCubeMapTextureParams(gl, loadMipmap);
  15760. texture.width = ktx.pixelWidth;
  15761. texture.height = ktx.pixelHeight;
  15762. texture.isReady = true;
  15763. }, undefined, undefined, true, onerror);
  15764. }
  15765. else if (isDDS) {
  15766. if (files && files.length === 6) {
  15767. this._cascadeLoadFiles(scene, function (imgs) {
  15768. var info;
  15769. var loadMipmap = false;
  15770. var width = 0;
  15771. for (var index = 0; index < imgs.length; index++) {
  15772. var data = imgs[index];
  15773. info = BABYLON.DDSTools.GetDDSInfo(data);
  15774. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15775. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15776. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15777. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15778. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15779. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15780. }
  15781. texture.width = info.width;
  15782. texture.height = info.height;
  15783. texture.type = info.textureType;
  15784. width = info.width;
  15785. }
  15786. _this.setCubeMapTextureParams(gl, loadMipmap);
  15787. texture.isReady = true;
  15788. if (onLoad) {
  15789. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15790. }
  15791. }, files, onError);
  15792. }
  15793. else {
  15794. this._loadFile(rootUrl, function (data) {
  15795. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15796. if (createPolynomials) {
  15797. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15798. }
  15799. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15800. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15801. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15802. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15803. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15804. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15805. }
  15806. _this.setCubeMapTextureParams(gl, loadMipmap);
  15807. texture.width = info.width;
  15808. texture.height = info.height;
  15809. texture.isReady = true;
  15810. texture.type = info.textureType;
  15811. if (onLoad) {
  15812. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15813. }
  15814. }, undefined, undefined, true, onerror);
  15815. }
  15816. }
  15817. else {
  15818. if (!files) {
  15819. throw new Error("Cannot load cubemap because files were not defined");
  15820. }
  15821. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15822. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15823. var height = width;
  15824. _this._prepareWorkingCanvas();
  15825. if (!_this._workingCanvas || !_this._workingContext) {
  15826. return;
  15827. }
  15828. _this._workingCanvas.width = width;
  15829. _this._workingCanvas.height = height;
  15830. var faces = [
  15831. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15832. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15833. ];
  15834. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15835. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15836. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15837. for (var index = 0; index < faces.length; index++) {
  15838. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15839. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15840. }
  15841. if (!noMipmap) {
  15842. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15843. }
  15844. _this.setCubeMapTextureParams(gl, !noMipmap);
  15845. texture.width = width;
  15846. texture.height = height;
  15847. texture.isReady = true;
  15848. if (format) {
  15849. texture.format = format;
  15850. }
  15851. texture.onLoadedObservable.notifyObservers(texture);
  15852. texture.onLoadedObservable.clear();
  15853. if (onLoad) {
  15854. onLoad();
  15855. }
  15856. }, files, onError);
  15857. }
  15858. this._internalTexturesCache.push(texture);
  15859. return texture;
  15860. };
  15861. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15866. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15867. // this.resetTextureCache();
  15868. };
  15869. /**
  15870. * Update a raw cube texture
  15871. * @param texture defines the texture to udpdate
  15872. * @param data defines the data to store
  15873. * @param format defines the data format
  15874. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15875. * @param invertY defines if data must be stored with Y axis inverted
  15876. * @param compression defines the compression used (null by default)
  15877. * @param level defines which level of the texture to update
  15878. */
  15879. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15880. if (compression === void 0) { compression = null; }
  15881. if (level === void 0) { level = 0; }
  15882. texture._bufferViewArray = data;
  15883. texture.format = format;
  15884. texture.type = type;
  15885. texture.invertY = invertY;
  15886. texture._compression = compression;
  15887. var gl = this._gl;
  15888. var textureType = this._getWebGLTextureType(type);
  15889. var internalFormat = this._getInternalFormat(format);
  15890. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15891. var needConversion = false;
  15892. if (internalFormat === gl.RGB) {
  15893. internalFormat = gl.RGBA;
  15894. needConversion = true;
  15895. }
  15896. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15897. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15898. if (texture.width % 4 !== 0) {
  15899. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15900. }
  15901. // Data are known to be in +X +Y +Z -X -Y -Z
  15902. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15903. var faceData = data[faceIndex];
  15904. if (compression) {
  15905. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15906. }
  15907. else {
  15908. if (needConversion) {
  15909. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15910. }
  15911. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15912. }
  15913. }
  15914. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15915. if (isPot && texture.generateMipMaps && level === 0) {
  15916. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15917. }
  15918. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15919. // this.resetTextureCache();
  15920. texture.isReady = true;
  15921. };
  15922. /**
  15923. * Creates a new raw cube texture
  15924. * @param data defines the array of data to use to create each face
  15925. * @param size defines the size of the textures
  15926. * @param format defines the format of the data
  15927. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15928. * @param generateMipMaps defines if the engine should generate the mip levels
  15929. * @param invertY defines if data must be stored with Y axis inverted
  15930. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15931. * @param compression defines the compression used (null by default)
  15932. * @returns the cube texture as an InternalTexture
  15933. */
  15934. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15935. if (compression === void 0) { compression = null; }
  15936. var gl = this._gl;
  15937. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15938. texture.isCube = true;
  15939. texture.generateMipMaps = generateMipMaps;
  15940. texture.format = format;
  15941. texture.type = type;
  15942. if (!this._doNotHandleContextLost) {
  15943. texture._bufferViewArray = data;
  15944. }
  15945. var textureType = this._getWebGLTextureType(type);
  15946. var internalFormat = this._getInternalFormat(format);
  15947. if (internalFormat === gl.RGB) {
  15948. internalFormat = gl.RGBA;
  15949. }
  15950. var width = size;
  15951. var height = width;
  15952. texture.width = width;
  15953. texture.height = height;
  15954. // Double check on POT to generate Mips.
  15955. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15956. if (!isPot) {
  15957. generateMipMaps = false;
  15958. }
  15959. // Upload data if needed. The texture won't be ready until then.
  15960. if (data) {
  15961. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15962. }
  15963. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15964. // Filters
  15965. if (data && generateMipMaps) {
  15966. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15967. }
  15968. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15969. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15970. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15971. }
  15972. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15975. }
  15976. else {
  15977. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15980. }
  15981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15982. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15983. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15984. return texture;
  15985. };
  15986. /**
  15987. * Creates a new raw cube texture from a specified url
  15988. * @param url defines the url where the data is located
  15989. * @param scene defines the current scene
  15990. * @param size defines the size of the textures
  15991. * @param format defines the format of the data
  15992. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15993. * @param noMipmap defines if the engine should avoid generating the mip levels
  15994. * @param callback defines a callback used to extract texture data from loaded data
  15995. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15996. * @param onLoad defines a callback called when texture is loaded
  15997. * @param onError defines a callback called if there is an error
  15998. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15999. * @param invertY defines if data must be stored with Y axis inverted
  16000. * @returns the cube texture as an InternalTexture
  16001. */
  16002. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16003. var _this = this;
  16004. if (onLoad === void 0) { onLoad = null; }
  16005. if (onError === void 0) { onError = null; }
  16006. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16007. if (invertY === void 0) { invertY = false; }
  16008. var gl = this._gl;
  16009. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16010. scene._addPendingData(texture);
  16011. texture.url = url;
  16012. this._internalTexturesCache.push(texture);
  16013. var onerror = function (request, exception) {
  16014. scene._removePendingData(texture);
  16015. if (onError && request) {
  16016. onError(request.status + " " + request.statusText, exception);
  16017. }
  16018. };
  16019. var internalCallback = function (data) {
  16020. var width = texture.width;
  16021. var faceDataArrays = callback(data);
  16022. if (!faceDataArrays) {
  16023. return;
  16024. }
  16025. if (mipmapGenerator) {
  16026. var textureType = _this._getWebGLTextureType(type);
  16027. var internalFormat = _this._getInternalFormat(format);
  16028. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16029. var needConversion = false;
  16030. if (internalFormat === gl.RGB) {
  16031. internalFormat = gl.RGBA;
  16032. needConversion = true;
  16033. }
  16034. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16035. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  16036. var mipData = mipmapGenerator(faceDataArrays);
  16037. for (var level = 0; level < mipData.length; level++) {
  16038. var mipSize = width >> level;
  16039. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16040. var mipFaceData = mipData[level][faceIndex];
  16041. if (needConversion) {
  16042. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16043. }
  16044. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16045. }
  16046. }
  16047. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16048. }
  16049. else {
  16050. texture.generateMipMaps = !noMipmap;
  16051. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16052. }
  16053. texture.isReady = true;
  16054. // this.resetTextureCache();
  16055. scene._removePendingData(texture);
  16056. if (onLoad) {
  16057. onLoad();
  16058. }
  16059. };
  16060. this._loadFile(url, function (data) {
  16061. internalCallback(data);
  16062. }, undefined, scene.database, true, onerror);
  16063. return texture;
  16064. };
  16065. ;
  16066. /**
  16067. * Update a raw 3D texture
  16068. * @param texture defines the texture to update
  16069. * @param data defines the data to store
  16070. * @param format defines the data format
  16071. * @param invertY defines if data must be stored with Y axis inverted
  16072. * @param compression defines the used compression (can be null)
  16073. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16074. */
  16075. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16076. if (compression === void 0) { compression = null; }
  16077. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16078. var internalType = this._getWebGLTextureType(textureType);
  16079. var internalFormat = this._getInternalFormat(format);
  16080. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16081. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16082. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16083. if (!this._doNotHandleContextLost) {
  16084. texture._bufferView = data;
  16085. texture.format = format;
  16086. texture.invertY = invertY;
  16087. texture._compression = compression;
  16088. }
  16089. if (texture.width % 4 !== 0) {
  16090. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16091. }
  16092. if (compression && data) {
  16093. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16094. }
  16095. else {
  16096. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16097. }
  16098. if (texture.generateMipMaps) {
  16099. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16100. }
  16101. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16102. // this.resetTextureCache();
  16103. texture.isReady = true;
  16104. };
  16105. /**
  16106. * Creates a new raw 3D texture
  16107. * @param data defines the data used to create the texture
  16108. * @param width defines the width of the texture
  16109. * @param height defines the height of the texture
  16110. * @param depth defines the depth of the texture
  16111. * @param format defines the format of the texture
  16112. * @param generateMipMaps defines if the engine must generate mip levels
  16113. * @param invertY defines if data must be stored with Y axis inverted
  16114. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16115. * @param compression defines the compressed used (can be null)
  16116. * @param textureType defines the compressed used (can be null)
  16117. * @returns a new raw 3D texture (stored in an InternalTexture)
  16118. */
  16119. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16120. if (compression === void 0) { compression = null; }
  16121. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16122. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16123. texture.baseWidth = width;
  16124. texture.baseHeight = height;
  16125. texture.baseDepth = depth;
  16126. texture.width = width;
  16127. texture.height = height;
  16128. texture.depth = depth;
  16129. texture.format = format;
  16130. texture.type = textureType;
  16131. texture.generateMipMaps = generateMipMaps;
  16132. texture.samplingMode = samplingMode;
  16133. texture.is3D = true;
  16134. if (!this._doNotHandleContextLost) {
  16135. texture._bufferView = data;
  16136. }
  16137. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16138. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16139. // Filters
  16140. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16141. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16142. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16143. if (generateMipMaps) {
  16144. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16145. }
  16146. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16147. this._internalTexturesCache.push(texture);
  16148. return texture;
  16149. };
  16150. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16151. var gl = this._gl;
  16152. if (!gl) {
  16153. return;
  16154. }
  16155. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16158. if (!noMipmap && !isCompressed) {
  16159. gl.generateMipmap(gl.TEXTURE_2D);
  16160. }
  16161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16162. // this.resetTextureCache();
  16163. if (scene) {
  16164. scene._removePendingData(texture);
  16165. }
  16166. texture.onLoadedObservable.notifyObservers(texture);
  16167. texture.onLoadedObservable.clear();
  16168. };
  16169. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16170. var _this = this;
  16171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16172. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16173. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16174. var gl = this._gl;
  16175. if (!gl) {
  16176. return;
  16177. }
  16178. if (!texture._webGLTexture) {
  16179. // this.resetTextureCache();
  16180. if (scene) {
  16181. scene._removePendingData(texture);
  16182. }
  16183. return;
  16184. }
  16185. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16186. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16187. texture.baseWidth = width;
  16188. texture.baseHeight = height;
  16189. texture.width = potWidth;
  16190. texture.height = potHeight;
  16191. texture.isReady = true;
  16192. if (processFunction(potWidth, potHeight, function () {
  16193. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16194. })) {
  16195. // Returning as texture needs extra async steps
  16196. return;
  16197. }
  16198. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16199. };
  16200. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16201. // Create new RGBA data container.
  16202. var rgbaData;
  16203. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16204. rgbaData = new Float32Array(width * height * 4);
  16205. }
  16206. else {
  16207. rgbaData = new Uint32Array(width * height * 4);
  16208. }
  16209. // Convert each pixel.
  16210. for (var x = 0; x < width; x++) {
  16211. for (var y = 0; y < height; y++) {
  16212. var index = (y * width + x) * 3;
  16213. var newIndex = (y * width + x) * 4;
  16214. // Map Old Value to new value.
  16215. rgbaData[newIndex + 0] = rgbData[index + 0];
  16216. rgbaData[newIndex + 1] = rgbData[index + 1];
  16217. rgbaData[newIndex + 2] = rgbData[index + 2];
  16218. // Add fully opaque alpha channel.
  16219. rgbaData[newIndex + 3] = 1;
  16220. }
  16221. }
  16222. return rgbaData;
  16223. };
  16224. /** @hidden */
  16225. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16226. var gl = this._gl;
  16227. if (texture._framebuffer) {
  16228. gl.deleteFramebuffer(texture._framebuffer);
  16229. texture._framebuffer = null;
  16230. }
  16231. if (texture._depthStencilBuffer) {
  16232. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16233. texture._depthStencilBuffer = null;
  16234. }
  16235. if (texture._MSAAFramebuffer) {
  16236. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16237. texture._MSAAFramebuffer = null;
  16238. }
  16239. if (texture._MSAARenderBuffer) {
  16240. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16241. texture._MSAARenderBuffer = null;
  16242. }
  16243. };
  16244. /** @hidden */
  16245. Engine.prototype._releaseTexture = function (texture) {
  16246. var gl = this._gl;
  16247. this._releaseFramebufferObjects(texture);
  16248. gl.deleteTexture(texture._webGLTexture);
  16249. // Unbind channels
  16250. this.unbindAllTextures();
  16251. var index = this._internalTexturesCache.indexOf(texture);
  16252. if (index !== -1) {
  16253. this._internalTexturesCache.splice(index, 1);
  16254. }
  16255. // Integrated fixed lod samplers.
  16256. if (texture._lodTextureHigh) {
  16257. texture._lodTextureHigh.dispose();
  16258. }
  16259. if (texture._lodTextureMid) {
  16260. texture._lodTextureMid.dispose();
  16261. }
  16262. if (texture._lodTextureLow) {
  16263. texture._lodTextureLow.dispose();
  16264. }
  16265. // Set output texture of post process to null if the texture has been released/disposed
  16266. this.scenes.forEach(function (scene) {
  16267. scene.postProcesses.forEach(function (postProcess) {
  16268. if (postProcess._outputTexture == texture) {
  16269. postProcess._outputTexture = null;
  16270. }
  16271. });
  16272. scene.cameras.forEach(function (camera) {
  16273. camera._postProcesses.forEach(function (postProcess) {
  16274. if (postProcess) {
  16275. if (postProcess._outputTexture == texture) {
  16276. postProcess._outputTexture = null;
  16277. }
  16278. }
  16279. });
  16280. });
  16281. });
  16282. };
  16283. Engine.prototype.setProgram = function (program) {
  16284. if (this._currentProgram !== program) {
  16285. this._gl.useProgram(program);
  16286. this._currentProgram = program;
  16287. }
  16288. };
  16289. /**
  16290. * Binds an effect to the webGL context
  16291. * @param effect defines the effect to bind
  16292. */
  16293. Engine.prototype.bindSamplers = function (effect) {
  16294. this.setProgram(effect.getProgram());
  16295. var samplers = effect.getSamplers();
  16296. for (var index = 0; index < samplers.length; index++) {
  16297. var uniform = effect.getUniform(samplers[index]);
  16298. if (uniform) {
  16299. this._boundUniforms[index] = uniform;
  16300. }
  16301. }
  16302. this._currentEffect = null;
  16303. };
  16304. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16305. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16306. return;
  16307. }
  16308. // Remove
  16309. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16310. // Bind last to it
  16311. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16312. // Bind to dummy
  16313. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16314. };
  16315. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16316. if (!internalTexture) {
  16317. return -1;
  16318. }
  16319. internalTexture._initialSlot = channel;
  16320. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16321. if (channel !== internalTexture._designatedSlot) {
  16322. this._textureCollisions.addCount(1, false);
  16323. }
  16324. }
  16325. else {
  16326. if (channel !== internalTexture._designatedSlot) {
  16327. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16328. return internalTexture._designatedSlot;
  16329. }
  16330. else {
  16331. // No slot for this texture, let's pick a new one (if we find a free slot)
  16332. if (this._nextFreeTextureSlots.length) {
  16333. return this._nextFreeTextureSlots[0];
  16334. }
  16335. // We need to recycle the oldest bound texture, sorry.
  16336. this._textureCollisions.addCount(1, false);
  16337. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16338. }
  16339. }
  16340. }
  16341. return channel;
  16342. };
  16343. Engine.prototype._linkTrackers = function (previous, next) {
  16344. previous.next = next;
  16345. next.previous = previous;
  16346. };
  16347. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16348. var currentSlot = internalTexture._designatedSlot;
  16349. if (currentSlot === -1) {
  16350. return -1;
  16351. }
  16352. internalTexture._designatedSlot = -1;
  16353. if (this.disableTextureBindingOptimization) {
  16354. return -1;
  16355. }
  16356. // Remove from bound list
  16357. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16358. // Free the slot
  16359. this._boundTexturesCache[currentSlot] = null;
  16360. this._nextFreeTextureSlots.push(currentSlot);
  16361. return currentSlot;
  16362. };
  16363. Engine.prototype._activateCurrentTexture = function () {
  16364. if (this._currentTextureChannel !== this._activeChannel) {
  16365. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16366. this._currentTextureChannel = this._activeChannel;
  16367. }
  16368. };
  16369. /** @hidden */
  16370. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16371. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16372. if (force === void 0) { force = false; }
  16373. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16374. this._activeChannel = texture._designatedSlot;
  16375. }
  16376. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16377. var isTextureForRendering = texture && texture._initialSlot > -1;
  16378. if (currentTextureBound !== texture || force) {
  16379. if (currentTextureBound) {
  16380. this._removeDesignatedSlot(currentTextureBound);
  16381. }
  16382. this._activateCurrentTexture();
  16383. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16384. this._boundTexturesCache[this._activeChannel] = texture;
  16385. if (texture) {
  16386. if (!this.disableTextureBindingOptimization) {
  16387. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16388. if (slotIndex > -1) {
  16389. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16390. }
  16391. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16392. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16393. }
  16394. texture._designatedSlot = this._activeChannel;
  16395. }
  16396. }
  16397. else if (forTextureDataUpdate) {
  16398. this._activateCurrentTexture();
  16399. }
  16400. if (isTextureForRendering && !forTextureDataUpdate) {
  16401. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16402. }
  16403. };
  16404. /** @hidden */
  16405. Engine.prototype._bindTexture = function (channel, texture) {
  16406. if (channel < 0) {
  16407. return;
  16408. }
  16409. if (texture) {
  16410. channel = this._getCorrectTextureChannel(channel, texture);
  16411. }
  16412. this._activeChannel = channel;
  16413. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16414. };
  16415. /**
  16416. * Sets a texture to the webGL context from a postprocess
  16417. * @param channel defines the channel to use
  16418. * @param postProcess defines the source postprocess
  16419. */
  16420. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16421. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16422. };
  16423. /**
  16424. * Binds the output of the passed in post process to the texture channel specified
  16425. * @param channel The channel the texture should be bound to
  16426. * @param postProcess The post process which's output should be bound
  16427. */
  16428. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16429. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16430. };
  16431. /**
  16432. * Unbind all textures from the webGL context
  16433. */
  16434. Engine.prototype.unbindAllTextures = function () {
  16435. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16436. this._activeChannel = channel;
  16437. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16438. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16439. if (this.webGLVersion > 1) {
  16440. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16441. }
  16442. }
  16443. };
  16444. /**
  16445. * Sets a texture to the according uniform.
  16446. * @param channel The texture channel
  16447. * @param uniform The uniform to set
  16448. * @param texture The texture to apply
  16449. */
  16450. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16451. if (channel < 0) {
  16452. return;
  16453. }
  16454. if (uniform) {
  16455. this._boundUniforms[channel] = uniform;
  16456. }
  16457. this._setTexture(channel, texture);
  16458. };
  16459. /**
  16460. * Sets a depth stencil texture from a render target to the according uniform.
  16461. * @param channel The texture channel
  16462. * @param uniform The uniform to set
  16463. * @param texture The render target texture containing the depth stencil texture to apply
  16464. */
  16465. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16466. if (channel < 0) {
  16467. return;
  16468. }
  16469. if (uniform) {
  16470. this._boundUniforms[channel] = uniform;
  16471. }
  16472. if (!texture || !texture.depthStencilTexture) {
  16473. this._setTexture(channel, null);
  16474. }
  16475. else {
  16476. this._setTexture(channel, texture, false, true);
  16477. }
  16478. };
  16479. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16480. var uniform = this._boundUniforms[sourceSlot];
  16481. if (uniform._currentState === destination) {
  16482. return;
  16483. }
  16484. this._gl.uniform1i(uniform, destination);
  16485. uniform._currentState = destination;
  16486. };
  16487. Engine.prototype._getTextureWrapMode = function (mode) {
  16488. switch (mode) {
  16489. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16490. return this._gl.REPEAT;
  16491. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16492. return this._gl.CLAMP_TO_EDGE;
  16493. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16494. return this._gl.MIRRORED_REPEAT;
  16495. }
  16496. return this._gl.REPEAT;
  16497. };
  16498. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16499. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16500. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16501. // Not ready?
  16502. if (!texture) {
  16503. if (this._boundTexturesCache[channel] != null) {
  16504. this._activeChannel = channel;
  16505. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16506. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16507. if (this.webGLVersion > 1) {
  16508. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16509. }
  16510. }
  16511. return false;
  16512. }
  16513. // Video
  16514. if (texture.video) {
  16515. this._activeChannel = channel;
  16516. texture.update();
  16517. }
  16518. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16519. texture.delayLoad();
  16520. return false;
  16521. }
  16522. var internalTexture;
  16523. if (depthStencilTexture) {
  16524. internalTexture = texture.depthStencilTexture;
  16525. }
  16526. else if (texture.isReady()) {
  16527. internalTexture = texture.getInternalTexture();
  16528. }
  16529. else if (texture.isCube) {
  16530. internalTexture = this.emptyCubeTexture;
  16531. }
  16532. else if (texture.is3D) {
  16533. internalTexture = this.emptyTexture3D;
  16534. }
  16535. else {
  16536. internalTexture = this.emptyTexture;
  16537. }
  16538. if (!isPartOfTextureArray) {
  16539. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16540. }
  16541. var needToBind = true;
  16542. if (this._boundTexturesCache[channel] === internalTexture) {
  16543. this._moveBoundTextureOnTop(internalTexture);
  16544. if (!isPartOfTextureArray) {
  16545. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16546. }
  16547. needToBind = false;
  16548. }
  16549. this._activeChannel = channel;
  16550. if (internalTexture && internalTexture.is3D) {
  16551. if (needToBind) {
  16552. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16553. }
  16554. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16555. internalTexture._cachedWrapU = texture.wrapU;
  16556. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16557. }
  16558. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16559. internalTexture._cachedWrapV = texture.wrapV;
  16560. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16561. }
  16562. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16563. internalTexture._cachedWrapR = texture.wrapR;
  16564. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16565. }
  16566. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16567. }
  16568. else if (internalTexture && internalTexture.isCube) {
  16569. if (needToBind) {
  16570. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16571. }
  16572. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16573. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16574. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16575. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16576. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16577. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16578. }
  16579. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16580. }
  16581. else {
  16582. if (needToBind) {
  16583. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16584. }
  16585. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16586. internalTexture._cachedWrapU = texture.wrapU;
  16587. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16588. }
  16589. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16590. internalTexture._cachedWrapV = texture.wrapV;
  16591. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16592. }
  16593. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16594. }
  16595. return true;
  16596. };
  16597. /**
  16598. * Sets an array of texture to the webGL context
  16599. * @param channel defines the channel where the texture array must be set
  16600. * @param uniform defines the associated uniform location
  16601. * @param textures defines the array of textures to bind
  16602. */
  16603. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16604. if (channel < 0 || !uniform) {
  16605. return;
  16606. }
  16607. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16608. this._textureUnits = new Int32Array(textures.length);
  16609. }
  16610. for (var i = 0; i < textures.length; i++) {
  16611. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16612. }
  16613. this._gl.uniform1iv(uniform, this._textureUnits);
  16614. for (var index = 0; index < textures.length; index++) {
  16615. this._setTexture(this._textureUnits[index], textures[index], true);
  16616. }
  16617. };
  16618. /** @hidden */
  16619. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16620. var internalTexture = texture.getInternalTexture();
  16621. if (!internalTexture) {
  16622. return;
  16623. }
  16624. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16625. var value = texture.anisotropicFilteringLevel;
  16626. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16627. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16628. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16629. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16630. }
  16631. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16632. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16633. internalTexture._cachedAnisotropicFilteringLevel = value;
  16634. }
  16635. };
  16636. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16637. this._bindTextureDirectly(target, texture, true, true);
  16638. this._gl.texParameterf(target, parameter, value);
  16639. };
  16640. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16641. if (texture) {
  16642. this._bindTextureDirectly(target, texture, true, true);
  16643. }
  16644. this._gl.texParameteri(target, parameter, value);
  16645. };
  16646. /**
  16647. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16648. * @param x defines the x coordinate of the rectangle where pixels must be read
  16649. * @param y defines the y coordinate of the rectangle where pixels must be read
  16650. * @param width defines the width of the rectangle where pixels must be read
  16651. * @param height defines the height of the rectangle where pixels must be read
  16652. * @returns a Uint8Array containing RGBA colors
  16653. */
  16654. Engine.prototype.readPixels = function (x, y, width, height) {
  16655. var data = new Uint8Array(height * width * 4);
  16656. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16657. return data;
  16658. };
  16659. /**
  16660. * Add an externaly attached data from its key.
  16661. * This method call will fail and return false, if such key already exists.
  16662. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16663. * @param key the unique key that identifies the data
  16664. * @param data the data object to associate to the key for this Engine instance
  16665. * @return true if no such key were already present and the data was added successfully, false otherwise
  16666. */
  16667. Engine.prototype.addExternalData = function (key, data) {
  16668. if (!this._externalData) {
  16669. this._externalData = new BABYLON.StringDictionary();
  16670. }
  16671. return this._externalData.add(key, data);
  16672. };
  16673. /**
  16674. * Get an externaly attached data from its key
  16675. * @param key the unique key that identifies the data
  16676. * @return the associated data, if present (can be null), or undefined if not present
  16677. */
  16678. Engine.prototype.getExternalData = function (key) {
  16679. if (!this._externalData) {
  16680. this._externalData = new BABYLON.StringDictionary();
  16681. }
  16682. return this._externalData.get(key);
  16683. };
  16684. /**
  16685. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16686. * @param key the unique key that identifies the data
  16687. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16688. * @return the associated data, can be null if the factory returned null.
  16689. */
  16690. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16691. if (!this._externalData) {
  16692. this._externalData = new BABYLON.StringDictionary();
  16693. }
  16694. return this._externalData.getOrAddWithFactory(key, factory);
  16695. };
  16696. /**
  16697. * Remove an externaly attached data from the Engine instance
  16698. * @param key the unique key that identifies the data
  16699. * @return true if the data was successfully removed, false if it doesn't exist
  16700. */
  16701. Engine.prototype.removeExternalData = function (key) {
  16702. if (!this._externalData) {
  16703. this._externalData = new BABYLON.StringDictionary();
  16704. }
  16705. return this._externalData.remove(key);
  16706. };
  16707. /**
  16708. * Unbind all vertex attributes from the webGL context
  16709. */
  16710. Engine.prototype.unbindAllAttributes = function () {
  16711. if (this._mustWipeVertexAttributes) {
  16712. this._mustWipeVertexAttributes = false;
  16713. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16714. this._gl.disableVertexAttribArray(i);
  16715. this._vertexAttribArraysEnabled[i] = false;
  16716. this._currentBufferPointers[i].active = false;
  16717. }
  16718. return;
  16719. }
  16720. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16721. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16722. continue;
  16723. }
  16724. this._gl.disableVertexAttribArray(i);
  16725. this._vertexAttribArraysEnabled[i] = false;
  16726. this._currentBufferPointers[i].active = false;
  16727. }
  16728. };
  16729. /**
  16730. * 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
  16731. */
  16732. Engine.prototype.releaseEffects = function () {
  16733. for (var name in this._compiledEffects) {
  16734. this._deleteProgram(this._compiledEffects[name]._program);
  16735. }
  16736. this._compiledEffects = {};
  16737. };
  16738. /**
  16739. * Dispose and release all associated resources
  16740. */
  16741. Engine.prototype.dispose = function () {
  16742. this.hideLoadingUI();
  16743. this.stopRenderLoop();
  16744. // Release postProcesses
  16745. while (this.postProcesses.length) {
  16746. this.postProcesses[0].dispose();
  16747. }
  16748. // Empty texture
  16749. if (this._emptyTexture) {
  16750. this._releaseTexture(this._emptyTexture);
  16751. this._emptyTexture = null;
  16752. }
  16753. if (this._emptyCubeTexture) {
  16754. this._releaseTexture(this._emptyCubeTexture);
  16755. this._emptyCubeTexture = null;
  16756. }
  16757. // Rescale PP
  16758. if (this._rescalePostProcess) {
  16759. this._rescalePostProcess.dispose();
  16760. }
  16761. // Release scenes
  16762. while (this.scenes.length) {
  16763. this.scenes[0].dispose();
  16764. }
  16765. // Release audio engine
  16766. if (Engine.audioEngine) {
  16767. Engine.audioEngine.dispose();
  16768. }
  16769. // Release effects
  16770. this.releaseEffects();
  16771. // Unbind
  16772. this.unbindAllAttributes();
  16773. this._boundUniforms = [];
  16774. if (this._dummyFramebuffer) {
  16775. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16776. }
  16777. //WebVR
  16778. this.disableVR();
  16779. // Events
  16780. if (BABYLON.Tools.IsWindowObjectExist()) {
  16781. window.removeEventListener("blur", this._onBlur);
  16782. window.removeEventListener("focus", this._onFocus);
  16783. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16784. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16785. if (this._renderingCanvas) {
  16786. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16787. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16788. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16789. if (!this._doNotHandleContextLost) {
  16790. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16791. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16792. }
  16793. }
  16794. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16795. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16796. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16797. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16798. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16799. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16800. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16801. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16802. if (this._onVrDisplayConnect) {
  16803. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16804. if (this._onVrDisplayDisconnect) {
  16805. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16806. }
  16807. if (this._onVrDisplayPresentChange) {
  16808. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16809. }
  16810. this._onVrDisplayConnect = null;
  16811. this._onVrDisplayDisconnect = null;
  16812. }
  16813. }
  16814. // Remove from Instances
  16815. var index = Engine.Instances.indexOf(this);
  16816. if (index >= 0) {
  16817. Engine.Instances.splice(index, 1);
  16818. }
  16819. this._workingCanvas = null;
  16820. this._workingContext = null;
  16821. this._currentBufferPointers = [];
  16822. this._renderingCanvas = null;
  16823. this._currentProgram = null;
  16824. this._bindedRenderFunction = null;
  16825. this.onResizeObservable.clear();
  16826. this.onCanvasBlurObservable.clear();
  16827. this.onCanvasFocusObservable.clear();
  16828. this.onCanvasPointerOutObservable.clear();
  16829. this.onBeginFrameObservable.clear();
  16830. this.onEndFrameObservable.clear();
  16831. BABYLON.Effect.ResetCache();
  16832. // Abort active requests
  16833. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16834. var request = _a[_i];
  16835. request.abort();
  16836. }
  16837. };
  16838. // Loading screen
  16839. /**
  16840. * Display the loading screen
  16841. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16842. */
  16843. Engine.prototype.displayLoadingUI = function () {
  16844. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16845. return;
  16846. }
  16847. var loadingScreen = this.loadingScreen;
  16848. if (loadingScreen) {
  16849. loadingScreen.displayLoadingUI();
  16850. }
  16851. };
  16852. /**
  16853. * Hide the loading screen
  16854. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16855. */
  16856. Engine.prototype.hideLoadingUI = function () {
  16857. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16858. return;
  16859. }
  16860. var loadingScreen = this.loadingScreen;
  16861. if (loadingScreen) {
  16862. loadingScreen.hideLoadingUI();
  16863. }
  16864. };
  16865. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16866. /**
  16867. * Gets the current loading screen object
  16868. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16869. */
  16870. get: function () {
  16871. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16872. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16873. return this._loadingScreen;
  16874. },
  16875. /**
  16876. * Sets the current loading screen object
  16877. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16878. */
  16879. set: function (loadingScreen) {
  16880. this._loadingScreen = loadingScreen;
  16881. },
  16882. enumerable: true,
  16883. configurable: true
  16884. });
  16885. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16886. /**
  16887. * Sets the current loading screen text
  16888. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16889. */
  16890. set: function (text) {
  16891. this.loadingScreen.loadingUIText = text;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16897. /**
  16898. * Sets the current loading screen background color
  16899. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16900. */
  16901. set: function (color) {
  16902. this.loadingScreen.loadingUIBackgroundColor = color;
  16903. },
  16904. enumerable: true,
  16905. configurable: true
  16906. });
  16907. /**
  16908. * Attach a new callback raised when context lost event is fired
  16909. * @param callback defines the callback to call
  16910. */
  16911. Engine.prototype.attachContextLostEvent = function (callback) {
  16912. if (this._renderingCanvas) {
  16913. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16914. }
  16915. };
  16916. /**
  16917. * Attach a new callback raised when context restored event is fired
  16918. * @param callback defines the callback to call
  16919. */
  16920. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16921. if (this._renderingCanvas) {
  16922. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16923. }
  16924. };
  16925. /**
  16926. * Gets the source code of the vertex shader associated with a specific webGL program
  16927. * @param program defines the program to use
  16928. * @returns a string containing the source code of the vertex shader associated with the program
  16929. */
  16930. Engine.prototype.getVertexShaderSource = function (program) {
  16931. var shaders = this._gl.getAttachedShaders(program);
  16932. if (!shaders) {
  16933. return null;
  16934. }
  16935. return this._gl.getShaderSource(shaders[0]);
  16936. };
  16937. /**
  16938. * Gets the source code of the fragment shader associated with a specific webGL program
  16939. * @param program defines the program to use
  16940. * @returns a string containing the source code of the fragment shader associated with the program
  16941. */
  16942. Engine.prototype.getFragmentShaderSource = function (program) {
  16943. var shaders = this._gl.getAttachedShaders(program);
  16944. if (!shaders) {
  16945. return null;
  16946. }
  16947. return this._gl.getShaderSource(shaders[1]);
  16948. };
  16949. /**
  16950. * Get the current error code of the webGL context
  16951. * @returns the error code
  16952. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16953. */
  16954. Engine.prototype.getError = function () {
  16955. return this._gl.getError();
  16956. };
  16957. // FPS
  16958. /**
  16959. * Gets the current framerate
  16960. * @returns a number representing the framerate
  16961. */
  16962. Engine.prototype.getFps = function () {
  16963. return this._fps;
  16964. };
  16965. /**
  16966. * Gets the time spent between current and previous frame
  16967. * @returns a number representing the delta time in ms
  16968. */
  16969. Engine.prototype.getDeltaTime = function () {
  16970. return this._deltaTime;
  16971. };
  16972. Engine.prototype._measureFps = function () {
  16973. this._performanceMonitor.sampleFrame();
  16974. this._fps = this._performanceMonitor.averageFPS;
  16975. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16976. };
  16977. /** @hidden */
  16978. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16979. if (faceIndex === void 0) { faceIndex = -1; }
  16980. var gl = this._gl;
  16981. if (!this._dummyFramebuffer) {
  16982. var dummy = gl.createFramebuffer();
  16983. if (!dummy) {
  16984. throw new Error("Unable to create dummy framebuffer");
  16985. }
  16986. this._dummyFramebuffer = dummy;
  16987. }
  16988. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16989. if (faceIndex > -1) {
  16990. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16991. }
  16992. else {
  16993. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16994. }
  16995. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16996. var buffer;
  16997. switch (readType) {
  16998. case gl.UNSIGNED_BYTE:
  16999. buffer = new Uint8Array(4 * width * height);
  17000. readType = gl.UNSIGNED_BYTE;
  17001. break;
  17002. default:
  17003. buffer = new Float32Array(4 * width * height);
  17004. readType = gl.FLOAT;
  17005. break;
  17006. }
  17007. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17008. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17009. return buffer;
  17010. };
  17011. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17012. if (this._webGLVersion > 1) {
  17013. return this._caps.colorBufferFloat;
  17014. }
  17015. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17016. };
  17017. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17018. if (this._webGLVersion > 1) {
  17019. return this._caps.colorBufferFloat;
  17020. }
  17021. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17022. };
  17023. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17024. Engine.prototype._canRenderToFramebuffer = function (type) {
  17025. var gl = this._gl;
  17026. //clear existing errors
  17027. while (gl.getError() !== gl.NO_ERROR) { }
  17028. var successful = true;
  17029. var texture = gl.createTexture();
  17030. gl.bindTexture(gl.TEXTURE_2D, texture);
  17031. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17032. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17034. var fb = gl.createFramebuffer();
  17035. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17036. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17037. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17038. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17039. successful = successful && (gl.getError() === gl.NO_ERROR);
  17040. //try render by clearing frame buffer's color buffer
  17041. if (successful) {
  17042. gl.clear(gl.COLOR_BUFFER_BIT);
  17043. successful = successful && (gl.getError() === gl.NO_ERROR);
  17044. }
  17045. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17046. if (successful) {
  17047. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17048. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17049. var readFormat = gl.RGBA;
  17050. var readType = gl.UNSIGNED_BYTE;
  17051. var buffer = new Uint8Array(4);
  17052. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17053. successful = successful && (gl.getError() === gl.NO_ERROR);
  17054. }
  17055. //clean up
  17056. gl.deleteTexture(texture);
  17057. gl.deleteFramebuffer(fb);
  17058. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17059. //clear accumulated errors
  17060. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17061. return successful;
  17062. };
  17063. /** @hidden */
  17064. Engine.prototype._getWebGLTextureType = function (type) {
  17065. if (type === Engine.TEXTURETYPE_FLOAT) {
  17066. return this._gl.FLOAT;
  17067. }
  17068. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17069. // Add Half Float Constant.
  17070. return this._gl.HALF_FLOAT_OES;
  17071. }
  17072. return this._gl.UNSIGNED_BYTE;
  17073. };
  17074. ;
  17075. Engine.prototype._getInternalFormat = function (format) {
  17076. var internalFormat = this._gl.RGBA;
  17077. switch (format) {
  17078. case Engine.TEXTUREFORMAT_ALPHA:
  17079. internalFormat = this._gl.ALPHA;
  17080. break;
  17081. case Engine.TEXTUREFORMAT_LUMINANCE:
  17082. internalFormat = this._gl.LUMINANCE;
  17083. break;
  17084. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17085. internalFormat = this._gl.LUMINANCE_ALPHA;
  17086. break;
  17087. case Engine.TEXTUREFORMAT_RGB:
  17088. internalFormat = this._gl.RGB;
  17089. break;
  17090. case Engine.TEXTUREFORMAT_RGBA:
  17091. internalFormat = this._gl.RGBA;
  17092. break;
  17093. case Engine.TEXTUREFORMAT_R:
  17094. internalFormat = this._gl.RED;
  17095. break;
  17096. case Engine.TEXTUREFORMAT_RG:
  17097. internalFormat = this._gl.RG;
  17098. break;
  17099. }
  17100. return internalFormat;
  17101. };
  17102. /** @hidden */
  17103. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17104. if (this._webGLVersion === 1) {
  17105. if (format !== undefined) {
  17106. switch (format) {
  17107. case Engine.TEXTUREFORMAT_LUMINANCE:
  17108. return this._gl.LUMINANCE;
  17109. case Engine.TEXTUREFORMAT_ALPHA:
  17110. return this._gl.ALPHA;
  17111. }
  17112. }
  17113. return this._gl.RGBA;
  17114. }
  17115. if (type === Engine.TEXTURETYPE_FLOAT) {
  17116. if (format !== undefined) {
  17117. switch (format) {
  17118. case Engine.TEXTUREFORMAT_R:
  17119. return this._gl.R32F;
  17120. case Engine.TEXTUREFORMAT_RG:
  17121. return this._gl.RG32F;
  17122. case Engine.TEXTUREFORMAT_RGB:
  17123. return this._gl.RGB32F;
  17124. }
  17125. }
  17126. return this._gl.RGBA32F;
  17127. }
  17128. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17129. if (format) {
  17130. switch (format) {
  17131. case Engine.TEXTUREFORMAT_R:
  17132. return this._gl.R16F;
  17133. case Engine.TEXTUREFORMAT_RG:
  17134. return this._gl.RG16F;
  17135. case Engine.TEXTUREFORMAT_RGB:
  17136. return this._gl.RGB16F;
  17137. }
  17138. }
  17139. return this._gl.RGBA16F;
  17140. }
  17141. if (format !== undefined) {
  17142. switch (format) {
  17143. case Engine.TEXTUREFORMAT_LUMINANCE:
  17144. return this._gl.LUMINANCE;
  17145. case Engine.TEXTUREFORMAT_RGB:
  17146. return this._gl.RGB;
  17147. case Engine.TEXTUREFORMAT_R:
  17148. return this._gl.R8;
  17149. case Engine.TEXTUREFORMAT_RG:
  17150. return this._gl.RG8;
  17151. case Engine.TEXTUREFORMAT_ALPHA:
  17152. return this._gl.ALPHA;
  17153. }
  17154. }
  17155. return this._gl.RGBA;
  17156. };
  17157. ;
  17158. /** @hidden */
  17159. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17160. if (type === Engine.TEXTURETYPE_FLOAT) {
  17161. return this._gl.RGBA32F;
  17162. }
  17163. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17164. return this._gl.RGBA16F;
  17165. }
  17166. return this._gl.RGBA8;
  17167. };
  17168. ;
  17169. /**
  17170. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17171. * @return the new query
  17172. */
  17173. Engine.prototype.createQuery = function () {
  17174. return this._gl.createQuery();
  17175. };
  17176. /**
  17177. * Delete and release a webGL query
  17178. * @param query defines the query to delete
  17179. * @return the current engine
  17180. */
  17181. Engine.prototype.deleteQuery = function (query) {
  17182. this._gl.deleteQuery(query);
  17183. return this;
  17184. };
  17185. /**
  17186. * Check if a given query has resolved and got its value
  17187. * @param query defines the query to check
  17188. * @returns true if the query got its value
  17189. */
  17190. Engine.prototype.isQueryResultAvailable = function (query) {
  17191. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17192. };
  17193. /**
  17194. * Gets the value of a given query
  17195. * @param query defines the query to check
  17196. * @returns the value of the query
  17197. */
  17198. Engine.prototype.getQueryResult = function (query) {
  17199. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17200. };
  17201. /**
  17202. * Initiates an occlusion query
  17203. * @param algorithmType defines the algorithm to use
  17204. * @param query defines the query to use
  17205. * @returns the current engine
  17206. * @see http://doc.babylonjs.com/features/occlusionquery
  17207. */
  17208. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17209. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17210. this._gl.beginQuery(glAlgorithm, query);
  17211. return this;
  17212. };
  17213. /**
  17214. * Ends an occlusion query
  17215. * @see http://doc.babylonjs.com/features/occlusionquery
  17216. * @param algorithmType defines the algorithm to use
  17217. * @returns the current engine
  17218. */
  17219. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17220. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17221. this._gl.endQuery(glAlgorithm);
  17222. return this;
  17223. };
  17224. /* Time queries */
  17225. Engine.prototype._createTimeQuery = function () {
  17226. var timerQuery = this._caps.timerQuery;
  17227. if (timerQuery.createQueryEXT) {
  17228. return timerQuery.createQueryEXT();
  17229. }
  17230. return this.createQuery();
  17231. };
  17232. Engine.prototype._deleteTimeQuery = function (query) {
  17233. var timerQuery = this._caps.timerQuery;
  17234. if (timerQuery.deleteQueryEXT) {
  17235. timerQuery.deleteQueryEXT(query);
  17236. return;
  17237. }
  17238. this.deleteQuery(query);
  17239. };
  17240. Engine.prototype._getTimeQueryResult = function (query) {
  17241. var timerQuery = this._caps.timerQuery;
  17242. if (timerQuery.getQueryObjectEXT) {
  17243. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17244. }
  17245. return this.getQueryResult(query);
  17246. };
  17247. Engine.prototype._getTimeQueryAvailability = function (query) {
  17248. var timerQuery = this._caps.timerQuery;
  17249. if (timerQuery.getQueryObjectEXT) {
  17250. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17251. }
  17252. return this.isQueryResultAvailable(query);
  17253. };
  17254. /**
  17255. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17256. * Please note that only one query can be issued at a time
  17257. * @returns a time token used to track the time span
  17258. */
  17259. Engine.prototype.startTimeQuery = function () {
  17260. var timerQuery = this._caps.timerQuery;
  17261. if (!timerQuery) {
  17262. return null;
  17263. }
  17264. var token = new BABYLON._TimeToken();
  17265. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17266. if (this._caps.canUseTimestampForTimerQuery) {
  17267. token._startTimeQuery = this._createTimeQuery();
  17268. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17269. }
  17270. else {
  17271. if (this._currentNonTimestampToken) {
  17272. return this._currentNonTimestampToken;
  17273. }
  17274. token._timeElapsedQuery = this._createTimeQuery();
  17275. if (timerQuery.beginQueryEXT) {
  17276. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17277. }
  17278. else {
  17279. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17280. }
  17281. this._currentNonTimestampToken = token;
  17282. }
  17283. return token;
  17284. };
  17285. /**
  17286. * Ends a time query
  17287. * @param token defines the token used to measure the time span
  17288. * @returns the time spent (in ns)
  17289. */
  17290. Engine.prototype.endTimeQuery = function (token) {
  17291. var timerQuery = this._caps.timerQuery;
  17292. if (!timerQuery || !token) {
  17293. return -1;
  17294. }
  17295. if (this._caps.canUseTimestampForTimerQuery) {
  17296. if (!token._startTimeQuery) {
  17297. return -1;
  17298. }
  17299. if (!token._endTimeQuery) {
  17300. token._endTimeQuery = this._createTimeQuery();
  17301. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17302. }
  17303. }
  17304. else if (!token._timeElapsedQueryEnded) {
  17305. if (!token._timeElapsedQuery) {
  17306. return -1;
  17307. }
  17308. if (timerQuery.endQueryEXT) {
  17309. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17310. }
  17311. else {
  17312. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17313. }
  17314. token._timeElapsedQueryEnded = true;
  17315. }
  17316. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17317. var available = false;
  17318. if (token._endTimeQuery) {
  17319. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17320. }
  17321. else if (token._timeElapsedQuery) {
  17322. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17323. }
  17324. if (available && !disjoint) {
  17325. var result = 0;
  17326. if (this._caps.canUseTimestampForTimerQuery) {
  17327. if (!token._startTimeQuery || !token._endTimeQuery) {
  17328. return -1;
  17329. }
  17330. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17331. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17332. result = timeEnd - timeStart;
  17333. this._deleteTimeQuery(token._startTimeQuery);
  17334. this._deleteTimeQuery(token._endTimeQuery);
  17335. token._startTimeQuery = null;
  17336. token._endTimeQuery = null;
  17337. }
  17338. else {
  17339. if (!token._timeElapsedQuery) {
  17340. return -1;
  17341. }
  17342. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17343. this._deleteTimeQuery(token._timeElapsedQuery);
  17344. token._timeElapsedQuery = null;
  17345. token._timeElapsedQueryEnded = false;
  17346. this._currentNonTimestampToken = null;
  17347. }
  17348. return result;
  17349. }
  17350. return -1;
  17351. };
  17352. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17353. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17354. };
  17355. // Transform feedback
  17356. /**
  17357. * Creates a webGL transform feedback object
  17358. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17359. * @returns the webGL transform feedback object
  17360. */
  17361. Engine.prototype.createTransformFeedback = function () {
  17362. return this._gl.createTransformFeedback();
  17363. };
  17364. /**
  17365. * Delete a webGL transform feedback object
  17366. * @param value defines the webGL transform feedback object to delete
  17367. */
  17368. Engine.prototype.deleteTransformFeedback = function (value) {
  17369. this._gl.deleteTransformFeedback(value);
  17370. };
  17371. /**
  17372. * Bind a webGL transform feedback object to the webgl context
  17373. * @param value defines the webGL transform feedback object to bind
  17374. */
  17375. Engine.prototype.bindTransformFeedback = function (value) {
  17376. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17377. };
  17378. /**
  17379. * Begins a transform feedback operation
  17380. * @param usePoints defines if points or triangles must be used
  17381. */
  17382. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17383. if (usePoints === void 0) { usePoints = true; }
  17384. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17385. };
  17386. /**
  17387. * Ends a transform feedback operation
  17388. */
  17389. Engine.prototype.endTransformFeedback = function () {
  17390. this._gl.endTransformFeedback();
  17391. };
  17392. /**
  17393. * Specify the varyings to use with transform feedback
  17394. * @param program defines the associated webGL program
  17395. * @param value defines the list of strings representing the varying names
  17396. */
  17397. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17398. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17399. };
  17400. /**
  17401. * Bind a webGL buffer for a transform feedback operation
  17402. * @param value defines the webGL buffer to bind
  17403. */
  17404. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17405. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17406. };
  17407. /** @hidden */
  17408. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17409. var _this = this;
  17410. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17411. this._activeRequests.push(request);
  17412. request.onCompleteObservable.add(function (request) {
  17413. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17414. });
  17415. return request;
  17416. };
  17417. /** @hidden */
  17418. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17419. var _this = this;
  17420. return new Promise(function (resolve, reject) {
  17421. _this._loadFile(url, function (data) {
  17422. resolve(data);
  17423. }, undefined, database, useArrayBuffer, function (request, exception) {
  17424. reject(exception);
  17425. });
  17426. });
  17427. };
  17428. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17429. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17430. var onload = function (data) {
  17431. loadedFiles[index] = data;
  17432. loadedFiles._internalCount++;
  17433. if (loadedFiles._internalCount === 6) {
  17434. onfinish(loadedFiles);
  17435. }
  17436. };
  17437. var onerror = function (request, exception) {
  17438. if (onErrorCallBack && request) {
  17439. onErrorCallBack(request.status + " " + request.statusText, exception);
  17440. }
  17441. };
  17442. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17443. };
  17444. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17445. if (onError === void 0) { onError = null; }
  17446. var loadedFiles = [];
  17447. loadedFiles._internalCount = 0;
  17448. for (var index = 0; index < 6; index++) {
  17449. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17450. }
  17451. };
  17452. // Statics
  17453. /**
  17454. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17455. * @returns true if the engine can be created
  17456. * @ignorenaming
  17457. */
  17458. Engine.isSupported = function () {
  17459. try {
  17460. var tempcanvas = document.createElement("canvas");
  17461. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17462. return gl != null && !!window.WebGLRenderingContext;
  17463. }
  17464. catch (e) {
  17465. return false;
  17466. }
  17467. };
  17468. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17469. Engine.ExceptionList = [
  17470. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17471. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17472. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17473. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17474. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17475. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17476. ];
  17477. /** Gets the list of created engines */
  17478. Engine.Instances = new Array();
  17479. // Const statics
  17480. Engine._ALPHA_DISABLE = 0;
  17481. Engine._ALPHA_ADD = 1;
  17482. Engine._ALPHA_COMBINE = 2;
  17483. Engine._ALPHA_SUBTRACT = 3;
  17484. Engine._ALPHA_MULTIPLY = 4;
  17485. Engine._ALPHA_MAXIMIZED = 5;
  17486. Engine._ALPHA_ONEONE = 6;
  17487. Engine._ALPHA_PREMULTIPLIED = 7;
  17488. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17489. Engine._ALPHA_INTERPOLATE = 9;
  17490. Engine._ALPHA_SCREENMODE = 10;
  17491. Engine._DELAYLOADSTATE_NONE = 0;
  17492. Engine._DELAYLOADSTATE_LOADED = 1;
  17493. Engine._DELAYLOADSTATE_LOADING = 2;
  17494. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17495. Engine._TEXTUREFORMAT_ALPHA = 0;
  17496. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17497. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17498. Engine._TEXTUREFORMAT_RGB = 4;
  17499. Engine._TEXTUREFORMAT_RGBA = 5;
  17500. Engine._TEXTUREFORMAT_R = 6;
  17501. Engine._TEXTUREFORMAT_RG = 7;
  17502. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17503. Engine._TEXTURETYPE_FLOAT = 1;
  17504. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17505. // Depht or Stencil test Constants.
  17506. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17507. 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.
  17508. 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.
  17509. 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.
  17510. 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.
  17511. 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.
  17512. 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.
  17513. 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.
  17514. // Stencil Actions Constants.
  17515. Engine._KEEP = 0x1E00;
  17516. Engine._REPLACE = 0x1E01;
  17517. Engine._INCR = 0x1E02;
  17518. Engine._DECR = 0x1E03;
  17519. Engine._INVERT = 0x150A;
  17520. Engine._INCR_WRAP = 0x8507;
  17521. Engine._DECR_WRAP = 0x8508;
  17522. // Texture rescaling mode
  17523. Engine._SCALEMODE_FLOOR = 1;
  17524. Engine._SCALEMODE_NEAREST = 2;
  17525. Engine._SCALEMODE_CEILING = 3;
  17526. // Updatable statics so stick with vars here
  17527. /**
  17528. * Gets or sets the epsilon value used by collision engine
  17529. */
  17530. Engine.CollisionsEpsilon = 0.001;
  17531. /**
  17532. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17533. */
  17534. Engine.CodeRepository = "src/";
  17535. /**
  17536. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17537. */
  17538. Engine.ShadersRepository = "src/Shaders/";
  17539. return Engine;
  17540. }());
  17541. BABYLON.Engine = Engine;
  17542. })(BABYLON || (BABYLON = {}));
  17543. //# sourceMappingURL=babylon.engine.js.map
  17544. var BABYLON;
  17545. (function (BABYLON) {
  17546. /**
  17547. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17548. */
  17549. var Node = /** @class */ (function () {
  17550. /**
  17551. * Creates a new Node
  17552. * @param {string} name - the name and id to be given to this node
  17553. * @param {BABYLON.Scene} the scene this node will be added to
  17554. */
  17555. function Node(name, scene) {
  17556. if (scene === void 0) { scene = null; }
  17557. /**
  17558. * Gets or sets a string used to store user defined state for the node
  17559. */
  17560. this.state = "";
  17561. /**
  17562. * Gets or sets an object used to store user defined information for the node
  17563. */
  17564. this.metadata = null;
  17565. /**
  17566. * Gets or sets a boolean used to define if the node must be serialized
  17567. */
  17568. this.doNotSerialize = false;
  17569. /** @hidden */
  17570. this._isDisposed = false;
  17571. /**
  17572. * Gets a list of Animations associated with the node
  17573. */
  17574. this.animations = new Array();
  17575. this._ranges = {};
  17576. this._isEnabled = true;
  17577. this._isReady = true;
  17578. /** @hidden */
  17579. this._currentRenderId = -1;
  17580. this._parentRenderId = -1;
  17581. this._childRenderId = -1;
  17582. this._animationPropertiesOverride = null;
  17583. /**
  17584. * An event triggered when the mesh is disposed
  17585. */
  17586. this.onDisposeObservable = new BABYLON.Observable();
  17587. // Behaviors
  17588. this._behaviors = new Array();
  17589. this.name = name;
  17590. this.id = name;
  17591. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17592. this.uniqueId = this._scene.getUniqueId();
  17593. this._initCache();
  17594. }
  17595. /**
  17596. * Gets a boolean indicating if the node has been disposed
  17597. * @returns true if the node was disposed
  17598. */
  17599. Node.prototype.isDisposed = function () {
  17600. return this._isDisposed;
  17601. };
  17602. Object.defineProperty(Node.prototype, "parent", {
  17603. get: function () {
  17604. return this._parentNode;
  17605. },
  17606. /**
  17607. * Gets or sets the parent of the node
  17608. */
  17609. set: function (parent) {
  17610. if (this._parentNode === parent) {
  17611. return;
  17612. }
  17613. // Remove self from list of children of parent
  17614. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17615. var index = this._parentNode._children.indexOf(this);
  17616. if (index !== -1) {
  17617. this._parentNode._children.splice(index, 1);
  17618. }
  17619. }
  17620. // Store new parent
  17621. this._parentNode = parent;
  17622. // Add as child to new parent
  17623. if (this._parentNode) {
  17624. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17625. this._parentNode._children = new Array();
  17626. }
  17627. this._parentNode._children.push(this);
  17628. }
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17634. /**
  17635. * Gets or sets the animation properties override
  17636. */
  17637. get: function () {
  17638. if (!this._animationPropertiesOverride) {
  17639. return this._scene.animationPropertiesOverride;
  17640. }
  17641. return this._animationPropertiesOverride;
  17642. },
  17643. set: function (value) {
  17644. this._animationPropertiesOverride = value;
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. /**
  17650. * Gets a string idenfifying the name of the class
  17651. * @returns "Node" string
  17652. */
  17653. Node.prototype.getClassName = function () {
  17654. return "Node";
  17655. };
  17656. Object.defineProperty(Node.prototype, "onDispose", {
  17657. /**
  17658. * Sets a callback that will be raised when the node will be disposed
  17659. */
  17660. set: function (callback) {
  17661. if (this._onDisposeObserver) {
  17662. this.onDisposeObservable.remove(this._onDisposeObserver);
  17663. }
  17664. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17665. },
  17666. enumerable: true,
  17667. configurable: true
  17668. });
  17669. /**
  17670. * Gets the scene of the node
  17671. * @returns a {BABYLON.Scene}
  17672. */
  17673. Node.prototype.getScene = function () {
  17674. return this._scene;
  17675. };
  17676. /**
  17677. * Gets the engine of the node
  17678. * @returns a {BABYLON.Engine}
  17679. */
  17680. Node.prototype.getEngine = function () {
  17681. return this._scene.getEngine();
  17682. };
  17683. /**
  17684. * Attach a behavior to the node
  17685. * @see http://doc.babylonjs.com/features/behaviour
  17686. * @param behavior defines the behavior to attach
  17687. * @returns the current Node
  17688. */
  17689. Node.prototype.addBehavior = function (behavior) {
  17690. var _this = this;
  17691. var index = this._behaviors.indexOf(behavior);
  17692. if (index !== -1) {
  17693. return this;
  17694. }
  17695. behavior.init();
  17696. if (this._scene.isLoading) {
  17697. // We defer the attach when the scene will be loaded
  17698. this._scene.onDataLoadedObservable.addOnce(function () {
  17699. behavior.attach(_this);
  17700. });
  17701. }
  17702. else {
  17703. behavior.attach(this);
  17704. }
  17705. this._behaviors.push(behavior);
  17706. return this;
  17707. };
  17708. /**
  17709. * Remove an attached behavior
  17710. * @see http://doc.babylonjs.com/features/behaviour
  17711. * @param behavior defines the behavior to attach
  17712. * @returns the current Node
  17713. */
  17714. Node.prototype.removeBehavior = function (behavior) {
  17715. var index = this._behaviors.indexOf(behavior);
  17716. if (index === -1) {
  17717. return this;
  17718. }
  17719. this._behaviors[index].detach();
  17720. this._behaviors.splice(index, 1);
  17721. return this;
  17722. };
  17723. Object.defineProperty(Node.prototype, "behaviors", {
  17724. /**
  17725. * Gets the list of attached behaviors
  17726. * @see http://doc.babylonjs.com/features/behaviour
  17727. */
  17728. get: function () {
  17729. return this._behaviors;
  17730. },
  17731. enumerable: true,
  17732. configurable: true
  17733. });
  17734. /**
  17735. * Gets an attached behavior by name
  17736. * @param name defines the name of the behavior to look for
  17737. * @see http://doc.babylonjs.com/features/behaviour
  17738. * @returns null if behavior was not found else the requested behavior
  17739. */
  17740. Node.prototype.getBehaviorByName = function (name) {
  17741. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17742. var behavior = _a[_i];
  17743. if (behavior.name === name) {
  17744. return behavior;
  17745. }
  17746. }
  17747. return null;
  17748. };
  17749. /**
  17750. * Returns the world matrix of the node
  17751. * @returns a matrix containing the node's world matrix
  17752. */
  17753. Node.prototype.getWorldMatrix = function () {
  17754. return BABYLON.Matrix.Identity();
  17755. };
  17756. /** @hidden */
  17757. Node.prototype._getWorldMatrixDeterminant = function () {
  17758. return 1;
  17759. };
  17760. // override it in derived class if you add new variables to the cache
  17761. // and call the parent class method
  17762. /** @hidden */
  17763. Node.prototype._initCache = function () {
  17764. this._cache = {};
  17765. this._cache.parent = undefined;
  17766. };
  17767. /** @hidden */
  17768. Node.prototype.updateCache = function (force) {
  17769. if (!force && this.isSynchronized())
  17770. return;
  17771. this._cache.parent = this.parent;
  17772. this._updateCache();
  17773. };
  17774. // override it in derived class if you add new variables to the cache
  17775. // and call the parent class method if !ignoreParentClass
  17776. /** @hidden */
  17777. Node.prototype._updateCache = function (ignoreParentClass) {
  17778. };
  17779. // override it in derived class if you add new variables to the cache
  17780. /** @hidden */
  17781. Node.prototype._isSynchronized = function () {
  17782. return true;
  17783. };
  17784. /** @hidden */
  17785. Node.prototype._markSyncedWithParent = function () {
  17786. if (this.parent) {
  17787. this._parentRenderId = this.parent._childRenderId;
  17788. }
  17789. };
  17790. /** @hidden */
  17791. Node.prototype.isSynchronizedWithParent = function () {
  17792. if (!this.parent) {
  17793. return true;
  17794. }
  17795. if (this._parentRenderId !== this.parent._childRenderId) {
  17796. return false;
  17797. }
  17798. return this.parent.isSynchronized();
  17799. };
  17800. /** @hidden */
  17801. Node.prototype.isSynchronized = function (updateCache) {
  17802. var check = this.hasNewParent();
  17803. check = check || !this.isSynchronizedWithParent();
  17804. check = check || !this._isSynchronized();
  17805. if (updateCache)
  17806. this.updateCache(true);
  17807. return !check;
  17808. };
  17809. /** @hidden */
  17810. Node.prototype.hasNewParent = function (update) {
  17811. if (this._cache.parent === this.parent)
  17812. return false;
  17813. if (update)
  17814. this._cache.parent = this.parent;
  17815. return true;
  17816. };
  17817. /**
  17818. * Is this node ready to be used/rendered
  17819. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17820. * @return true if the node is ready
  17821. */
  17822. Node.prototype.isReady = function (completeCheck) {
  17823. if (completeCheck === void 0) { completeCheck = false; }
  17824. return this._isReady;
  17825. };
  17826. /**
  17827. * Is this node enabled?
  17828. * 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
  17829. * @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
  17830. * @return whether this node (and its parent) is enabled
  17831. */
  17832. Node.prototype.isEnabled = function (checkAncestors) {
  17833. if (checkAncestors === void 0) { checkAncestors = true; }
  17834. if (checkAncestors === false) {
  17835. return this._isEnabled;
  17836. }
  17837. if (this._isEnabled === false) {
  17838. return false;
  17839. }
  17840. if (this.parent !== undefined && this.parent !== null) {
  17841. return this.parent.isEnabled(checkAncestors);
  17842. }
  17843. return true;
  17844. };
  17845. /**
  17846. * Set the enabled state of this node
  17847. * @param value defines the new enabled state
  17848. */
  17849. Node.prototype.setEnabled = function (value) {
  17850. this._isEnabled = value;
  17851. };
  17852. /**
  17853. * Is this node a descendant of the given node?
  17854. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17855. * @param ancestor defines the parent node to inspect
  17856. * @returns a boolean indicating if this node is a descendant of the given node
  17857. */
  17858. Node.prototype.isDescendantOf = function (ancestor) {
  17859. if (this.parent) {
  17860. if (this.parent === ancestor) {
  17861. return true;
  17862. }
  17863. return this.parent.isDescendantOf(ancestor);
  17864. }
  17865. return false;
  17866. };
  17867. /** @hidden */
  17868. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17869. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17870. if (!this._children) {
  17871. return;
  17872. }
  17873. for (var index = 0; index < this._children.length; index++) {
  17874. var item = this._children[index];
  17875. if (!predicate || predicate(item)) {
  17876. results.push(item);
  17877. }
  17878. if (!directDescendantsOnly) {
  17879. item._getDescendants(results, false, predicate);
  17880. }
  17881. }
  17882. };
  17883. /**
  17884. * Will return all nodes that have this node as ascendant
  17885. * @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
  17886. * @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
  17887. * @return all children nodes of all types
  17888. */
  17889. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17890. var results = new Array();
  17891. this._getDescendants(results, directDescendantsOnly, predicate);
  17892. return results;
  17893. };
  17894. /**
  17895. * Get all child-meshes of this node
  17896. * @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
  17897. * @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
  17898. * @returns an array of {BABYLON.AbstractMesh}
  17899. */
  17900. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17901. var results = [];
  17902. this._getDescendants(results, directDescendantsOnly, function (node) {
  17903. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17904. });
  17905. return results;
  17906. };
  17907. /**
  17908. * Get all child-transformNodes of this node
  17909. * @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
  17910. * @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
  17911. * @returns an array of {BABYLON.TransformNode}
  17912. */
  17913. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17914. var results = [];
  17915. this._getDescendants(results, directDescendantsOnly, function (node) {
  17916. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17917. });
  17918. return results;
  17919. };
  17920. /**
  17921. * Get all direct children of this node
  17922. * @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
  17923. * @returns an array of {BABYLON.Node}
  17924. */
  17925. Node.prototype.getChildren = function (predicate) {
  17926. return this.getDescendants(true, predicate);
  17927. };
  17928. /** @hidden */
  17929. Node.prototype._setReady = function (state) {
  17930. if (state === this._isReady) {
  17931. return;
  17932. }
  17933. if (!state) {
  17934. this._isReady = false;
  17935. return;
  17936. }
  17937. if (this.onReady) {
  17938. this.onReady(this);
  17939. }
  17940. this._isReady = true;
  17941. };
  17942. /**
  17943. * Get an animation by name
  17944. * @param name defines the name of the animation to look for
  17945. * @returns null if not found else the requested animation
  17946. */
  17947. Node.prototype.getAnimationByName = function (name) {
  17948. for (var i = 0; i < this.animations.length; i++) {
  17949. var animation = this.animations[i];
  17950. if (animation.name === name) {
  17951. return animation;
  17952. }
  17953. }
  17954. return null;
  17955. };
  17956. /**
  17957. * Creates an animation range for this node
  17958. * @param name defines the name of the range
  17959. * @param from defines the starting key
  17960. * @param to defines the end key
  17961. */
  17962. Node.prototype.createAnimationRange = function (name, from, to) {
  17963. // check name not already in use
  17964. if (!this._ranges[name]) {
  17965. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17966. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17967. if (this.animations[i]) {
  17968. this.animations[i].createRange(name, from, to);
  17969. }
  17970. }
  17971. }
  17972. };
  17973. /**
  17974. * Delete a specific animation range
  17975. * @param name defines the name of the range to delete
  17976. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17977. */
  17978. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17979. if (deleteFrames === void 0) { deleteFrames = true; }
  17980. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17981. if (this.animations[i]) {
  17982. this.animations[i].deleteRange(name, deleteFrames);
  17983. }
  17984. }
  17985. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17986. };
  17987. /**
  17988. * Get an animation range by name
  17989. * @param name defines the name of the animation range to look for
  17990. * @returns null if not found else the requested animation range
  17991. */
  17992. Node.prototype.getAnimationRange = function (name) {
  17993. return this._ranges[name];
  17994. };
  17995. /**
  17996. * Will start the animation sequence
  17997. * @param name defines the range frames for animation sequence
  17998. * @param loop defines if the animation should loop (false by default)
  17999. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18000. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18001. * @returns the object created for this animation. If range does not exist, it will return null
  18002. */
  18003. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18004. var range = this.getAnimationRange(name);
  18005. if (!range) {
  18006. return null;
  18007. }
  18008. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18009. };
  18010. /**
  18011. * Serialize animation ranges into a JSON compatible object
  18012. * @returns serialization object
  18013. */
  18014. Node.prototype.serializeAnimationRanges = function () {
  18015. var serializationRanges = [];
  18016. for (var name in this._ranges) {
  18017. var localRange = this._ranges[name];
  18018. if (!localRange) {
  18019. continue;
  18020. }
  18021. var range = {};
  18022. range.name = name;
  18023. range.from = localRange.from;
  18024. range.to = localRange.to;
  18025. serializationRanges.push(range);
  18026. }
  18027. return serializationRanges;
  18028. };
  18029. /**
  18030. * Computes the world matrix of the node
  18031. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18032. * @returns the world matrix
  18033. */
  18034. Node.prototype.computeWorldMatrix = function (force) {
  18035. return BABYLON.Matrix.Identity();
  18036. };
  18037. /**
  18038. * Releases resources associated with this node.
  18039. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18040. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18041. */
  18042. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18043. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18044. if (!doNotRecurse) {
  18045. var nodes = this.getDescendants(true);
  18046. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18047. var node = nodes_1[_i];
  18048. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18049. }
  18050. }
  18051. else {
  18052. var transformNodes = this.getChildTransformNodes(true);
  18053. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18054. var transformNode = transformNodes_1[_a];
  18055. transformNode.parent = null;
  18056. transformNode.computeWorldMatrix(true);
  18057. }
  18058. }
  18059. this.parent = null;
  18060. // Callback
  18061. this.onDisposeObservable.notifyObservers(this);
  18062. this.onDisposeObservable.clear();
  18063. // Behaviors
  18064. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18065. var behavior = _c[_b];
  18066. behavior.detach();
  18067. }
  18068. this._behaviors = [];
  18069. this._isDisposed = true;
  18070. };
  18071. /**
  18072. * Parse animation range data from a serialization object and store them into a given node
  18073. * @param node defines where to store the animation ranges
  18074. * @param parsedNode defines the serialization object to read data from
  18075. * @param scene defines the hosting scene
  18076. */
  18077. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18078. if (parsedNode.ranges) {
  18079. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18080. var data = parsedNode.ranges[index];
  18081. node.createAnimationRange(data.name, data.from, data.to);
  18082. }
  18083. }
  18084. };
  18085. __decorate([
  18086. BABYLON.serialize()
  18087. ], Node.prototype, "name", void 0);
  18088. __decorate([
  18089. BABYLON.serialize()
  18090. ], Node.prototype, "id", void 0);
  18091. __decorate([
  18092. BABYLON.serialize()
  18093. ], Node.prototype, "uniqueId", void 0);
  18094. __decorate([
  18095. BABYLON.serialize()
  18096. ], Node.prototype, "state", void 0);
  18097. __decorate([
  18098. BABYLON.serialize()
  18099. ], Node.prototype, "metadata", void 0);
  18100. return Node;
  18101. }());
  18102. BABYLON.Node = Node;
  18103. })(BABYLON || (BABYLON = {}));
  18104. //# sourceMappingURL=babylon.node.js.map
  18105. var BABYLON;
  18106. (function (BABYLON) {
  18107. var BoundingSphere = /** @class */ (function () {
  18108. /**
  18109. * Creates a new bounding sphere
  18110. * @param min defines the minimum vector (in local space)
  18111. * @param max defines the maximum vector (in local space)
  18112. */
  18113. function BoundingSphere(min, max) {
  18114. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18115. this.reConstruct(min, max);
  18116. }
  18117. /**
  18118. * Recreates the entire bounding sphere from scratch
  18119. * @param min defines the new minimum vector (in local space)
  18120. * @param max defines the new maximum vector (in local space)
  18121. */
  18122. BoundingSphere.prototype.reConstruct = function (min, max) {
  18123. this.minimum = min.clone();
  18124. this.maximum = max.clone();
  18125. var distance = BABYLON.Vector3.Distance(min, max);
  18126. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18127. this.radius = distance * 0.5;
  18128. this.centerWorld = BABYLON.Vector3.Zero();
  18129. this._update(BABYLON.Matrix.Identity());
  18130. };
  18131. // Methods
  18132. BoundingSphere.prototype._update = function (world) {
  18133. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18134. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18135. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18136. };
  18137. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18138. for (var i = 0; i < 6; i++) {
  18139. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18140. return false;
  18141. }
  18142. return true;
  18143. };
  18144. BoundingSphere.prototype.intersectsPoint = function (point) {
  18145. var x = this.centerWorld.x - point.x;
  18146. var y = this.centerWorld.y - point.y;
  18147. var z = this.centerWorld.z - point.z;
  18148. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18149. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18150. return false;
  18151. return true;
  18152. };
  18153. // Statics
  18154. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18155. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18156. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18157. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18158. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18159. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18160. return false;
  18161. return true;
  18162. };
  18163. return BoundingSphere;
  18164. }());
  18165. BABYLON.BoundingSphere = BoundingSphere;
  18166. })(BABYLON || (BABYLON = {}));
  18167. //# sourceMappingURL=babylon.boundingSphere.js.map
  18168. var BABYLON;
  18169. (function (BABYLON) {
  18170. var BoundingBox = /** @class */ (function () {
  18171. /**
  18172. * Creates a new bounding box
  18173. * @param min defines the minimum vector (in local space)
  18174. * @param max defines the maximum vector (in local space)
  18175. */
  18176. function BoundingBox(min, max) {
  18177. this.vectorsWorld = new Array();
  18178. this.reConstruct(min, max);
  18179. }
  18180. // Methods
  18181. /**
  18182. * Recreates the entire bounding box from scratch
  18183. * @param min defines the new minimum vector (in local space)
  18184. * @param max defines the new maximum vector (in local space)
  18185. */
  18186. BoundingBox.prototype.reConstruct = function (min, max) {
  18187. this.minimum = min.clone();
  18188. this.maximum = max.clone();
  18189. // Bounding vectors
  18190. this.vectors = new Array();
  18191. this.vectors.push(this.minimum.clone());
  18192. this.vectors.push(this.maximum.clone());
  18193. this.vectors.push(this.minimum.clone());
  18194. this.vectors[2].x = this.maximum.x;
  18195. this.vectors.push(this.minimum.clone());
  18196. this.vectors[3].y = this.maximum.y;
  18197. this.vectors.push(this.minimum.clone());
  18198. this.vectors[4].z = this.maximum.z;
  18199. this.vectors.push(this.maximum.clone());
  18200. this.vectors[5].z = this.minimum.z;
  18201. this.vectors.push(this.maximum.clone());
  18202. this.vectors[6].x = this.minimum.x;
  18203. this.vectors.push(this.maximum.clone());
  18204. this.vectors[7].y = this.minimum.y;
  18205. // OBB
  18206. this.center = this.maximum.add(this.minimum).scale(0.5);
  18207. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18208. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18209. // World
  18210. for (var index = 0; index < this.vectors.length; index++) {
  18211. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18212. }
  18213. this.minimumWorld = BABYLON.Vector3.Zero();
  18214. this.maximumWorld = BABYLON.Vector3.Zero();
  18215. this.centerWorld = BABYLON.Vector3.Zero();
  18216. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18217. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18218. };
  18219. BoundingBox.prototype.getWorldMatrix = function () {
  18220. return this._worldMatrix;
  18221. };
  18222. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18223. this._worldMatrix.copyFrom(matrix);
  18224. return this;
  18225. };
  18226. BoundingBox.prototype._update = function (world) {
  18227. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18228. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18229. for (var index = 0; index < this.vectors.length; index++) {
  18230. var v = this.vectorsWorld[index];
  18231. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18232. if (v.x < this.minimumWorld.x)
  18233. this.minimumWorld.x = v.x;
  18234. if (v.y < this.minimumWorld.y)
  18235. this.minimumWorld.y = v.y;
  18236. if (v.z < this.minimumWorld.z)
  18237. this.minimumWorld.z = v.z;
  18238. if (v.x > this.maximumWorld.x)
  18239. this.maximumWorld.x = v.x;
  18240. if (v.y > this.maximumWorld.y)
  18241. this.maximumWorld.y = v.y;
  18242. if (v.z > this.maximumWorld.z)
  18243. this.maximumWorld.z = v.z;
  18244. }
  18245. // Extend
  18246. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18247. this.extendSizeWorld.scaleInPlace(0.5);
  18248. // OBB
  18249. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18250. this.centerWorld.scaleInPlace(0.5);
  18251. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18252. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18253. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18254. this._worldMatrix = world;
  18255. };
  18256. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18257. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18258. };
  18259. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18260. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18261. };
  18262. BoundingBox.prototype.intersectsPoint = function (point) {
  18263. var delta = -BABYLON.Epsilon;
  18264. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18265. return false;
  18266. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18267. return false;
  18268. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18269. return false;
  18270. return true;
  18271. };
  18272. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18273. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18274. };
  18275. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18276. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18277. return false;
  18278. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18279. return false;
  18280. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18281. return false;
  18282. return true;
  18283. };
  18284. // Statics
  18285. BoundingBox.Intersects = function (box0, box1) {
  18286. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18287. return false;
  18288. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18289. return false;
  18290. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18291. return false;
  18292. return true;
  18293. };
  18294. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18295. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18296. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18297. return (num <= (sphereRadius * sphereRadius));
  18298. };
  18299. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18300. for (var p = 0; p < 6; p++) {
  18301. for (var i = 0; i < 8; i++) {
  18302. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18303. return false;
  18304. }
  18305. }
  18306. }
  18307. return true;
  18308. };
  18309. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18310. for (var p = 0; p < 6; p++) {
  18311. var inCount = 8;
  18312. for (var i = 0; i < 8; i++) {
  18313. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18314. --inCount;
  18315. }
  18316. else {
  18317. break;
  18318. }
  18319. }
  18320. if (inCount === 0)
  18321. return false;
  18322. }
  18323. return true;
  18324. };
  18325. return BoundingBox;
  18326. }());
  18327. BABYLON.BoundingBox = BoundingBox;
  18328. })(BABYLON || (BABYLON = {}));
  18329. //# sourceMappingURL=babylon.boundingBox.js.map
  18330. var BABYLON;
  18331. (function (BABYLON) {
  18332. var computeBoxExtents = function (axis, box) {
  18333. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18334. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18335. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18336. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18337. var r = r0 + r1 + r2;
  18338. return {
  18339. min: p - r,
  18340. max: p + r
  18341. };
  18342. };
  18343. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18344. var axisOverlap = function (axis, box0, box1) {
  18345. var result0 = computeBoxExtents(axis, box0);
  18346. var result1 = computeBoxExtents(axis, box1);
  18347. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18348. };
  18349. var BoundingInfo = /** @class */ (function () {
  18350. function BoundingInfo(minimum, maximum) {
  18351. this.minimum = minimum;
  18352. this.maximum = maximum;
  18353. this._isLocked = false;
  18354. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18355. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18356. }
  18357. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18358. get: function () {
  18359. return this._isLocked;
  18360. },
  18361. set: function (value) {
  18362. this._isLocked = value;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. // Methods
  18368. BoundingInfo.prototype.update = function (world) {
  18369. if (this._isLocked) {
  18370. return;
  18371. }
  18372. this.boundingBox._update(world);
  18373. this.boundingSphere._update(world);
  18374. };
  18375. /**
  18376. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18377. * @param center New center of the bounding info
  18378. * @param extend New extend of the bounding info
  18379. */
  18380. BoundingInfo.prototype.centerOn = function (center, extend) {
  18381. this.minimum = center.subtract(extend);
  18382. this.maximum = center.add(extend);
  18383. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18384. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18385. return this;
  18386. };
  18387. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18388. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18389. return false;
  18390. return this.boundingBox.isInFrustum(frustumPlanes);
  18391. };
  18392. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18393. /**
  18394. * Gets the world distance between the min and max points of the bounding box
  18395. */
  18396. get: function () {
  18397. var boundingBox = this.boundingBox;
  18398. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18399. return size.length();
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18405. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18406. };
  18407. BoundingInfo.prototype._checkCollision = function (collider) {
  18408. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18409. };
  18410. BoundingInfo.prototype.intersectsPoint = function (point) {
  18411. if (!this.boundingSphere.centerWorld) {
  18412. return false;
  18413. }
  18414. if (!this.boundingSphere.intersectsPoint(point)) {
  18415. return false;
  18416. }
  18417. if (!this.boundingBox.intersectsPoint(point)) {
  18418. return false;
  18419. }
  18420. return true;
  18421. };
  18422. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18423. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18424. return false;
  18425. }
  18426. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18427. return false;
  18428. }
  18429. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18430. return false;
  18431. }
  18432. if (!precise) {
  18433. return true;
  18434. }
  18435. var box0 = this.boundingBox;
  18436. var box1 = boundingInfo.boundingBox;
  18437. if (!axisOverlap(box0.directions[0], box0, box1))
  18438. return false;
  18439. if (!axisOverlap(box0.directions[1], box0, box1))
  18440. return false;
  18441. if (!axisOverlap(box0.directions[2], box0, box1))
  18442. return false;
  18443. if (!axisOverlap(box1.directions[0], box0, box1))
  18444. return false;
  18445. if (!axisOverlap(box1.directions[1], box0, box1))
  18446. return false;
  18447. if (!axisOverlap(box1.directions[2], box0, box1))
  18448. return false;
  18449. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18450. return false;
  18451. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18452. return false;
  18453. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18454. return false;
  18455. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18456. return false;
  18457. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18458. return false;
  18459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18460. return false;
  18461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18462. return false;
  18463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18464. return false;
  18465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18466. return false;
  18467. return true;
  18468. };
  18469. return BoundingInfo;
  18470. }());
  18471. BABYLON.BoundingInfo = BoundingInfo;
  18472. })(BABYLON || (BABYLON = {}));
  18473. //# sourceMappingURL=babylon.boundingInfo.js.map
  18474. var BABYLON;
  18475. (function (BABYLON) {
  18476. var TransformNode = /** @class */ (function (_super) {
  18477. __extends(TransformNode, _super);
  18478. function TransformNode(name, scene, isPure) {
  18479. if (scene === void 0) { scene = null; }
  18480. if (isPure === void 0) { isPure = true; }
  18481. var _this = _super.call(this, name, scene) || this;
  18482. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18483. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18484. _this._up = new BABYLON.Vector3(0, 1, 0);
  18485. _this._right = new BABYLON.Vector3(1, 0, 0);
  18486. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18487. // Properties
  18488. _this._rotation = BABYLON.Vector3.Zero();
  18489. _this._scaling = BABYLON.Vector3.One();
  18490. _this._isDirty = false;
  18491. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18492. _this.scalingDeterminant = 1;
  18493. _this.infiniteDistance = false;
  18494. /**
  18495. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18496. * By default the system will update normals to compensate
  18497. */
  18498. _this.ignoreNonUniformScaling = false;
  18499. _this.position = BABYLON.Vector3.Zero();
  18500. _this._localWorld = BABYLON.Matrix.Zero();
  18501. _this._worldMatrix = BABYLON.Matrix.Zero();
  18502. _this._worldMatrixDeterminant = 0;
  18503. _this._absolutePosition = BABYLON.Vector3.Zero();
  18504. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18505. _this._postMultiplyPivotMatrix = false;
  18506. _this._isWorldMatrixFrozen = false;
  18507. /**
  18508. * An event triggered after the world matrix is updated
  18509. */
  18510. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18511. _this._nonUniformScaling = false;
  18512. if (isPure) {
  18513. _this.getScene().addTransformNode(_this);
  18514. }
  18515. return _this;
  18516. }
  18517. /**
  18518. * Gets a string idenfifying the name of the class
  18519. * @returns "TransformNode" string
  18520. */
  18521. TransformNode.prototype.getClassName = function () {
  18522. return "TransformNode";
  18523. };
  18524. Object.defineProperty(TransformNode.prototype, "rotation", {
  18525. /**
  18526. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18527. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18528. * Default : (0.0, 0.0, 0.0)
  18529. */
  18530. get: function () {
  18531. return this._rotation;
  18532. },
  18533. set: function (newRotation) {
  18534. this._rotation = newRotation;
  18535. },
  18536. enumerable: true,
  18537. configurable: true
  18538. });
  18539. Object.defineProperty(TransformNode.prototype, "scaling", {
  18540. /**
  18541. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18542. * Default : (1.0, 1.0, 1.0)
  18543. */
  18544. get: function () {
  18545. return this._scaling;
  18546. },
  18547. /**
  18548. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18549. * Default : (1.0, 1.0, 1.0)
  18550. */
  18551. set: function (newScaling) {
  18552. this._scaling = newScaling;
  18553. },
  18554. enumerable: true,
  18555. configurable: true
  18556. });
  18557. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18558. /**
  18559. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18560. * It's null by default.
  18561. * 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)
  18562. */
  18563. get: function () {
  18564. return this._rotationQuaternion;
  18565. },
  18566. set: function (quaternion) {
  18567. this._rotationQuaternion = quaternion;
  18568. //reset the rotation vector.
  18569. if (quaternion && this.rotation.length()) {
  18570. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18571. }
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Object.defineProperty(TransformNode.prototype, "forward", {
  18577. /**
  18578. * The forward direction of that transform in world space.
  18579. */
  18580. get: function () {
  18581. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Object.defineProperty(TransformNode.prototype, "up", {
  18587. /**
  18588. * The up direction of that transform in world space.
  18589. */
  18590. get: function () {
  18591. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. Object.defineProperty(TransformNode.prototype, "right", {
  18597. /**
  18598. * The right direction of that transform in world space.
  18599. */
  18600. get: function () {
  18601. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. /**
  18607. * Returns the latest update of the World matrix
  18608. * Returns a Matrix.
  18609. */
  18610. TransformNode.prototype.getWorldMatrix = function () {
  18611. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18612. this.computeWorldMatrix();
  18613. }
  18614. return this._worldMatrix;
  18615. };
  18616. /** @hidden */
  18617. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18618. return this._worldMatrixDeterminant;
  18619. };
  18620. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18621. /**
  18622. * Returns directly the latest state of the mesh World matrix.
  18623. * A Matrix is returned.
  18624. */
  18625. get: function () {
  18626. return this._worldMatrix;
  18627. },
  18628. enumerable: true,
  18629. configurable: true
  18630. });
  18631. /**
  18632. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18633. * Returns the TransformNode.
  18634. */
  18635. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18636. this._poseMatrix.copyFrom(matrix);
  18637. return this;
  18638. };
  18639. /**
  18640. * Returns the mesh Pose matrix.
  18641. * Returned object : Matrix
  18642. */
  18643. TransformNode.prototype.getPoseMatrix = function () {
  18644. return this._poseMatrix;
  18645. };
  18646. TransformNode.prototype._isSynchronized = function () {
  18647. if (this._isDirty) {
  18648. return false;
  18649. }
  18650. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18651. return false;
  18652. if (this._cache.pivotMatrixUpdated) {
  18653. return false;
  18654. }
  18655. if (this.infiniteDistance) {
  18656. return false;
  18657. }
  18658. if (!this._cache.position.equals(this.position))
  18659. return false;
  18660. if (this.rotationQuaternion) {
  18661. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18662. return false;
  18663. }
  18664. if (!this._cache.rotation.equals(this.rotation))
  18665. return false;
  18666. if (!this._cache.scaling.equals(this.scaling))
  18667. return false;
  18668. return true;
  18669. };
  18670. TransformNode.prototype._initCache = function () {
  18671. _super.prototype._initCache.call(this);
  18672. this._cache.localMatrixUpdated = false;
  18673. this._cache.position = BABYLON.Vector3.Zero();
  18674. this._cache.scaling = BABYLON.Vector3.Zero();
  18675. this._cache.rotation = BABYLON.Vector3.Zero();
  18676. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18677. this._cache.billboardMode = -1;
  18678. };
  18679. TransformNode.prototype.markAsDirty = function (property) {
  18680. if (property === "rotation") {
  18681. this.rotationQuaternion = null;
  18682. }
  18683. this._currentRenderId = Number.MAX_VALUE;
  18684. this._isDirty = true;
  18685. return this;
  18686. };
  18687. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18688. /**
  18689. * Returns the current mesh absolute position.
  18690. * Retuns a Vector3.
  18691. */
  18692. get: function () {
  18693. return this._absolutePosition;
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. /**
  18699. * Sets a new matrix to apply before all other transformation
  18700. * @param matrix defines the transform matrix
  18701. * @returns the current TransformNode
  18702. */
  18703. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18704. return this.setPivotMatrix(matrix, false);
  18705. };
  18706. /**
  18707. * Sets a new pivot matrix to the current node
  18708. * @param matrix defines the new pivot matrix to use
  18709. * @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
  18710. * @returns the current TransformNode
  18711. */
  18712. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18713. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18714. this._pivotMatrix = matrix.clone();
  18715. this._cache.pivotMatrixUpdated = true;
  18716. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18717. if (this._postMultiplyPivotMatrix) {
  18718. if (!this._pivotMatrixInverse) {
  18719. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18720. }
  18721. else {
  18722. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18723. }
  18724. }
  18725. return this;
  18726. };
  18727. /**
  18728. * Returns the mesh pivot matrix.
  18729. * Default : Identity.
  18730. * A Matrix is returned.
  18731. */
  18732. TransformNode.prototype.getPivotMatrix = function () {
  18733. return this._pivotMatrix;
  18734. };
  18735. /**
  18736. * Prevents the World matrix to be computed any longer.
  18737. * Returns the TransformNode.
  18738. */
  18739. TransformNode.prototype.freezeWorldMatrix = function () {
  18740. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18741. this.computeWorldMatrix(true);
  18742. this._isWorldMatrixFrozen = true;
  18743. return this;
  18744. };
  18745. /**
  18746. * Allows back the World matrix computation.
  18747. * Returns the TransformNode.
  18748. */
  18749. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18750. this._isWorldMatrixFrozen = false;
  18751. this.computeWorldMatrix(true);
  18752. return this;
  18753. };
  18754. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18755. /**
  18756. * True if the World matrix has been frozen.
  18757. * Returns a boolean.
  18758. */
  18759. get: function () {
  18760. return this._isWorldMatrixFrozen;
  18761. },
  18762. enumerable: true,
  18763. configurable: true
  18764. });
  18765. /**
  18766. * Retuns the mesh absolute position in the World.
  18767. * Returns a Vector3.
  18768. */
  18769. TransformNode.prototype.getAbsolutePosition = function () {
  18770. this.computeWorldMatrix();
  18771. return this._absolutePosition;
  18772. };
  18773. /**
  18774. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18775. * Returns the TransformNode.
  18776. */
  18777. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18778. if (!absolutePosition) {
  18779. return this;
  18780. }
  18781. var absolutePositionX;
  18782. var absolutePositionY;
  18783. var absolutePositionZ;
  18784. if (absolutePosition.x === undefined) {
  18785. if (arguments.length < 3) {
  18786. return this;
  18787. }
  18788. absolutePositionX = arguments[0];
  18789. absolutePositionY = arguments[1];
  18790. absolutePositionZ = arguments[2];
  18791. }
  18792. else {
  18793. absolutePositionX = absolutePosition.x;
  18794. absolutePositionY = absolutePosition.y;
  18795. absolutePositionZ = absolutePosition.z;
  18796. }
  18797. if (this.parent) {
  18798. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18799. invertParentWorldMatrix.invert();
  18800. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18801. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18802. }
  18803. else {
  18804. this.position.x = absolutePositionX;
  18805. this.position.y = absolutePositionY;
  18806. this.position.z = absolutePositionZ;
  18807. }
  18808. return this;
  18809. };
  18810. /**
  18811. * Sets the mesh position in its local space.
  18812. * Returns the TransformNode.
  18813. */
  18814. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18815. this.computeWorldMatrix();
  18816. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18817. return this;
  18818. };
  18819. /**
  18820. * Returns the mesh position in the local space from the current World matrix values.
  18821. * Returns a new Vector3.
  18822. */
  18823. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18824. this.computeWorldMatrix();
  18825. var invLocalWorldMatrix = this._localWorld.clone();
  18826. invLocalWorldMatrix.invert();
  18827. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18828. };
  18829. /**
  18830. * Translates the mesh along the passed Vector3 in its local space.
  18831. * Returns the TransformNode.
  18832. */
  18833. TransformNode.prototype.locallyTranslate = function (vector3) {
  18834. this.computeWorldMatrix(true);
  18835. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18836. return this;
  18837. };
  18838. /**
  18839. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18840. * @param targetPoint the position (must be in same space as current mesh) to look at
  18841. * @param yawCor optional yaw (y-axis) correction in radians
  18842. * @param pitchCor optional pitch (x-axis) correction in radians
  18843. * @param rollCor optional roll (z-axis) correction in radians
  18844. * @param space the choosen space of the target
  18845. * @returns the TransformNode.
  18846. */
  18847. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18848. if (yawCor === void 0) { yawCor = 0; }
  18849. if (pitchCor === void 0) { pitchCor = 0; }
  18850. if (rollCor === void 0) { rollCor = 0; }
  18851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18852. var dv = TransformNode._lookAtVectorCache;
  18853. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18854. targetPoint.subtractToRef(pos, dv);
  18855. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18856. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18857. var pitch = Math.atan2(dv.y, len);
  18858. if (this.rotationQuaternion) {
  18859. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18860. }
  18861. else {
  18862. this.rotation.x = pitch + pitchCor;
  18863. this.rotation.y = yaw + yawCor;
  18864. this.rotation.z = rollCor;
  18865. }
  18866. return this;
  18867. };
  18868. /**
  18869. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18870. * This Vector3 is expressed in the World space.
  18871. */
  18872. TransformNode.prototype.getDirection = function (localAxis) {
  18873. var result = BABYLON.Vector3.Zero();
  18874. this.getDirectionToRef(localAxis, result);
  18875. return result;
  18876. };
  18877. /**
  18878. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18879. * localAxis is expressed in the mesh local space.
  18880. * result is computed in the Wordl space from the mesh World matrix.
  18881. * Returns the TransformNode.
  18882. */
  18883. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18884. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18885. return this;
  18886. };
  18887. /**
  18888. * Sets a new pivot point to the current node
  18889. * @param point defines the new pivot point to use
  18890. * @param space defines if the point is in world or local space (local by default)
  18891. * @returns the current TransformNode
  18892. */
  18893. TransformNode.prototype.setPivotPoint = function (point, space) {
  18894. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18895. if (this.getScene().getRenderId() == 0) {
  18896. this.computeWorldMatrix(true);
  18897. }
  18898. var wm = this.getWorldMatrix();
  18899. if (space == BABYLON.Space.WORLD) {
  18900. var tmat = BABYLON.Tmp.Matrix[0];
  18901. wm.invertToRef(tmat);
  18902. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18903. }
  18904. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18905. };
  18906. /**
  18907. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18908. */
  18909. TransformNode.prototype.getPivotPoint = function () {
  18910. var point = BABYLON.Vector3.Zero();
  18911. this.getPivotPointToRef(point);
  18912. return point;
  18913. };
  18914. /**
  18915. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18916. * Returns the TransformNode.
  18917. */
  18918. TransformNode.prototype.getPivotPointToRef = function (result) {
  18919. result.x = -this._pivotMatrix.m[12];
  18920. result.y = -this._pivotMatrix.m[13];
  18921. result.z = -this._pivotMatrix.m[14];
  18922. return this;
  18923. };
  18924. /**
  18925. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18926. */
  18927. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18928. var point = BABYLON.Vector3.Zero();
  18929. this.getAbsolutePivotPointToRef(point);
  18930. return point;
  18931. };
  18932. /**
  18933. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18934. * Returns the TransformNode.
  18935. */
  18936. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18937. result.x = this._pivotMatrix.m[12];
  18938. result.y = this._pivotMatrix.m[13];
  18939. result.z = this._pivotMatrix.m[14];
  18940. this.getPivotPointToRef(result);
  18941. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18942. return this;
  18943. };
  18944. /**
  18945. * Defines the passed node as the parent of the current node.
  18946. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18947. * Returns the TransformNode.
  18948. */
  18949. TransformNode.prototype.setParent = function (node) {
  18950. if (node === null) {
  18951. var rotation = BABYLON.Tmp.Quaternion[0];
  18952. var position = BABYLON.Tmp.Vector3[0];
  18953. var scale = BABYLON.Tmp.Vector3[1];
  18954. if (this.parent && this.parent.computeWorldMatrix) {
  18955. this.parent.computeWorldMatrix(true);
  18956. }
  18957. this.computeWorldMatrix(true);
  18958. this.getWorldMatrix().decompose(scale, rotation, position);
  18959. if (this.rotationQuaternion) {
  18960. this.rotationQuaternion.copyFrom(rotation);
  18961. }
  18962. else {
  18963. rotation.toEulerAnglesToRef(this.rotation);
  18964. }
  18965. this.scaling.x = scale.x;
  18966. this.scaling.y = scale.y;
  18967. this.scaling.z = scale.z;
  18968. this.position.x = position.x;
  18969. this.position.y = position.y;
  18970. this.position.z = position.z;
  18971. }
  18972. else {
  18973. var rotation = BABYLON.Tmp.Quaternion[0];
  18974. var position = BABYLON.Tmp.Vector3[0];
  18975. var scale = BABYLON.Tmp.Vector3[1];
  18976. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18977. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18978. this.computeWorldMatrix(true);
  18979. node.computeWorldMatrix(true);
  18980. node.getWorldMatrix().invertToRef(invParentMatrix);
  18981. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18982. diffMatrix.decompose(scale, rotation, position);
  18983. if (this.rotationQuaternion) {
  18984. this.rotationQuaternion.copyFrom(rotation);
  18985. }
  18986. else {
  18987. rotation.toEulerAnglesToRef(this.rotation);
  18988. }
  18989. this.position.x = position.x;
  18990. this.position.y = position.y;
  18991. this.position.z = position.z;
  18992. this.scaling.x = scale.x;
  18993. this.scaling.y = scale.y;
  18994. this.scaling.z = scale.z;
  18995. }
  18996. this.parent = node;
  18997. return this;
  18998. };
  18999. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19000. get: function () {
  19001. return this._nonUniformScaling;
  19002. },
  19003. enumerable: true,
  19004. configurable: true
  19005. });
  19006. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19007. if (this._nonUniformScaling === value) {
  19008. return false;
  19009. }
  19010. this._nonUniformScaling = value;
  19011. return true;
  19012. };
  19013. /**
  19014. * Attach the current TransformNode to another TransformNode associated with a bone
  19015. * @param bone Bone affecting the TransformNode
  19016. * @param affectedTransformNode TransformNode associated with the bone
  19017. */
  19018. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19019. this._transformToBoneReferal = affectedTransformNode;
  19020. this.parent = bone;
  19021. if (bone.getWorldMatrix().determinant() < 0) {
  19022. this.scalingDeterminant *= -1;
  19023. }
  19024. return this;
  19025. };
  19026. TransformNode.prototype.detachFromBone = function () {
  19027. if (!this.parent) {
  19028. return this;
  19029. }
  19030. if (this.parent.getWorldMatrix().determinant() < 0) {
  19031. this.scalingDeterminant *= -1;
  19032. }
  19033. this._transformToBoneReferal = null;
  19034. this.parent = null;
  19035. return this;
  19036. };
  19037. /**
  19038. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19039. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19040. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19041. * The passed axis is also normalized.
  19042. * Returns the TransformNode.
  19043. */
  19044. TransformNode.prototype.rotate = function (axis, amount, space) {
  19045. axis.normalize();
  19046. if (!this.rotationQuaternion) {
  19047. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19048. this.rotation = BABYLON.Vector3.Zero();
  19049. }
  19050. var rotationQuaternion;
  19051. if (!space || space === BABYLON.Space.LOCAL) {
  19052. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19053. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19054. }
  19055. else {
  19056. if (this.parent) {
  19057. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19058. invertParentWorldMatrix.invert();
  19059. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19060. }
  19061. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19062. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19063. }
  19064. return this;
  19065. };
  19066. /**
  19067. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19068. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19069. * The passed axis is also normalized.
  19070. * Returns the TransformNode.
  19071. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19072. */
  19073. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19074. axis.normalize();
  19075. if (!this.rotationQuaternion) {
  19076. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19077. this.rotation.copyFromFloats(0, 0, 0);
  19078. }
  19079. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19080. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19081. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19082. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19083. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19084. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19085. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19086. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19087. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19088. return this;
  19089. };
  19090. /**
  19091. * Translates the mesh along the axis vector for the passed distance in the given space.
  19092. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19093. * Returns the TransformNode.
  19094. */
  19095. TransformNode.prototype.translate = function (axis, distance, space) {
  19096. var displacementVector = axis.scale(distance);
  19097. if (!space || space === BABYLON.Space.LOCAL) {
  19098. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19099. this.setPositionWithLocalVector(tempV3);
  19100. }
  19101. else {
  19102. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19103. }
  19104. return this;
  19105. };
  19106. /**
  19107. * Adds a rotation step to the mesh current rotation.
  19108. * x, y, z are Euler angles expressed in radians.
  19109. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19110. * This means this rotation is made in the mesh local space only.
  19111. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19112. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19113. * ```javascript
  19114. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19115. * ```
  19116. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19117. * 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.
  19118. * Returns the TransformNode.
  19119. */
  19120. TransformNode.prototype.addRotation = function (x, y, z) {
  19121. var rotationQuaternion;
  19122. if (this.rotationQuaternion) {
  19123. rotationQuaternion = this.rotationQuaternion;
  19124. }
  19125. else {
  19126. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19127. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19128. }
  19129. var accumulation = BABYLON.Tmp.Quaternion[0];
  19130. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19131. rotationQuaternion.multiplyInPlace(accumulation);
  19132. if (!this.rotationQuaternion) {
  19133. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19134. }
  19135. return this;
  19136. };
  19137. /**
  19138. * Computes the mesh World matrix and returns it.
  19139. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19140. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19141. * If the parameter `force`is set to `true`, the actual computation is done.
  19142. * Returns the mesh World Matrix.
  19143. */
  19144. TransformNode.prototype.computeWorldMatrix = function (force) {
  19145. if (this._isWorldMatrixFrozen) {
  19146. return this._worldMatrix;
  19147. }
  19148. if (!force && this.isSynchronized(true)) {
  19149. this._currentRenderId = this.getScene().getRenderId();
  19150. return this._worldMatrix;
  19151. }
  19152. this._cache.position.copyFrom(this.position);
  19153. this._cache.scaling.copyFrom(this.scaling);
  19154. this._cache.pivotMatrixUpdated = false;
  19155. this._cache.billboardMode = this.billboardMode;
  19156. this._currentRenderId = this.getScene().getRenderId();
  19157. this._childRenderId = this.getScene().getRenderId();
  19158. this._isDirty = false;
  19159. // Scaling
  19160. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19161. // Rotation
  19162. //rotate, if quaternion is set and rotation was used
  19163. if (this.rotationQuaternion) {
  19164. var len = this.rotation.length();
  19165. if (len) {
  19166. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19167. this.rotation.copyFromFloats(0, 0, 0);
  19168. }
  19169. }
  19170. if (this.rotationQuaternion) {
  19171. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19172. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19173. }
  19174. else {
  19175. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19176. this._cache.rotation.copyFrom(this.rotation);
  19177. }
  19178. // Translation
  19179. var camera = this.getScene().activeCamera;
  19180. if (this.infiniteDistance && !this.parent && camera) {
  19181. var cameraWorldMatrix = camera.getWorldMatrix();
  19182. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19183. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19184. }
  19185. else {
  19186. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19187. }
  19188. // Composing transformations
  19189. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19190. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19191. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19192. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19193. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19194. // Need to decompose each rotation here
  19195. var currentPosition = BABYLON.Tmp.Vector3[3];
  19196. if (this.parent && this.parent.getWorldMatrix) {
  19197. if (this._transformToBoneReferal) {
  19198. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19199. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19200. }
  19201. else {
  19202. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19203. }
  19204. }
  19205. else {
  19206. currentPosition.copyFrom(this.position);
  19207. }
  19208. currentPosition.subtractInPlace(camera.globalPosition);
  19209. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19210. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19211. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19212. }
  19213. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19214. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19215. }
  19216. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19217. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19218. }
  19219. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19220. }
  19221. else {
  19222. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19223. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19224. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19225. }
  19226. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19227. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19228. }
  19229. // Local world
  19230. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19231. // Parent
  19232. if (this.parent && this.parent.getWorldMatrix) {
  19233. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19234. if (this._transformToBoneReferal) {
  19235. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19236. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19237. }
  19238. else {
  19239. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19240. }
  19241. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19242. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19243. this._worldMatrix.copyFrom(this._localWorld);
  19244. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19245. }
  19246. else {
  19247. if (this._transformToBoneReferal) {
  19248. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19249. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19250. }
  19251. else {
  19252. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19253. }
  19254. }
  19255. this._markSyncedWithParent();
  19256. }
  19257. else {
  19258. this._worldMatrix.copyFrom(this._localWorld);
  19259. }
  19260. // Post multiply inverse of pivotMatrix
  19261. if (this._postMultiplyPivotMatrix) {
  19262. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19263. }
  19264. // Normal matrix
  19265. if (!this.ignoreNonUniformScaling) {
  19266. if (this.scaling.isNonUniform) {
  19267. this._updateNonUniformScalingState(true);
  19268. }
  19269. else if (this.parent && this.parent._nonUniformScaling) {
  19270. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19271. }
  19272. else {
  19273. this._updateNonUniformScalingState(false);
  19274. }
  19275. }
  19276. else {
  19277. this._updateNonUniformScalingState(false);
  19278. }
  19279. this._afterComputeWorldMatrix();
  19280. // Absolute position
  19281. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19282. // Callbacks
  19283. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19284. if (!this._poseMatrix) {
  19285. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19286. }
  19287. // Cache the determinant
  19288. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19289. return this._worldMatrix;
  19290. };
  19291. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19292. };
  19293. /**
  19294. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19295. * @param func: callback function to add
  19296. *
  19297. * Returns the TransformNode.
  19298. */
  19299. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19300. this.onAfterWorldMatrixUpdateObservable.add(func);
  19301. return this;
  19302. };
  19303. /**
  19304. * Removes a registered callback function.
  19305. * Returns the TransformNode.
  19306. */
  19307. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19308. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19309. return this;
  19310. };
  19311. /**
  19312. * Clone the current transform node
  19313. * Returns the new transform node
  19314. * @param name Name of the new clone
  19315. * @param newParent New parent for the clone
  19316. * @param doNotCloneChildren Do not clone children hierarchy
  19317. */
  19318. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19319. var _this = this;
  19320. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19321. result.name = name;
  19322. result.id = name;
  19323. if (newParent) {
  19324. result.parent = newParent;
  19325. }
  19326. if (!doNotCloneChildren) {
  19327. // Children
  19328. var directDescendants = this.getDescendants(true);
  19329. for (var index = 0; index < directDescendants.length; index++) {
  19330. var child = directDescendants[index];
  19331. if (child.clone) {
  19332. child.clone(name + "." + child.name, result);
  19333. }
  19334. }
  19335. }
  19336. return result;
  19337. };
  19338. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19339. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19340. serializationObject.type = this.getClassName();
  19341. // Parent
  19342. if (this.parent) {
  19343. serializationObject.parentId = this.parent.id;
  19344. }
  19345. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19346. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19347. }
  19348. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19349. serializationObject.isEnabled = this.isEnabled();
  19350. // Parent
  19351. if (this.parent) {
  19352. serializationObject.parentId = this.parent.id;
  19353. }
  19354. return serializationObject;
  19355. };
  19356. // Statics
  19357. /**
  19358. * Returns a new TransformNode object parsed from the source provided.
  19359. * The parameter `parsedMesh` is the source.
  19360. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19361. */
  19362. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19363. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19364. if (BABYLON.Tags) {
  19365. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19366. }
  19367. if (parsedTransformNode.localMatrix) {
  19368. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19369. }
  19370. else if (parsedTransformNode.pivotMatrix) {
  19371. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19372. }
  19373. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19374. // Parent
  19375. if (parsedTransformNode.parentId) {
  19376. transformNode._waitingParentId = parsedTransformNode.parentId;
  19377. }
  19378. return transformNode;
  19379. };
  19380. /**
  19381. * Releases resources associated with this transform node.
  19382. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19383. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19384. */
  19385. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19386. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19387. // Animations
  19388. this.getScene().stopAnimation(this);
  19389. // Remove from scene
  19390. this.getScene().removeTransformNode(this);
  19391. this.onAfterWorldMatrixUpdateObservable.clear();
  19392. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19393. };
  19394. // Statics
  19395. TransformNode.BILLBOARDMODE_NONE = 0;
  19396. TransformNode.BILLBOARDMODE_X = 1;
  19397. TransformNode.BILLBOARDMODE_Y = 2;
  19398. TransformNode.BILLBOARDMODE_Z = 4;
  19399. TransformNode.BILLBOARDMODE_ALL = 7;
  19400. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19401. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19402. __decorate([
  19403. BABYLON.serializeAsVector3()
  19404. ], TransformNode.prototype, "_rotation", void 0);
  19405. __decorate([
  19406. BABYLON.serializeAsQuaternion()
  19407. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19408. __decorate([
  19409. BABYLON.serializeAsVector3()
  19410. ], TransformNode.prototype, "_scaling", void 0);
  19411. __decorate([
  19412. BABYLON.serialize()
  19413. ], TransformNode.prototype, "billboardMode", void 0);
  19414. __decorate([
  19415. BABYLON.serialize()
  19416. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19417. __decorate([
  19418. BABYLON.serialize()
  19419. ], TransformNode.prototype, "infiniteDistance", void 0);
  19420. __decorate([
  19421. BABYLON.serialize()
  19422. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19423. __decorate([
  19424. BABYLON.serializeAsVector3()
  19425. ], TransformNode.prototype, "position", void 0);
  19426. return TransformNode;
  19427. }(BABYLON.Node));
  19428. BABYLON.TransformNode = TransformNode;
  19429. })(BABYLON || (BABYLON = {}));
  19430. //# sourceMappingURL=babylon.transformNode.js.map
  19431. var BABYLON;
  19432. (function (BABYLON) {
  19433. /**
  19434. * Class used to store all common mesh properties
  19435. */
  19436. var AbstractMesh = /** @class */ (function (_super) {
  19437. __extends(AbstractMesh, _super);
  19438. // Constructor
  19439. /**
  19440. * Creates a new AbstractMesh
  19441. * @param name defines the name of the mesh
  19442. * @param scene defines the hosting scene
  19443. */
  19444. function AbstractMesh(name, scene) {
  19445. if (scene === void 0) { scene = null; }
  19446. var _this = _super.call(this, name, scene, false) || this;
  19447. _this._facetNb = 0; // facet number
  19448. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19449. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19450. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19451. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19452. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19453. _this._subDiv = {
  19454. max: 1,
  19455. X: 1,
  19456. Y: 1,
  19457. Z: 1
  19458. };
  19459. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19460. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19461. // Events
  19462. /**
  19463. * An event triggered when this mesh collides with another one
  19464. */
  19465. _this.onCollideObservable = new BABYLON.Observable();
  19466. /**
  19467. * An event triggered when the collision's position changes
  19468. */
  19469. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19470. /**
  19471. * An event triggered when material is changed
  19472. */
  19473. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19474. // Properties
  19475. /**
  19476. * Gets or sets the orientation for POV movement & rotation
  19477. */
  19478. _this.definedFacingForward = true;
  19479. /**
  19480. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19481. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19482. * * 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.
  19483. * @see http://doc.babylonjs.com/features/occlusionquery
  19484. */
  19485. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19486. /**
  19487. * 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:
  19488. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19489. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19490. * * 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.
  19491. * @see http://doc.babylonjs.com/features/occlusionquery
  19492. */
  19493. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19494. /**
  19495. * 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.
  19496. * The default value is -1 which means don't break the query and wait till the result
  19497. * @see http://doc.babylonjs.com/features/occlusionquery
  19498. */
  19499. _this.occlusionRetryCount = -1;
  19500. _this._occlusionInternalRetryCounter = 0;
  19501. _this._isOccluded = false;
  19502. _this._isOcclusionQueryInProgress = false;
  19503. _this._visibility = 1.0;
  19504. /** Gets or sets the alpha index used to sort transparent meshes
  19505. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19506. */
  19507. _this.alphaIndex = Number.MAX_VALUE;
  19508. /**
  19509. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19510. */
  19511. _this.isVisible = true;
  19512. /**
  19513. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19514. */
  19515. _this.isPickable = true;
  19516. /**
  19517. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19518. */
  19519. _this.showBoundingBox = false;
  19520. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19521. _this.showSubMeshesBoundingBox = false;
  19522. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19523. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19524. */
  19525. _this.isBlocker = false;
  19526. /**
  19527. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19528. */
  19529. _this.enablePointerMoveEvents = false;
  19530. /**
  19531. * Specifies the rendering group id for this mesh (0 by default)
  19532. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19533. */
  19534. _this.renderingGroupId = 0;
  19535. _this._receiveShadows = false;
  19536. /**
  19537. * Gets or sets a boolean indicating if the outline must be rendered as well
  19538. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19539. */
  19540. _this.renderOutline = false;
  19541. /** Defines color to use when rendering outline */
  19542. _this.outlineColor = BABYLON.Color3.Red();
  19543. /** Define width to use when rendering outline */
  19544. _this.outlineWidth = 0.02;
  19545. /**
  19546. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19547. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19548. */
  19549. _this.renderOverlay = false;
  19550. /** Defines color to use when rendering overlay */
  19551. _this.overlayColor = BABYLON.Color3.Red();
  19552. /** Defines alpha to use when rendering overlay */
  19553. _this.overlayAlpha = 0.5;
  19554. _this._hasVertexAlpha = false;
  19555. _this._useVertexColors = true;
  19556. _this._computeBonesUsingShaders = true;
  19557. _this._numBoneInfluencers = 4;
  19558. _this._applyFog = true;
  19559. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19560. _this.useOctreeForRenderingSelection = true;
  19561. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19562. _this.useOctreeForPicking = true;
  19563. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19564. _this.useOctreeForCollisions = true;
  19565. _this._layerMask = 0x0FFFFFFF;
  19566. /**
  19567. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19568. */
  19569. _this.alwaysSelectAsActiveMesh = false;
  19570. /**
  19571. * Gets or sets the current action manager
  19572. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19573. */
  19574. _this.actionManager = null;
  19575. /**
  19576. * Gets or sets impostor used for physic simulation
  19577. * @see http://doc.babylonjs.com/features/physics_engine
  19578. */
  19579. _this.physicsImpostor = null;
  19580. // Collisions
  19581. _this._checkCollisions = false;
  19582. _this._collisionMask = -1;
  19583. _this._collisionGroup = -1;
  19584. /**
  19585. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19586. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19587. */
  19588. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19589. /**
  19590. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19591. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19592. */
  19593. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19594. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19595. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19596. // Edges
  19597. /**
  19598. * Defines edge width used when edgesRenderer is enabled
  19599. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19600. */
  19601. _this.edgesWidth = 1;
  19602. /**
  19603. * Defines edge color used when edgesRenderer is enabled
  19604. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19605. */
  19606. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19607. // Cache
  19608. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19609. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19610. /** @hidden */
  19611. _this._renderId = 0;
  19612. /** @hidden */
  19613. _this._intersectionsInProgress = new Array();
  19614. /** @hidden */
  19615. _this._unIndexed = false;
  19616. /** @hidden */
  19617. _this._lightSources = new Array();
  19618. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19619. if (collidedMesh === void 0) { collidedMesh = null; }
  19620. //TODO move this to the collision coordinator!
  19621. if (_this.getScene().workerCollisions)
  19622. newPosition.multiplyInPlace(_this._collider._radius);
  19623. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19624. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19625. _this.position.addInPlace(_this._diffPositionForCollisions);
  19626. }
  19627. if (collidedMesh) {
  19628. _this.onCollideObservable.notifyObservers(collidedMesh);
  19629. }
  19630. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19631. };
  19632. _this.getScene().addMesh(_this);
  19633. _this._resyncLightSources();
  19634. return _this;
  19635. }
  19636. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19637. /**
  19638. * No billboard
  19639. */
  19640. get: function () {
  19641. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19647. /** Billboard on X axis */
  19648. get: function () {
  19649. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19650. },
  19651. enumerable: true,
  19652. configurable: true
  19653. });
  19654. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19655. /** Billboard on Y axis */
  19656. get: function () {
  19657. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19658. },
  19659. enumerable: true,
  19660. configurable: true
  19661. });
  19662. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19663. /** Billboard on Z axis */
  19664. get: function () {
  19665. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19666. },
  19667. enumerable: true,
  19668. configurable: true
  19669. });
  19670. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19671. /** Billboard on all axes */
  19672. get: function () {
  19673. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19674. },
  19675. enumerable: true,
  19676. configurable: true
  19677. });
  19678. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19679. /**
  19680. * Gets the number of facets in the mesh
  19681. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19682. */
  19683. get: function () {
  19684. return this._facetNb;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19690. /**
  19691. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19692. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19693. */
  19694. get: function () {
  19695. return this._partitioningSubdivisions;
  19696. },
  19697. set: function (nb) {
  19698. this._partitioningSubdivisions = nb;
  19699. },
  19700. enumerable: true,
  19701. configurable: true
  19702. });
  19703. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19704. /**
  19705. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19706. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19707. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19708. */
  19709. get: function () {
  19710. return this._partitioningBBoxRatio;
  19711. },
  19712. set: function (ratio) {
  19713. this._partitioningBBoxRatio = ratio;
  19714. },
  19715. enumerable: true,
  19716. configurable: true
  19717. });
  19718. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19719. /**
  19720. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19721. * Works only for updatable meshes.
  19722. * Doesn't work with multi-materials
  19723. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19724. */
  19725. get: function () {
  19726. return this._facetDepthSort;
  19727. },
  19728. set: function (sort) {
  19729. this._facetDepthSort = sort;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19735. /**
  19736. * The location (Vector3) where the facet depth sort must be computed from.
  19737. * By default, the active camera position.
  19738. * Used only when facet depth sort is enabled
  19739. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19740. */
  19741. get: function () {
  19742. return this._facetDepthSortFrom;
  19743. },
  19744. set: function (location) {
  19745. this._facetDepthSortFrom = location;
  19746. },
  19747. enumerable: true,
  19748. configurable: true
  19749. });
  19750. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19751. /**
  19752. * gets a boolean indicating if facetData is enabled
  19753. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19754. */
  19755. get: function () {
  19756. return this._facetDataEnabled;
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. /** @hidden */
  19762. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19763. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19764. return false;
  19765. }
  19766. this._markSubMeshesAsMiscDirty();
  19767. return true;
  19768. };
  19769. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19770. /** Set a function to call when this mesh collides with another one */
  19771. set: function (callback) {
  19772. if (this._onCollideObserver) {
  19773. this.onCollideObservable.remove(this._onCollideObserver);
  19774. }
  19775. this._onCollideObserver = this.onCollideObservable.add(callback);
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19781. /** Set a function to call when the collision's position changes */
  19782. set: function (callback) {
  19783. if (this._onCollisionPositionChangeObserver) {
  19784. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19785. }
  19786. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19792. /**
  19793. * 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
  19794. * @see http://doc.babylonjs.com/features/occlusionquery
  19795. */
  19796. get: function () {
  19797. return this._isOccluded;
  19798. },
  19799. set: function (value) {
  19800. this._isOccluded = value;
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19806. /**
  19807. * Flag to check the progress status of the query
  19808. * @see http://doc.babylonjs.com/features/occlusionquery
  19809. */
  19810. get: function () {
  19811. return this._isOcclusionQueryInProgress;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19817. /**
  19818. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19819. */
  19820. get: function () {
  19821. return this._visibility;
  19822. },
  19823. /**
  19824. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19825. */
  19826. set: function (value) {
  19827. if (this._visibility === value) {
  19828. return;
  19829. }
  19830. this._visibility = value;
  19831. this._markSubMeshesAsMiscDirty();
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(AbstractMesh.prototype, "material", {
  19837. /** Gets or sets current material */
  19838. get: function () {
  19839. return this._material;
  19840. },
  19841. set: function (value) {
  19842. if (this._material === value) {
  19843. return;
  19844. }
  19845. this._material = value;
  19846. if (this.onMaterialChangedObservable.hasObservers) {
  19847. this.onMaterialChangedObservable.notifyObservers(this);
  19848. }
  19849. if (!this.subMeshes) {
  19850. return;
  19851. }
  19852. this._unBindEffect();
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19858. /**
  19859. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19860. * @see http://doc.babylonjs.com/babylon101/shadows
  19861. */
  19862. get: function () {
  19863. return this._receiveShadows;
  19864. },
  19865. set: function (value) {
  19866. if (this._receiveShadows === value) {
  19867. return;
  19868. }
  19869. this._receiveShadows = value;
  19870. this._markSubMeshesAsLightDirty();
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19876. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19877. get: function () {
  19878. return this._hasVertexAlpha;
  19879. },
  19880. set: function (value) {
  19881. if (this._hasVertexAlpha === value) {
  19882. return;
  19883. }
  19884. this._hasVertexAlpha = value;
  19885. this._markSubMeshesAsAttributesDirty();
  19886. this._markSubMeshesAsMiscDirty();
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19892. /** 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) */
  19893. get: function () {
  19894. return this._useVertexColors;
  19895. },
  19896. set: function (value) {
  19897. if (this._useVertexColors === value) {
  19898. return;
  19899. }
  19900. this._useVertexColors = value;
  19901. this._markSubMeshesAsAttributesDirty();
  19902. },
  19903. enumerable: true,
  19904. configurable: true
  19905. });
  19906. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19907. /**
  19908. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19909. */
  19910. get: function () {
  19911. return this._computeBonesUsingShaders;
  19912. },
  19913. set: function (value) {
  19914. if (this._computeBonesUsingShaders === value) {
  19915. return;
  19916. }
  19917. this._computeBonesUsingShaders = value;
  19918. this._markSubMeshesAsAttributesDirty();
  19919. },
  19920. enumerable: true,
  19921. configurable: true
  19922. });
  19923. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19924. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19925. get: function () {
  19926. return this._numBoneInfluencers;
  19927. },
  19928. set: function (value) {
  19929. if (this._numBoneInfluencers === value) {
  19930. return;
  19931. }
  19932. this._numBoneInfluencers = value;
  19933. this._markSubMeshesAsAttributesDirty();
  19934. },
  19935. enumerable: true,
  19936. configurable: true
  19937. });
  19938. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19939. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19940. get: function () {
  19941. return this._applyFog;
  19942. },
  19943. set: function (value) {
  19944. if (this._applyFog === value) {
  19945. return;
  19946. }
  19947. this._applyFog = value;
  19948. this._markSubMeshesAsMiscDirty();
  19949. },
  19950. enumerable: true,
  19951. configurable: true
  19952. });
  19953. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19954. /**
  19955. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19956. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19957. */
  19958. get: function () {
  19959. return this._layerMask;
  19960. },
  19961. set: function (value) {
  19962. if (value === this._layerMask) {
  19963. return;
  19964. }
  19965. this._layerMask = value;
  19966. this._resyncLightSources();
  19967. },
  19968. enumerable: true,
  19969. configurable: true
  19970. });
  19971. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19972. /**
  19973. * Gets or sets a collision mask used to mask collisions (default is -1).
  19974. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19975. */
  19976. get: function () {
  19977. return this._collisionMask;
  19978. },
  19979. set: function (mask) {
  19980. this._collisionMask = !isNaN(mask) ? mask : -1;
  19981. },
  19982. enumerable: true,
  19983. configurable: true
  19984. });
  19985. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19986. /**
  19987. * Gets or sets the current collision group mask (-1 by default).
  19988. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19989. */
  19990. get: function () {
  19991. return this._collisionGroup;
  19992. },
  19993. set: function (mask) {
  19994. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19995. },
  19996. enumerable: true,
  19997. configurable: true
  19998. });
  19999. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20000. /** @hidden */
  20001. get: function () {
  20002. return null;
  20003. },
  20004. enumerable: true,
  20005. configurable: true
  20006. });
  20007. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20008. get: function () {
  20009. return this._skeleton;
  20010. },
  20011. /**
  20012. * Gets or sets a skeleton to apply skining transformations
  20013. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20014. */
  20015. set: function (value) {
  20016. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20017. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20018. }
  20019. if (value && value.needInitialSkinMatrix) {
  20020. value._registerMeshWithPoseMatrix(this);
  20021. }
  20022. this._skeleton = value;
  20023. if (!this._skeleton) {
  20024. this._bonesTransformMatrices = null;
  20025. }
  20026. this._markSubMeshesAsAttributesDirty();
  20027. },
  20028. enumerable: true,
  20029. configurable: true
  20030. });
  20031. /**
  20032. * Returns the string "AbstractMesh"
  20033. * @returns "AbstractMesh"
  20034. */
  20035. AbstractMesh.prototype.getClassName = function () {
  20036. return "AbstractMesh";
  20037. };
  20038. /**
  20039. * Gets a string representation of the current mesh
  20040. * @param fullDetails defines a boolean indicating if full details must be included
  20041. * @returns a string representation of the current mesh
  20042. */
  20043. AbstractMesh.prototype.toString = function (fullDetails) {
  20044. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20045. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20046. if (this._skeleton) {
  20047. ret += ", skeleton: " + this._skeleton.name;
  20048. }
  20049. if (fullDetails) {
  20050. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20051. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20052. }
  20053. return ret;
  20054. };
  20055. /** @hidden */
  20056. AbstractMesh.prototype._rebuild = function () {
  20057. if (this._occlusionQuery) {
  20058. this._occlusionQuery = null;
  20059. }
  20060. if (this._edgesRenderer) {
  20061. this._edgesRenderer._rebuild();
  20062. }
  20063. if (!this.subMeshes) {
  20064. return;
  20065. }
  20066. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20067. var subMesh = _a[_i];
  20068. subMesh._rebuild();
  20069. }
  20070. };
  20071. /** @hidden */
  20072. AbstractMesh.prototype._resyncLightSources = function () {
  20073. this._lightSources.length = 0;
  20074. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20075. var light = _a[_i];
  20076. if (!light.isEnabled()) {
  20077. continue;
  20078. }
  20079. if (light.canAffectMesh(this)) {
  20080. this._lightSources.push(light);
  20081. }
  20082. }
  20083. this._markSubMeshesAsLightDirty();
  20084. };
  20085. /** @hidden */
  20086. AbstractMesh.prototype._resyncLighSource = function (light) {
  20087. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20088. var index = this._lightSources.indexOf(light);
  20089. if (index === -1) {
  20090. if (!isIn) {
  20091. return;
  20092. }
  20093. this._lightSources.push(light);
  20094. }
  20095. else {
  20096. if (isIn) {
  20097. return;
  20098. }
  20099. this._lightSources.splice(index, 1);
  20100. }
  20101. this._markSubMeshesAsLightDirty();
  20102. };
  20103. /** @hidden */
  20104. AbstractMesh.prototype._unBindEffect = function () {
  20105. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20106. var subMesh = _a[_i];
  20107. subMesh.setEffect(null);
  20108. }
  20109. };
  20110. /** @hidden */
  20111. AbstractMesh.prototype._removeLightSource = function (light) {
  20112. var index = this._lightSources.indexOf(light);
  20113. if (index === -1) {
  20114. return;
  20115. }
  20116. this._lightSources.splice(index, 1);
  20117. this._markSubMeshesAsLightDirty();
  20118. };
  20119. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  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. if (subMesh._materialDefines) {
  20126. func(subMesh._materialDefines);
  20127. }
  20128. }
  20129. };
  20130. /** @hidden */
  20131. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20132. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20133. };
  20134. /** @hidden */
  20135. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20136. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20137. };
  20138. /** @hidden */
  20139. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20140. if (!this.subMeshes) {
  20141. return;
  20142. }
  20143. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20144. var subMesh = _a[_i];
  20145. var material = subMesh.getMaterial();
  20146. if (material) {
  20147. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20148. }
  20149. }
  20150. };
  20151. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20152. /**
  20153. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20154. */
  20155. get: function () {
  20156. return this._scaling;
  20157. },
  20158. set: function (newScaling) {
  20159. this._scaling = newScaling;
  20160. if (this.physicsImpostor) {
  20161. this.physicsImpostor.forceUpdate();
  20162. }
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. // Methods
  20168. /**
  20169. * Disables the mesh edge rendering mode
  20170. * @returns the currentAbstractMesh
  20171. */
  20172. AbstractMesh.prototype.disableEdgesRendering = function () {
  20173. if (this._edgesRenderer) {
  20174. this._edgesRenderer.dispose();
  20175. this._edgesRenderer = null;
  20176. }
  20177. return this;
  20178. };
  20179. /**
  20180. * Enables the edge rendering mode on the mesh.
  20181. * This mode makes the mesh edges visible
  20182. * @param epsilon defines the maximal distance between two angles to detect a face
  20183. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20184. * @returns the currentAbstractMesh
  20185. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20186. */
  20187. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20188. if (epsilon === void 0) { epsilon = 0.95; }
  20189. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20190. this.disableEdgesRendering();
  20191. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20192. return this;
  20193. };
  20194. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20195. /**
  20196. * Gets the edgesRenderer associated with the mesh
  20197. */
  20198. get: function () {
  20199. return this._edgesRenderer;
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20205. /**
  20206. * Returns true if the mesh is blocked. Implemented by child classes
  20207. */
  20208. get: function () {
  20209. return false;
  20210. },
  20211. enumerable: true,
  20212. configurable: true
  20213. });
  20214. /**
  20215. * Returns the mesh itself by default. Implemented by child classes
  20216. * @param camera defines the camera to use to pick the right LOD level
  20217. * @returns the currentAbstractMesh
  20218. */
  20219. AbstractMesh.prototype.getLOD = function (camera) {
  20220. return this;
  20221. };
  20222. /**
  20223. * Returns 0 by default. Implemented by child classes
  20224. * @returns an integer
  20225. */
  20226. AbstractMesh.prototype.getTotalVertices = function () {
  20227. return 0;
  20228. };
  20229. /**
  20230. * Returns null by default. Implemented by child classes
  20231. * @returns null
  20232. */
  20233. AbstractMesh.prototype.getIndices = function () {
  20234. return null;
  20235. };
  20236. /**
  20237. * Returns the array of the requested vertex data kind. Implemented by child classes
  20238. * @param kind defines the vertex data kind to use
  20239. * @returns null
  20240. */
  20241. AbstractMesh.prototype.getVerticesData = function (kind) {
  20242. return null;
  20243. };
  20244. /**
  20245. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20246. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20247. * Note that a new underlying VertexBuffer object is created each call.
  20248. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20249. * @param kind defines vertex data kind:
  20250. * * BABYLON.VertexBuffer.PositionKind
  20251. * * BABYLON.VertexBuffer.UVKind
  20252. * * BABYLON.VertexBuffer.UV2Kind
  20253. * * BABYLON.VertexBuffer.UV3Kind
  20254. * * BABYLON.VertexBuffer.UV4Kind
  20255. * * BABYLON.VertexBuffer.UV5Kind
  20256. * * BABYLON.VertexBuffer.UV6Kind
  20257. * * BABYLON.VertexBuffer.ColorKind
  20258. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20259. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20260. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20261. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20262. * @param data defines the data source
  20263. * @param updatable defines if the data must be flagged as updatable (or static)
  20264. * @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
  20265. * @returns the current mesh
  20266. */
  20267. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20268. return this;
  20269. };
  20270. /**
  20271. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20272. * If the mesh has no geometry, it is simply returned as it is.
  20273. * @param kind defines vertex data kind:
  20274. * * BABYLON.VertexBuffer.PositionKind
  20275. * * BABYLON.VertexBuffer.UVKind
  20276. * * BABYLON.VertexBuffer.UV2Kind
  20277. * * BABYLON.VertexBuffer.UV3Kind
  20278. * * BABYLON.VertexBuffer.UV4Kind
  20279. * * BABYLON.VertexBuffer.UV5Kind
  20280. * * BABYLON.VertexBuffer.UV6Kind
  20281. * * BABYLON.VertexBuffer.ColorKind
  20282. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20283. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20284. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20285. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20286. * @param data defines the data source
  20287. * @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
  20288. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20289. * @returns the current mesh
  20290. */
  20291. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20292. return this;
  20293. };
  20294. /**
  20295. * Sets the mesh indices,
  20296. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20297. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20298. * @param totalVertices Defines the total number of vertices
  20299. * @returns the current mesh
  20300. */
  20301. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20302. return this;
  20303. };
  20304. /**
  20305. * Gets a boolean indicating if specific vertex data is present
  20306. * @param kind defines the vertex data kind to use
  20307. * @returns true is data kind is present
  20308. */
  20309. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20310. return false;
  20311. };
  20312. /**
  20313. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20314. * @returns a BoundingInfo
  20315. */
  20316. AbstractMesh.prototype.getBoundingInfo = function () {
  20317. if (this._masterMesh) {
  20318. return this._masterMesh.getBoundingInfo();
  20319. }
  20320. if (!this._boundingInfo) {
  20321. // this._boundingInfo is being created here
  20322. this._updateBoundingInfo();
  20323. }
  20324. // cannot be null.
  20325. return this._boundingInfo;
  20326. };
  20327. /**
  20328. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20329. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20330. * @returns the current mesh
  20331. */
  20332. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20333. if (includeDescendants === void 0) { includeDescendants = true; }
  20334. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20335. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20336. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20337. if (maxDimension === 0) {
  20338. return this;
  20339. }
  20340. var scale = 1 / maxDimension;
  20341. this.scaling.scaleInPlace(scale);
  20342. return this;
  20343. };
  20344. /**
  20345. * Overwrite the current bounding info
  20346. * @param boundingInfo defines the new bounding info
  20347. * @returns the current mesh
  20348. */
  20349. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20350. this._boundingInfo = boundingInfo;
  20351. return this;
  20352. };
  20353. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20354. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20355. get: function () {
  20356. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20357. },
  20358. enumerable: true,
  20359. configurable: true
  20360. });
  20361. /** @hidden */
  20362. AbstractMesh.prototype._preActivate = function () {
  20363. };
  20364. /** @hidden */
  20365. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20366. };
  20367. /** @hidden */
  20368. AbstractMesh.prototype._activate = function (renderId) {
  20369. this._renderId = renderId;
  20370. };
  20371. /**
  20372. * Gets the current world matrix
  20373. * @returns a Matrix
  20374. */
  20375. AbstractMesh.prototype.getWorldMatrix = function () {
  20376. if (this._masterMesh) {
  20377. return this._masterMesh.getWorldMatrix();
  20378. }
  20379. return _super.prototype.getWorldMatrix.call(this);
  20380. };
  20381. /** @hidden */
  20382. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20383. if (this._masterMesh) {
  20384. return this._masterMesh._getWorldMatrixDeterminant();
  20385. }
  20386. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20387. };
  20388. // ================================== Point of View Movement =================================
  20389. /**
  20390. * Perform relative position change from the point of view of behind the front of the mesh.
  20391. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20392. * Supports definition of mesh facing forward or backward
  20393. * @param amountRight defines the distance on the right axis
  20394. * @param amountUp defines the distance on the up axis
  20395. * @param amountForward defines the distance on the forward axis
  20396. * @returns the current mesh
  20397. */
  20398. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20399. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20400. return this;
  20401. };
  20402. /**
  20403. * Calculate relative position change from the point of view of behind the front of the mesh.
  20404. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20405. * Supports definition of mesh facing forward or backward
  20406. * @param amountRight defines the distance on the right axis
  20407. * @param amountUp defines the distance on the up axis
  20408. * @param amountForward defines the distance on the forward axis
  20409. * @returns the new displacement vector
  20410. */
  20411. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20412. var rotMatrix = new BABYLON.Matrix();
  20413. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20414. rotQuaternion.toRotationMatrix(rotMatrix);
  20415. var translationDelta = BABYLON.Vector3.Zero();
  20416. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20417. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20418. return translationDelta;
  20419. };
  20420. // ================================== Point of View Rotation =================================
  20421. /**
  20422. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20423. * Supports definition of mesh facing forward or backward
  20424. * @param flipBack defines the flip
  20425. * @param twirlClockwise defines the twirl
  20426. * @param tiltRight defines the tilt
  20427. * @returns the current mesh
  20428. */
  20429. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20430. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20431. return this;
  20432. };
  20433. /**
  20434. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20435. * Supports definition of mesh facing forward or backward.
  20436. * @param flipBack defines the flip
  20437. * @param twirlClockwise defines the twirl
  20438. * @param tiltRight defines the tilt
  20439. * @returns the new rotation vector
  20440. */
  20441. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20442. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20443. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20444. };
  20445. /**
  20446. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20447. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20448. * @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
  20449. * @returns the new bounding vectors
  20450. */
  20451. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20452. if (includeDescendants === void 0) { includeDescendants = true; }
  20453. if (predicate === void 0) { predicate = null; }
  20454. // Ensures that all world matrix will be recomputed.
  20455. this.getScene().incrementRenderId();
  20456. this.computeWorldMatrix(true);
  20457. var min;
  20458. var max;
  20459. var boundingInfo = this.getBoundingInfo();
  20460. if (!this.subMeshes) {
  20461. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20462. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20463. }
  20464. else {
  20465. min = boundingInfo.boundingBox.minimumWorld;
  20466. max = boundingInfo.boundingBox.maximumWorld;
  20467. }
  20468. if (includeDescendants) {
  20469. var descendants = this.getDescendants(false);
  20470. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20471. var descendant = descendants_1[_i];
  20472. var childMesh = descendant;
  20473. childMesh.computeWorldMatrix(true);
  20474. // Filters meshes based on custom predicate function.
  20475. if (predicate && !predicate(childMesh)) {
  20476. continue;
  20477. }
  20478. //make sure we have the needed params to get mix and max
  20479. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20480. continue;
  20481. }
  20482. var childBoundingInfo = childMesh.getBoundingInfo();
  20483. var boundingBox = childBoundingInfo.boundingBox;
  20484. var minBox = boundingBox.minimumWorld;
  20485. var maxBox = boundingBox.maximumWorld;
  20486. BABYLON.Tools.CheckExtends(minBox, min, max);
  20487. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20488. }
  20489. }
  20490. return {
  20491. min: min,
  20492. max: max
  20493. };
  20494. };
  20495. /** @hidden */
  20496. AbstractMesh.prototype._updateBoundingInfo = function () {
  20497. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20498. this._boundingInfo.update(this.worldMatrixFromCache);
  20499. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20500. return this;
  20501. };
  20502. /** @hidden */
  20503. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20504. if (!this.subMeshes) {
  20505. return this;
  20506. }
  20507. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20508. var subMesh = this.subMeshes[subIndex];
  20509. if (!subMesh.IsGlobal) {
  20510. subMesh.updateBoundingInfo(matrix);
  20511. }
  20512. }
  20513. return this;
  20514. };
  20515. /** @hidden */
  20516. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20517. // Bounding info
  20518. this._updateBoundingInfo();
  20519. };
  20520. /**
  20521. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20522. * A mesh is in the frustum if its bounding box intersects the frustum
  20523. * @param frustumPlanes defines the frustum to test
  20524. * @returns true if the mesh is in the frustum planes
  20525. */
  20526. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20527. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20528. };
  20529. /**
  20530. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20531. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20532. * @param frustumPlanes defines the frustum to test
  20533. * @returns true if the mesh is completely in the frustum planes
  20534. */
  20535. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20536. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20537. };
  20538. /**
  20539. * True if the mesh intersects another mesh or a SolidParticle object
  20540. * @param mesh defines a target mesh or SolidParticle to test
  20541. * @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)
  20542. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20543. * @returns true if there is an intersection
  20544. */
  20545. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20546. if (precise === void 0) { precise = false; }
  20547. if (!this._boundingInfo || !mesh._boundingInfo) {
  20548. return false;
  20549. }
  20550. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20551. return true;
  20552. }
  20553. if (includeDescendants) {
  20554. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20555. var child = _a[_i];
  20556. if (child.intersectsMesh(mesh, precise, true)) {
  20557. return true;
  20558. }
  20559. }
  20560. }
  20561. return false;
  20562. };
  20563. /**
  20564. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20565. * @param point defines the point to test
  20566. * @returns true if there is an intersection
  20567. */
  20568. AbstractMesh.prototype.intersectsPoint = function (point) {
  20569. if (!this._boundingInfo) {
  20570. return false;
  20571. }
  20572. return this._boundingInfo.intersectsPoint(point);
  20573. };
  20574. /**
  20575. * Gets the current physics impostor
  20576. * @see http://doc.babylonjs.com/features/physics_engine
  20577. * @returns a physics impostor or null
  20578. */
  20579. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20580. return this.physicsImpostor;
  20581. };
  20582. /**
  20583. * Gets the position of the current mesh in camera space
  20584. * @param camera defines the camera to use
  20585. * @returns a position
  20586. */
  20587. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20588. if (camera === void 0) { camera = null; }
  20589. if (!camera) {
  20590. camera = this.getScene().activeCamera;
  20591. }
  20592. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20593. };
  20594. /**
  20595. * Returns the distance from the mesh to the active camera
  20596. * @param camera defines the camera to use
  20597. * @returns the distance
  20598. */
  20599. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20600. if (camera === void 0) { camera = null; }
  20601. if (!camera) {
  20602. camera = this.getScene().activeCamera;
  20603. }
  20604. return this.absolutePosition.subtract(camera.position).length();
  20605. };
  20606. /**
  20607. * Apply a physic impulse to the mesh
  20608. * @param force defines the force to apply
  20609. * @param contactPoint defines where to apply the force
  20610. * @returns the current mesh
  20611. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20612. */
  20613. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20614. if (!this.physicsImpostor) {
  20615. return this;
  20616. }
  20617. this.physicsImpostor.applyImpulse(force, contactPoint);
  20618. return this;
  20619. };
  20620. /**
  20621. * Creates a physic joint between two meshes
  20622. * @param otherMesh defines the other mesh to use
  20623. * @param pivot1 defines the pivot to use on this mesh
  20624. * @param pivot2 defines the pivot to use on the other mesh
  20625. * @param options defines additional options (can be plugin dependent)
  20626. * @returns the current mesh
  20627. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20628. */
  20629. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20630. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20631. return this;
  20632. }
  20633. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20634. mainPivot: pivot1,
  20635. connectedPivot: pivot2,
  20636. nativeParams: options
  20637. });
  20638. return this;
  20639. };
  20640. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20641. // Collisions
  20642. /**
  20643. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20644. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20645. */
  20646. get: function () {
  20647. return this._checkCollisions;
  20648. },
  20649. set: function (collisionEnabled) {
  20650. this._checkCollisions = collisionEnabled;
  20651. if (this.getScene().workerCollisions) {
  20652. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20653. }
  20654. },
  20655. enumerable: true,
  20656. configurable: true
  20657. });
  20658. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20659. /**
  20660. * Gets Collider object used to compute collisions (not physics)
  20661. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20662. */
  20663. get: function () {
  20664. return this._collider;
  20665. },
  20666. enumerable: true,
  20667. configurable: true
  20668. });
  20669. /**
  20670. * Move the mesh using collision engine
  20671. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20672. * @param displacement defines the requested displacement vector
  20673. * @returns the current mesh
  20674. */
  20675. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20676. var globalPosition = this.getAbsolutePosition();
  20677. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20678. if (!this._collider) {
  20679. this._collider = new BABYLON.Collider();
  20680. }
  20681. this._collider._radius = this.ellipsoid;
  20682. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20683. return this;
  20684. };
  20685. // Submeshes octree
  20686. /**
  20687. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20688. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20689. * @param maxCapacity defines the maximum size of each block (64 by default)
  20690. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20691. * @returns the new octree
  20692. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20693. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20694. */
  20695. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20696. if (maxCapacity === void 0) { maxCapacity = 64; }
  20697. if (maxDepth === void 0) { maxDepth = 2; }
  20698. if (!this._submeshesOctree) {
  20699. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20700. }
  20701. this.computeWorldMatrix(true);
  20702. var boundingInfo = this.getBoundingInfo();
  20703. // Update octree
  20704. var bbox = boundingInfo.boundingBox;
  20705. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20706. return this._submeshesOctree;
  20707. };
  20708. // Collisions
  20709. /** @hidden */
  20710. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20711. this._generatePointsArray();
  20712. if (!this._positions) {
  20713. return this;
  20714. }
  20715. // Transformation
  20716. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20717. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20718. subMesh._lastColliderWorldVertices = [];
  20719. subMesh._trianglePlanes = [];
  20720. var start = subMesh.verticesStart;
  20721. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20722. for (var i = start; i < end; i++) {
  20723. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20724. }
  20725. }
  20726. // Collide
  20727. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20728. if (collider.collisionFound) {
  20729. collider.collidedMesh = this;
  20730. }
  20731. return this;
  20732. };
  20733. /** @hidden */
  20734. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20735. var subMeshes;
  20736. var len;
  20737. // Octrees
  20738. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20739. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20740. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20741. len = intersections.length;
  20742. subMeshes = intersections.data;
  20743. }
  20744. else {
  20745. subMeshes = this.subMeshes;
  20746. len = subMeshes.length;
  20747. }
  20748. for (var index = 0; index < len; index++) {
  20749. var subMesh = subMeshes[index];
  20750. // Bounding test
  20751. if (len > 1 && !subMesh._checkCollision(collider))
  20752. continue;
  20753. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20754. }
  20755. return this;
  20756. };
  20757. /** @hidden */
  20758. AbstractMesh.prototype._checkCollision = function (collider) {
  20759. // Bounding box test
  20760. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20761. return this;
  20762. // Transformation matrix
  20763. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20764. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20765. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20766. return this;
  20767. };
  20768. // Picking
  20769. /** @hidden */
  20770. AbstractMesh.prototype._generatePointsArray = function () {
  20771. return false;
  20772. };
  20773. /**
  20774. * Checks if the passed Ray intersects with the mesh
  20775. * @param ray defines the ray to use
  20776. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20777. * @returns the picking info
  20778. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20779. */
  20780. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20781. var pickingInfo = new BABYLON.PickingInfo();
  20782. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20783. return pickingInfo;
  20784. }
  20785. if (!this._generatePointsArray()) {
  20786. return pickingInfo;
  20787. }
  20788. var intersectInfo = null;
  20789. // Octrees
  20790. var subMeshes;
  20791. var len;
  20792. if (this._submeshesOctree && this.useOctreeForPicking) {
  20793. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20794. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20795. len = intersections.length;
  20796. subMeshes = intersections.data;
  20797. }
  20798. else {
  20799. subMeshes = this.subMeshes;
  20800. len = subMeshes.length;
  20801. }
  20802. for (var index = 0; index < len; index++) {
  20803. var subMesh = subMeshes[index];
  20804. // Bounding test
  20805. if (len > 1 && !subMesh.canIntersects(ray))
  20806. continue;
  20807. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20808. if (currentIntersectInfo) {
  20809. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20810. intersectInfo = currentIntersectInfo;
  20811. intersectInfo.subMeshId = index;
  20812. if (fastCheck) {
  20813. break;
  20814. }
  20815. }
  20816. }
  20817. }
  20818. if (intersectInfo) {
  20819. // Get picked point
  20820. var world = this.getWorldMatrix();
  20821. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20822. var direction = ray.direction.clone();
  20823. direction = direction.scale(intersectInfo.distance);
  20824. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20825. var pickedPoint = worldOrigin.add(worldDirection);
  20826. // Return result
  20827. pickingInfo.hit = true;
  20828. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20829. pickingInfo.pickedPoint = pickedPoint;
  20830. pickingInfo.pickedMesh = this;
  20831. pickingInfo.bu = intersectInfo.bu || 0;
  20832. pickingInfo.bv = intersectInfo.bv || 0;
  20833. pickingInfo.faceId = intersectInfo.faceId;
  20834. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20835. return pickingInfo;
  20836. }
  20837. return pickingInfo;
  20838. };
  20839. /**
  20840. * Clones the current mesh
  20841. * @param name defines the mesh name
  20842. * @param newParent defines the new mesh parent
  20843. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20844. * @returns the new mesh
  20845. */
  20846. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20847. return null;
  20848. };
  20849. /**
  20850. * Disposes all the submeshes of the current meshnp
  20851. * @returns the current mesh
  20852. */
  20853. AbstractMesh.prototype.releaseSubMeshes = function () {
  20854. if (this.subMeshes) {
  20855. while (this.subMeshes.length) {
  20856. this.subMeshes[0].dispose();
  20857. }
  20858. }
  20859. else {
  20860. this.subMeshes = new Array();
  20861. }
  20862. return this;
  20863. };
  20864. /**
  20865. * Releases resources associated with this abstract mesh.
  20866. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20867. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20868. */
  20869. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20870. var _this = this;
  20871. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20872. var index;
  20873. // Smart Array Retainers.
  20874. this.getScene().freeActiveMeshes();
  20875. this.getScene().freeRenderingGroups();
  20876. // Action manager
  20877. if (this.actionManager !== undefined && this.actionManager !== null) {
  20878. this.actionManager.dispose();
  20879. this.actionManager = null;
  20880. }
  20881. // Skeleton
  20882. this._skeleton = null;
  20883. // Physics
  20884. if (this.physicsImpostor) {
  20885. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20886. }
  20887. // Intersections in progress
  20888. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20889. var other = this._intersectionsInProgress[index];
  20890. var pos = other._intersectionsInProgress.indexOf(this);
  20891. other._intersectionsInProgress.splice(pos, 1);
  20892. }
  20893. this._intersectionsInProgress = [];
  20894. // Lights
  20895. var lights = this.getScene().lights;
  20896. lights.forEach(function (light) {
  20897. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20898. if (meshIndex !== -1) {
  20899. light.includedOnlyMeshes.splice(meshIndex, 1);
  20900. }
  20901. meshIndex = light.excludedMeshes.indexOf(_this);
  20902. if (meshIndex !== -1) {
  20903. light.excludedMeshes.splice(meshIndex, 1);
  20904. }
  20905. // Shadow generators
  20906. var generator = light.getShadowGenerator();
  20907. if (generator) {
  20908. var shadowMap = generator.getShadowMap();
  20909. if (shadowMap && shadowMap.renderList) {
  20910. meshIndex = shadowMap.renderList.indexOf(_this);
  20911. if (meshIndex !== -1) {
  20912. shadowMap.renderList.splice(meshIndex, 1);
  20913. }
  20914. }
  20915. }
  20916. });
  20917. // Edges
  20918. if (this._edgesRenderer) {
  20919. this._edgesRenderer.dispose();
  20920. this._edgesRenderer = null;
  20921. }
  20922. // SubMeshes
  20923. if (this.getClassName() !== "InstancedMesh") {
  20924. this.releaseSubMeshes();
  20925. }
  20926. // Octree
  20927. var sceneOctree = this.getScene().selectionOctree;
  20928. if (sceneOctree !== undefined && sceneOctree !== null) {
  20929. var index = sceneOctree.dynamicContent.indexOf(this);
  20930. if (index !== -1) {
  20931. sceneOctree.dynamicContent.splice(index, 1);
  20932. }
  20933. }
  20934. // Query
  20935. var engine = this.getScene().getEngine();
  20936. if (this._occlusionQuery) {
  20937. this._isOcclusionQueryInProgress = false;
  20938. engine.deleteQuery(this._occlusionQuery);
  20939. this._occlusionQuery = null;
  20940. }
  20941. // Engine
  20942. engine.wipeCaches();
  20943. // Remove from scene
  20944. this.getScene().removeMesh(this);
  20945. if (disposeMaterialAndTextures) {
  20946. if (this.material) {
  20947. this.material.dispose(false, true);
  20948. }
  20949. }
  20950. if (!doNotRecurse) {
  20951. // Particles
  20952. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20953. if (this.getScene().particleSystems[index].emitter === this) {
  20954. this.getScene().particleSystems[index].dispose();
  20955. index--;
  20956. }
  20957. }
  20958. }
  20959. // facet data
  20960. if (this._facetDataEnabled) {
  20961. this.disableFacetData();
  20962. }
  20963. this.onAfterWorldMatrixUpdateObservable.clear();
  20964. this.onCollideObservable.clear();
  20965. this.onCollisionPositionChangeObservable.clear();
  20966. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20967. };
  20968. /**
  20969. * Adds the passed mesh as a child to the current mesh
  20970. * @param mesh defines the child mesh
  20971. * @returns the current mesh
  20972. */
  20973. AbstractMesh.prototype.addChild = function (mesh) {
  20974. mesh.setParent(this);
  20975. return this;
  20976. };
  20977. /**
  20978. * Removes the passed mesh from the current mesh children list
  20979. * @param mesh defines the child mesh
  20980. * @returns the current mesh
  20981. */
  20982. AbstractMesh.prototype.removeChild = function (mesh) {
  20983. mesh.setParent(null);
  20984. return this;
  20985. };
  20986. // Facet data
  20987. /** @hidden */
  20988. AbstractMesh.prototype._initFacetData = function () {
  20989. if (!this._facetNormals) {
  20990. this._facetNormals = new Array();
  20991. }
  20992. if (!this._facetPositions) {
  20993. this._facetPositions = new Array();
  20994. }
  20995. if (!this._facetPartitioning) {
  20996. this._facetPartitioning = new Array();
  20997. }
  20998. this._facetNb = (this.getIndices().length / 3) | 0;
  20999. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21000. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21001. for (var f = 0; f < this._facetNb; f++) {
  21002. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21003. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21004. }
  21005. this._facetDataEnabled = true;
  21006. return this;
  21007. };
  21008. /**
  21009. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21010. * This method can be called within the render loop.
  21011. * 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
  21012. * @returns the current mesh
  21013. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21014. */
  21015. AbstractMesh.prototype.updateFacetData = function () {
  21016. if (!this._facetDataEnabled) {
  21017. this._initFacetData();
  21018. }
  21019. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21020. var indices = this.getIndices();
  21021. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21022. var bInfo = this.getBoundingInfo();
  21023. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21024. // init arrays, matrix and sort function on first call
  21025. this._facetDepthSortEnabled = true;
  21026. if (indices instanceof Uint16Array) {
  21027. this._depthSortedIndices = new Uint16Array(indices);
  21028. }
  21029. else if (indices instanceof Uint32Array) {
  21030. this._depthSortedIndices = new Uint32Array(indices);
  21031. }
  21032. else {
  21033. var needs32bits = false;
  21034. for (var i = 0; i < indices.length; i++) {
  21035. if (indices[i] > 65535) {
  21036. needs32bits = true;
  21037. break;
  21038. }
  21039. }
  21040. if (needs32bits) {
  21041. this._depthSortedIndices = new Uint32Array(indices);
  21042. }
  21043. else {
  21044. this._depthSortedIndices = new Uint16Array(indices);
  21045. }
  21046. }
  21047. this._facetDepthSortFunction = function (f1, f2) {
  21048. return (f2.sqDistance - f1.sqDistance);
  21049. };
  21050. if (!this._facetDepthSortFrom) {
  21051. var camera = this.getScene().activeCamera;
  21052. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21053. }
  21054. this._depthSortedFacets = [];
  21055. for (var f = 0; f < this._facetNb; f++) {
  21056. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21057. this._depthSortedFacets.push(depthSortedFacet);
  21058. }
  21059. this._invertedMatrix = BABYLON.Matrix.Identity();
  21060. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21061. }
  21062. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21063. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21064. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21065. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21066. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21067. this._subDiv.max = this._partitioningSubdivisions;
  21068. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21069. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21070. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21071. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21072. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21073. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21074. // set the parameters for ComputeNormals()
  21075. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21076. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21077. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21078. this._facetParameters.bInfo = bInfo;
  21079. this._facetParameters.bbSize = this._bbSize;
  21080. this._facetParameters.subDiv = this._subDiv;
  21081. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21082. this._facetParameters.depthSort = this._facetDepthSort;
  21083. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21084. this.computeWorldMatrix(true);
  21085. this._worldMatrix.invertToRef(this._invertedMatrix);
  21086. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21087. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21088. }
  21089. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21090. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21091. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21092. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21093. var l = (this._depthSortedIndices.length / 3) | 0;
  21094. for (var f = 0; f < l; f++) {
  21095. var sind = this._depthSortedFacets[f].ind;
  21096. this._depthSortedIndices[f * 3] = indices[sind];
  21097. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21098. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21099. }
  21100. this.updateIndices(this._depthSortedIndices);
  21101. }
  21102. return this;
  21103. };
  21104. /**
  21105. * Returns the facetLocalNormals array.
  21106. * The normals are expressed in the mesh local spac
  21107. * @returns an array of Vector3
  21108. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21109. */
  21110. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21111. if (!this._facetNormals) {
  21112. this.updateFacetData();
  21113. }
  21114. return this._facetNormals;
  21115. };
  21116. /**
  21117. * Returns the facetLocalPositions array.
  21118. * The facet positions are expressed in the mesh local space
  21119. * @returns an array of Vector3
  21120. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21121. */
  21122. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21123. if (!this._facetPositions) {
  21124. this.updateFacetData();
  21125. }
  21126. return this._facetPositions;
  21127. };
  21128. /**
  21129. * Returns the facetLocalPartioning array
  21130. * @returns an array of array of numbers
  21131. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21132. */
  21133. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21134. if (!this._facetPartitioning) {
  21135. this.updateFacetData();
  21136. }
  21137. return this._facetPartitioning;
  21138. };
  21139. /**
  21140. * Returns the i-th facet position in the world system.
  21141. * This method allocates a new Vector3 per call
  21142. * @param i defines the facet index
  21143. * @returns a new Vector3
  21144. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21145. */
  21146. AbstractMesh.prototype.getFacetPosition = function (i) {
  21147. var pos = BABYLON.Vector3.Zero();
  21148. this.getFacetPositionToRef(i, pos);
  21149. return pos;
  21150. };
  21151. /**
  21152. * Sets the reference Vector3 with the i-th facet position in the world system
  21153. * @param i defines the facet index
  21154. * @param ref defines the target vector
  21155. * @returns the current mesh
  21156. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21157. */
  21158. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21159. var localPos = (this.getFacetLocalPositions())[i];
  21160. var world = this.getWorldMatrix();
  21161. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21162. return this;
  21163. };
  21164. /**
  21165. * Returns the i-th facet normal in the world system.
  21166. * This method allocates a new Vector3 per call
  21167. * @param i defines the facet index
  21168. * @returns a new Vector3
  21169. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21170. */
  21171. AbstractMesh.prototype.getFacetNormal = function (i) {
  21172. var norm = BABYLON.Vector3.Zero();
  21173. this.getFacetNormalToRef(i, norm);
  21174. return norm;
  21175. };
  21176. /**
  21177. * Sets the reference Vector3 with the i-th facet normal in the world system
  21178. * @param i defines the facet index
  21179. * @param ref defines the target vector
  21180. * @returns the current mesh
  21181. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21182. */
  21183. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21184. var localNorm = (this.getFacetLocalNormals())[i];
  21185. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21186. return this;
  21187. };
  21188. /**
  21189. * 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)
  21190. * @param x defines x coordinate
  21191. * @param y defines y coordinate
  21192. * @param z defines z coordinate
  21193. * @returns the array of facet indexes
  21194. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21195. */
  21196. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21197. var bInfo = this.getBoundingInfo();
  21198. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21199. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21200. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21201. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21202. return null;
  21203. }
  21204. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21205. };
  21206. /**
  21207. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21208. * @param projected sets as the (x,y,z) world projection on the facet
  21209. * @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
  21210. * @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
  21211. * @param x defines x coordinate
  21212. * @param y defines y coordinate
  21213. * @param z defines z coordinate
  21214. * @returns the face index if found (or null instead)
  21215. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21216. */
  21217. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21218. if (checkFace === void 0) { checkFace = false; }
  21219. if (facing === void 0) { facing = true; }
  21220. var world = this.getWorldMatrix();
  21221. var invMat = BABYLON.Tmp.Matrix[5];
  21222. world.invertToRef(invMat);
  21223. var invVect = BABYLON.Tmp.Vector3[8];
  21224. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21225. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21226. if (projected) {
  21227. // tranform the local computed projected vector to world coordinates
  21228. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21229. }
  21230. return closest;
  21231. };
  21232. /**
  21233. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21234. * @param projected sets as the (x,y,z) local projection on the facet
  21235. * @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
  21236. * @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
  21237. * @param x defines x coordinate
  21238. * @param y defines y coordinate
  21239. * @param z defines z coordinate
  21240. * @returns the face index if found (or null instead)
  21241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21242. */
  21243. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21244. if (checkFace === void 0) { checkFace = false; }
  21245. if (facing === void 0) { facing = true; }
  21246. var closest = null;
  21247. var tmpx = 0.0;
  21248. var tmpy = 0.0;
  21249. var tmpz = 0.0;
  21250. var d = 0.0; // tmp dot facet normal * facet position
  21251. var t0 = 0.0;
  21252. var projx = 0.0;
  21253. var projy = 0.0;
  21254. var projz = 0.0;
  21255. // Get all the facets in the same partitioning block than (x, y, z)
  21256. var facetPositions = this.getFacetLocalPositions();
  21257. var facetNormals = this.getFacetLocalNormals();
  21258. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21259. if (!facetsInBlock) {
  21260. return null;
  21261. }
  21262. // Get the closest facet to (x, y, z)
  21263. var shortest = Number.MAX_VALUE; // init distance vars
  21264. var tmpDistance = shortest;
  21265. var fib; // current facet in the block
  21266. var norm; // current facet normal
  21267. var p0; // current facet barycenter position
  21268. // loop on all the facets in the current partitioning block
  21269. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21270. fib = facetsInBlock[idx];
  21271. norm = facetNormals[fib];
  21272. p0 = facetPositions[fib];
  21273. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21274. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21275. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21276. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21277. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21278. projx = x + norm.x * t0;
  21279. projy = y + norm.y * t0;
  21280. projz = z + norm.z * t0;
  21281. tmpx = projx - x;
  21282. tmpy = projy - y;
  21283. tmpz = projz - z;
  21284. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21285. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21286. shortest = tmpDistance;
  21287. closest = fib;
  21288. if (projected) {
  21289. projected.x = projx;
  21290. projected.y = projy;
  21291. projected.z = projz;
  21292. }
  21293. }
  21294. }
  21295. }
  21296. return closest;
  21297. };
  21298. /**
  21299. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21300. * @returns the parameters
  21301. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21302. */
  21303. AbstractMesh.prototype.getFacetDataParameters = function () {
  21304. return this._facetParameters;
  21305. };
  21306. /**
  21307. * Disables the feature FacetData and frees the related memory
  21308. * @returns the current mesh
  21309. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21310. */
  21311. AbstractMesh.prototype.disableFacetData = function () {
  21312. if (this._facetDataEnabled) {
  21313. this._facetDataEnabled = false;
  21314. this._facetPositions = new Array();
  21315. this._facetNormals = new Array();
  21316. this._facetPartitioning = new Array();
  21317. this._facetParameters = null;
  21318. this._depthSortedIndices = new Uint32Array(0);
  21319. }
  21320. return this;
  21321. };
  21322. /**
  21323. * Updates the AbstractMesh indices array
  21324. * @param indices defines the data source
  21325. * @returns the current mesh
  21326. */
  21327. AbstractMesh.prototype.updateIndices = function (indices) {
  21328. return this;
  21329. };
  21330. /**
  21331. * Creates new normals data for the mesh
  21332. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21333. * @returns the current mesh
  21334. */
  21335. AbstractMesh.prototype.createNormals = function (updatable) {
  21336. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21337. var indices = this.getIndices();
  21338. var normals;
  21339. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21340. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21341. }
  21342. else {
  21343. normals = [];
  21344. }
  21345. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21346. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21347. return this;
  21348. };
  21349. /**
  21350. * Align the mesh with a normal
  21351. * @param normal defines the normal to use
  21352. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21353. * @returns the current mesh
  21354. */
  21355. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21356. if (!upDirection) {
  21357. upDirection = BABYLON.Axis.Y;
  21358. }
  21359. var axisX = BABYLON.Tmp.Vector3[0];
  21360. var axisZ = BABYLON.Tmp.Vector3[1];
  21361. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21362. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21363. if (this.rotationQuaternion) {
  21364. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21365. }
  21366. else {
  21367. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21368. }
  21369. return this;
  21370. };
  21371. /** @hidden */
  21372. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21373. var engine = this.getEngine();
  21374. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21375. this._isOccluded = false;
  21376. return;
  21377. }
  21378. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21379. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21380. if (isOcclusionQueryAvailable) {
  21381. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21382. this._isOcclusionQueryInProgress = false;
  21383. this._occlusionInternalRetryCounter = 0;
  21384. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21385. }
  21386. else {
  21387. this._occlusionInternalRetryCounter++;
  21388. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21389. this._isOcclusionQueryInProgress = false;
  21390. this._occlusionInternalRetryCounter = 0;
  21391. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21392. // if strict continue the last state of the object.
  21393. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21394. }
  21395. else {
  21396. return;
  21397. }
  21398. }
  21399. }
  21400. var scene = this.getScene();
  21401. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21402. if (!this._occlusionQuery) {
  21403. this._occlusionQuery = engine.createQuery();
  21404. }
  21405. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21406. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21407. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21408. this._isOcclusionQueryInProgress = true;
  21409. };
  21410. /** No occlusion */
  21411. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21412. /** Occlusion set to optimisitic */
  21413. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21414. /** Occlusion set to strict */
  21415. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21416. /** Use an accurante occlusion algorithm */
  21417. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21418. /** Use a conservative occlusion algorithm */
  21419. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21420. return AbstractMesh;
  21421. }(BABYLON.TransformNode));
  21422. BABYLON.AbstractMesh = AbstractMesh;
  21423. })(BABYLON || (BABYLON = {}));
  21424. //# sourceMappingURL=babylon.abstractMesh.js.map
  21425. var BABYLON;
  21426. (function (BABYLON) {
  21427. /**
  21428. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21429. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21430. * 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.
  21431. */
  21432. var Light = /** @class */ (function (_super) {
  21433. __extends(Light, _super);
  21434. /**
  21435. * Creates a Light object in the scene.
  21436. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21437. * @param name The firendly name of the light
  21438. * @param scene The scene the light belongs too
  21439. */
  21440. function Light(name, scene) {
  21441. var _this = _super.call(this, name, scene) || this;
  21442. /**
  21443. * Diffuse gives the basic color to an object.
  21444. */
  21445. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21446. /**
  21447. * Specular produces a highlight color on an object.
  21448. * Note: This is note affecting PBR materials.
  21449. */
  21450. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21451. /**
  21452. * Strength of the light.
  21453. * Note: By default it is define in the framework own unit.
  21454. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21455. */
  21456. _this.intensity = 1.0;
  21457. /**
  21458. * Defines how far from the source the light is impacting in scene units.
  21459. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21460. */
  21461. _this.range = Number.MAX_VALUE;
  21462. /**
  21463. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21464. * of light.
  21465. */
  21466. _this._photometricScale = 1.0;
  21467. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21468. _this._radius = 0.00001;
  21469. /**
  21470. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21471. * exceeding the number allowed of the materials.
  21472. */
  21473. _this.renderPriority = 0;
  21474. _this._shadowEnabled = true;
  21475. _this._excludeWithLayerMask = 0;
  21476. _this._includeOnlyWithLayerMask = 0;
  21477. _this._lightmapMode = 0;
  21478. /**
  21479. * @hidden Internal use only.
  21480. */
  21481. _this._excludedMeshesIds = new Array();
  21482. /**
  21483. * @hidden Internal use only.
  21484. */
  21485. _this._includedOnlyMeshesIds = new Array();
  21486. _this.getScene().addLight(_this);
  21487. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21488. _this._buildUniformLayout();
  21489. _this.includedOnlyMeshes = new Array();
  21490. _this.excludedMeshes = new Array();
  21491. _this._resyncMeshes();
  21492. return _this;
  21493. }
  21494. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21495. /**
  21496. * If every light affecting the material is in this lightmapMode,
  21497. * material.lightmapTexture adds or multiplies
  21498. * (depends on material.useLightmapAsShadowmap)
  21499. * after every other light calculations.
  21500. */
  21501. get: function () {
  21502. return Light._LIGHTMAP_DEFAULT;
  21503. },
  21504. enumerable: true,
  21505. configurable: true
  21506. });
  21507. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21508. /**
  21509. * material.lightmapTexture as only diffuse lighting from this light
  21510. * adds only specular lighting from this light
  21511. * adds dynamic shadows
  21512. */
  21513. get: function () {
  21514. return Light._LIGHTMAP_SPECULAR;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21520. /**
  21521. * material.lightmapTexture as only lighting
  21522. * no light calculation from this light
  21523. * only adds dynamic shadows from this light
  21524. */
  21525. get: function () {
  21526. return Light._LIGHTMAP_SHADOWSONLY;
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21532. /**
  21533. * Each light type uses the default quantity according to its type:
  21534. * point/spot lights use luminous intensity
  21535. * directional lights use illuminance
  21536. */
  21537. get: function () {
  21538. return Light._INTENSITYMODE_AUTOMATIC;
  21539. },
  21540. enumerable: true,
  21541. configurable: true
  21542. });
  21543. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21544. /**
  21545. * lumen (lm)
  21546. */
  21547. get: function () {
  21548. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21554. /**
  21555. * candela (lm/sr)
  21556. */
  21557. get: function () {
  21558. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21564. /**
  21565. * lux (lm/m^2)
  21566. */
  21567. get: function () {
  21568. return Light._INTENSITYMODE_ILLUMINANCE;
  21569. },
  21570. enumerable: true,
  21571. configurable: true
  21572. });
  21573. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21574. /**
  21575. * nit (cd/m^2)
  21576. */
  21577. get: function () {
  21578. return Light._INTENSITYMODE_LUMINANCE;
  21579. },
  21580. enumerable: true,
  21581. configurable: true
  21582. });
  21583. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21584. /**
  21585. * Light type const id of the point light.
  21586. */
  21587. get: function () {
  21588. return Light._LIGHTTYPEID_POINTLIGHT;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21594. /**
  21595. * Light type const id of the directional light.
  21596. */
  21597. get: function () {
  21598. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21604. /**
  21605. * Light type const id of the spot light.
  21606. */
  21607. get: function () {
  21608. return Light._LIGHTTYPEID_SPOTLIGHT;
  21609. },
  21610. enumerable: true,
  21611. configurable: true
  21612. });
  21613. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21614. /**
  21615. * Light type const id of the hemispheric light.
  21616. */
  21617. get: function () {
  21618. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21619. },
  21620. enumerable: true,
  21621. configurable: true
  21622. });
  21623. Object.defineProperty(Light.prototype, "intensityMode", {
  21624. /**
  21625. * Gets the photometric scale used to interpret the intensity.
  21626. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21627. */
  21628. get: function () {
  21629. return this._intensityMode;
  21630. },
  21631. /**
  21632. * Sets the photometric scale used to interpret the intensity.
  21633. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21634. */
  21635. set: function (value) {
  21636. this._intensityMode = value;
  21637. this._computePhotometricScale();
  21638. },
  21639. enumerable: true,
  21640. configurable: true
  21641. });
  21642. ;
  21643. ;
  21644. Object.defineProperty(Light.prototype, "radius", {
  21645. /**
  21646. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21647. */
  21648. get: function () {
  21649. return this._radius;
  21650. },
  21651. /**
  21652. * sets the light radius used by PBR Materials to simulate soft area lights.
  21653. */
  21654. set: function (value) {
  21655. this._radius = value;
  21656. this._computePhotometricScale();
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. ;
  21662. ;
  21663. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21664. /**
  21665. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21666. * the current shadow generator.
  21667. */
  21668. get: function () {
  21669. return this._shadowEnabled;
  21670. },
  21671. /**
  21672. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21673. * the current shadow generator.
  21674. */
  21675. set: function (value) {
  21676. if (this._shadowEnabled === value) {
  21677. return;
  21678. }
  21679. this._shadowEnabled = value;
  21680. this._markMeshesAsLightDirty();
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21686. /**
  21687. * Gets the only meshes impacted by this light.
  21688. */
  21689. get: function () {
  21690. return this._includedOnlyMeshes;
  21691. },
  21692. /**
  21693. * Sets the only meshes impacted by this light.
  21694. */
  21695. set: function (value) {
  21696. this._includedOnlyMeshes = value;
  21697. this._hookArrayForIncludedOnly(value);
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21703. /**
  21704. * Gets the meshes not impacted by this light.
  21705. */
  21706. get: function () {
  21707. return this._excludedMeshes;
  21708. },
  21709. /**
  21710. * Sets the meshes not impacted by this light.
  21711. */
  21712. set: function (value) {
  21713. this._excludedMeshes = value;
  21714. this._hookArrayForExcluded(value);
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21720. /**
  21721. * Gets the layer id use to find what meshes are not impacted by the light.
  21722. * Inactive if 0
  21723. */
  21724. get: function () {
  21725. return this._excludeWithLayerMask;
  21726. },
  21727. /**
  21728. * Sets the layer id use to find what meshes are not impacted by the light.
  21729. * Inactive if 0
  21730. */
  21731. set: function (value) {
  21732. this._excludeWithLayerMask = value;
  21733. this._resyncMeshes();
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21739. /**
  21740. * Gets the layer id use to find what meshes are impacted by the light.
  21741. * Inactive if 0
  21742. */
  21743. get: function () {
  21744. return this._includeOnlyWithLayerMask;
  21745. },
  21746. /**
  21747. * Sets the layer id use to find what meshes are impacted by the light.
  21748. * Inactive if 0
  21749. */
  21750. set: function (value) {
  21751. this._includeOnlyWithLayerMask = value;
  21752. this._resyncMeshes();
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. Object.defineProperty(Light.prototype, "lightmapMode", {
  21758. /**
  21759. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21760. */
  21761. get: function () {
  21762. return this._lightmapMode;
  21763. },
  21764. /**
  21765. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21766. */
  21767. set: function (value) {
  21768. if (this._lightmapMode === value) {
  21769. return;
  21770. }
  21771. this._lightmapMode = value;
  21772. this._markMeshesAsLightDirty();
  21773. },
  21774. enumerable: true,
  21775. configurable: true
  21776. });
  21777. /**
  21778. * Returns the string "Light".
  21779. * @returns the class name
  21780. */
  21781. Light.prototype.getClassName = function () {
  21782. return "Light";
  21783. };
  21784. /**
  21785. * Converts the light information to a readable string for debug purpose.
  21786. * @param fullDetails Supports for multiple levels of logging within scene loading
  21787. * @returns the human readable light info
  21788. */
  21789. Light.prototype.toString = function (fullDetails) {
  21790. var ret = "Name: " + this.name;
  21791. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21792. if (this.animations) {
  21793. for (var i = 0; i < this.animations.length; i++) {
  21794. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21795. }
  21796. }
  21797. if (fullDetails) {
  21798. }
  21799. return ret;
  21800. };
  21801. /**
  21802. * Set the enabled state of this node.
  21803. * @param value - the new enabled state
  21804. */
  21805. Light.prototype.setEnabled = function (value) {
  21806. _super.prototype.setEnabled.call(this, value);
  21807. this._resyncMeshes();
  21808. };
  21809. /**
  21810. * Returns the Light associated shadow generator if any.
  21811. * @return the associated shadow generator.
  21812. */
  21813. Light.prototype.getShadowGenerator = function () {
  21814. return this._shadowGenerator;
  21815. };
  21816. /**
  21817. * Returns a Vector3, the absolute light position in the World.
  21818. * @returns the world space position of the light
  21819. */
  21820. Light.prototype.getAbsolutePosition = function () {
  21821. return BABYLON.Vector3.Zero();
  21822. };
  21823. /**
  21824. * Specifies if the light will affect the passed mesh.
  21825. * @param mesh The mesh to test against the light
  21826. * @return true the mesh is affected otherwise, false.
  21827. */
  21828. Light.prototype.canAffectMesh = function (mesh) {
  21829. if (!mesh) {
  21830. return true;
  21831. }
  21832. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21833. return false;
  21834. }
  21835. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21836. return false;
  21837. }
  21838. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21839. return false;
  21840. }
  21841. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21842. return false;
  21843. }
  21844. return true;
  21845. };
  21846. /**
  21847. * Computes and Returns the light World matrix.
  21848. * @returns the world matrix
  21849. */
  21850. Light.prototype.getWorldMatrix = function () {
  21851. this._currentRenderId = this.getScene().getRenderId();
  21852. this._childRenderId = this._currentRenderId;
  21853. var worldMatrix = this._getWorldMatrix();
  21854. if (this.parent && this.parent.getWorldMatrix) {
  21855. if (!this._parentedWorldMatrix) {
  21856. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21857. }
  21858. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21859. this._markSyncedWithParent();
  21860. return this._parentedWorldMatrix;
  21861. }
  21862. return worldMatrix;
  21863. };
  21864. /**
  21865. * Sort function to order lights for rendering.
  21866. * @param a First Light object to compare to second.
  21867. * @param b Second Light object to compare first.
  21868. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21869. */
  21870. Light.CompareLightsPriority = function (a, b) {
  21871. //shadow-casting lights have priority over non-shadow-casting lights
  21872. //the renderPrioirty is a secondary sort criterion
  21873. if (a.shadowEnabled !== b.shadowEnabled) {
  21874. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21875. }
  21876. return b.renderPriority - a.renderPriority;
  21877. };
  21878. /**
  21879. * Releases resources associated with this node.
  21880. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21881. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21882. */
  21883. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21884. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21885. if (this._shadowGenerator) {
  21886. this._shadowGenerator.dispose();
  21887. this._shadowGenerator = null;
  21888. }
  21889. // Animations
  21890. this.getScene().stopAnimation(this);
  21891. // Remove from meshes
  21892. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21893. var mesh = _a[_i];
  21894. mesh._removeLightSource(this);
  21895. }
  21896. this._uniformBuffer.dispose();
  21897. // Remove from scene
  21898. this.getScene().removeLight(this);
  21899. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21900. };
  21901. /**
  21902. * Returns the light type ID (integer).
  21903. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21904. */
  21905. Light.prototype.getTypeID = function () {
  21906. return 0;
  21907. };
  21908. /**
  21909. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21910. * @returns the scaled intensity in intensity mode unit
  21911. */
  21912. Light.prototype.getScaledIntensity = function () {
  21913. return this._photometricScale * this.intensity;
  21914. };
  21915. /**
  21916. * Returns a new Light object, named "name", from the current one.
  21917. * @param name The name of the cloned light
  21918. * @returns the new created light
  21919. */
  21920. Light.prototype.clone = function (name) {
  21921. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21922. if (!constructor) {
  21923. return null;
  21924. }
  21925. return BABYLON.SerializationHelper.Clone(constructor, this);
  21926. };
  21927. /**
  21928. * Serializes the current light into a Serialization object.
  21929. * @returns the serialized object.
  21930. */
  21931. Light.prototype.serialize = function () {
  21932. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21933. // Type
  21934. serializationObject.type = this.getTypeID();
  21935. // Parent
  21936. if (this.parent) {
  21937. serializationObject.parentId = this.parent.id;
  21938. }
  21939. // Inclusion / exclusions
  21940. if (this.excludedMeshes.length > 0) {
  21941. serializationObject.excludedMeshesIds = [];
  21942. this.excludedMeshes.forEach(function (mesh) {
  21943. serializationObject.excludedMeshesIds.push(mesh.id);
  21944. });
  21945. }
  21946. if (this.includedOnlyMeshes.length > 0) {
  21947. serializationObject.includedOnlyMeshesIds = [];
  21948. this.includedOnlyMeshes.forEach(function (mesh) {
  21949. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21950. });
  21951. }
  21952. // Animations
  21953. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21954. serializationObject.ranges = this.serializeAnimationRanges();
  21955. return serializationObject;
  21956. };
  21957. /**
  21958. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21959. * This new light is named "name" and added to the passed scene.
  21960. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21961. * @param name The friendly name of the light
  21962. * @param scene The scene the new light will belong to
  21963. * @returns the constructor function
  21964. */
  21965. Light.GetConstructorFromName = function (type, name, scene) {
  21966. switch (type) {
  21967. case 0:
  21968. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21969. case 1:
  21970. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21971. case 2:
  21972. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21973. case 3:
  21974. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21975. }
  21976. return null;
  21977. };
  21978. /**
  21979. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21980. * @param parsedLight The JSON representation of the light
  21981. * @param scene The scene to create the parsed light in
  21982. * @returns the created light after parsing
  21983. */
  21984. Light.Parse = function (parsedLight, scene) {
  21985. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21986. if (!constructor) {
  21987. return null;
  21988. }
  21989. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21990. // Inclusion / exclusions
  21991. if (parsedLight.excludedMeshesIds) {
  21992. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21993. }
  21994. if (parsedLight.includedOnlyMeshesIds) {
  21995. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21996. }
  21997. // Parent
  21998. if (parsedLight.parentId) {
  21999. light._waitingParentId = parsedLight.parentId;
  22000. }
  22001. // Animations
  22002. if (parsedLight.animations) {
  22003. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22004. var parsedAnimation = parsedLight.animations[animationIndex];
  22005. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22006. }
  22007. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22008. }
  22009. if (parsedLight.autoAnimate) {
  22010. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22011. }
  22012. return light;
  22013. };
  22014. Light.prototype._hookArrayForExcluded = function (array) {
  22015. var _this = this;
  22016. var oldPush = array.push;
  22017. array.push = function () {
  22018. var items = [];
  22019. for (var _i = 0; _i < arguments.length; _i++) {
  22020. items[_i] = arguments[_i];
  22021. }
  22022. var result = oldPush.apply(array, items);
  22023. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22024. var item = items_1[_a];
  22025. item._resyncLighSource(_this);
  22026. }
  22027. return result;
  22028. };
  22029. var oldSplice = array.splice;
  22030. array.splice = function (index, deleteCount) {
  22031. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22032. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22033. var item = deleted_1[_i];
  22034. item._resyncLighSource(_this);
  22035. }
  22036. return deleted;
  22037. };
  22038. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22039. var item = array_1[_i];
  22040. item._resyncLighSource(this);
  22041. }
  22042. };
  22043. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22044. var _this = this;
  22045. var oldPush = array.push;
  22046. array.push = function () {
  22047. var items = [];
  22048. for (var _i = 0; _i < arguments.length; _i++) {
  22049. items[_i] = arguments[_i];
  22050. }
  22051. var result = oldPush.apply(array, items);
  22052. _this._resyncMeshes();
  22053. return result;
  22054. };
  22055. var oldSplice = array.splice;
  22056. array.splice = function (index, deleteCount) {
  22057. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22058. _this._resyncMeshes();
  22059. return deleted;
  22060. };
  22061. this._resyncMeshes();
  22062. };
  22063. Light.prototype._resyncMeshes = function () {
  22064. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22065. var mesh = _a[_i];
  22066. mesh._resyncLighSource(this);
  22067. }
  22068. };
  22069. /**
  22070. * Forces the meshes to update their light related information in their rendering used effects
  22071. * @hidden Internal Use Only
  22072. */
  22073. Light.prototype._markMeshesAsLightDirty = function () {
  22074. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22075. var mesh = _a[_i];
  22076. if (mesh._lightSources.indexOf(this) !== -1) {
  22077. mesh._markSubMeshesAsLightDirty();
  22078. }
  22079. }
  22080. };
  22081. /**
  22082. * Recomputes the cached photometric scale if needed.
  22083. */
  22084. Light.prototype._computePhotometricScale = function () {
  22085. this._photometricScale = this._getPhotometricScale();
  22086. this.getScene().resetCachedMaterial();
  22087. };
  22088. /**
  22089. * Returns the Photometric Scale according to the light type and intensity mode.
  22090. */
  22091. Light.prototype._getPhotometricScale = function () {
  22092. var photometricScale = 0.0;
  22093. var lightTypeID = this.getTypeID();
  22094. //get photometric mode
  22095. var photometricMode = this.intensityMode;
  22096. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22097. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22098. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22099. }
  22100. else {
  22101. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22102. }
  22103. }
  22104. //compute photometric scale
  22105. switch (lightTypeID) {
  22106. case Light.LIGHTTYPEID_POINTLIGHT:
  22107. case Light.LIGHTTYPEID_SPOTLIGHT:
  22108. switch (photometricMode) {
  22109. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22110. photometricScale = 1.0 / (4.0 * Math.PI);
  22111. break;
  22112. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22113. photometricScale = 1.0;
  22114. break;
  22115. case Light.INTENSITYMODE_LUMINANCE:
  22116. photometricScale = this.radius * this.radius;
  22117. break;
  22118. }
  22119. break;
  22120. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22121. switch (photometricMode) {
  22122. case Light.INTENSITYMODE_ILLUMINANCE:
  22123. photometricScale = 1.0;
  22124. break;
  22125. case Light.INTENSITYMODE_LUMINANCE:
  22126. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22127. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22128. var apexAngleRadians = this.radius;
  22129. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22130. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22131. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22132. photometricScale = solidAngle;
  22133. break;
  22134. }
  22135. break;
  22136. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22137. // No fall off in hemisperic light.
  22138. photometricScale = 1.0;
  22139. break;
  22140. }
  22141. return photometricScale;
  22142. };
  22143. /**
  22144. * Reorder the light in the scene according to their defined priority.
  22145. * @hidden Internal Use Only
  22146. */
  22147. Light.prototype._reorderLightsInScene = function () {
  22148. var scene = this.getScene();
  22149. if (this._renderPriority != 0) {
  22150. scene.requireLightSorting = true;
  22151. }
  22152. this.getScene().sortLightsByPriority();
  22153. };
  22154. //lightmapMode Consts
  22155. Light._LIGHTMAP_DEFAULT = 0;
  22156. Light._LIGHTMAP_SPECULAR = 1;
  22157. Light._LIGHTMAP_SHADOWSONLY = 2;
  22158. // Intensity Mode Consts
  22159. Light._INTENSITYMODE_AUTOMATIC = 0;
  22160. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22161. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22162. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22163. Light._INTENSITYMODE_LUMINANCE = 4;
  22164. // Light types ids const.
  22165. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22166. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22167. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22168. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22169. __decorate([
  22170. BABYLON.serializeAsColor3()
  22171. ], Light.prototype, "diffuse", void 0);
  22172. __decorate([
  22173. BABYLON.serializeAsColor3()
  22174. ], Light.prototype, "specular", void 0);
  22175. __decorate([
  22176. BABYLON.serialize()
  22177. ], Light.prototype, "intensity", void 0);
  22178. __decorate([
  22179. BABYLON.serialize()
  22180. ], Light.prototype, "range", void 0);
  22181. __decorate([
  22182. BABYLON.serialize()
  22183. ], Light.prototype, "intensityMode", null);
  22184. __decorate([
  22185. BABYLON.serialize()
  22186. ], Light.prototype, "radius", null);
  22187. __decorate([
  22188. BABYLON.serialize()
  22189. ], Light.prototype, "_renderPriority", void 0);
  22190. __decorate([
  22191. BABYLON.expandToProperty("_reorderLightsInScene")
  22192. ], Light.prototype, "renderPriority", void 0);
  22193. __decorate([
  22194. BABYLON.serialize("shadowEnabled")
  22195. ], Light.prototype, "_shadowEnabled", void 0);
  22196. __decorate([
  22197. BABYLON.serialize("excludeWithLayerMask")
  22198. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22199. __decorate([
  22200. BABYLON.serialize("includeOnlyWithLayerMask")
  22201. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22202. __decorate([
  22203. BABYLON.serialize("lightmapMode")
  22204. ], Light.prototype, "_lightmapMode", void 0);
  22205. return Light;
  22206. }(BABYLON.Node));
  22207. BABYLON.Light = Light;
  22208. })(BABYLON || (BABYLON = {}));
  22209. //# sourceMappingURL=babylon.light.js.map
  22210. var BABYLON;
  22211. (function (BABYLON) {
  22212. var Camera = /** @class */ (function (_super) {
  22213. __extends(Camera, _super);
  22214. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22215. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22216. var _this = _super.call(this, name, scene) || this;
  22217. /**
  22218. * The vector the camera should consider as up.
  22219. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22220. */
  22221. _this.upVector = BABYLON.Vector3.Up();
  22222. _this.orthoLeft = null;
  22223. _this.orthoRight = null;
  22224. _this.orthoBottom = null;
  22225. _this.orthoTop = null;
  22226. /**
  22227. * FOV is set in Radians. (default is 0.8)
  22228. */
  22229. _this.fov = 0.8;
  22230. _this.minZ = 1;
  22231. _this.maxZ = 10000.0;
  22232. _this.inertia = 0.9;
  22233. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22234. _this.isIntermediate = false;
  22235. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22236. /**
  22237. * Restricts the camera to viewing objects with the same layerMask.
  22238. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22239. */
  22240. _this.layerMask = 0x0FFFFFFF;
  22241. /**
  22242. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22243. */
  22244. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22245. // Camera rig members
  22246. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22247. _this._rigCameras = new Array();
  22248. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22249. _this._skipRendering = false;
  22250. _this.customRenderTargets = new Array();
  22251. // Observables
  22252. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22253. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22254. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22255. _this.onRestoreStateObservable = new BABYLON.Observable();
  22256. // Cache
  22257. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22258. _this._projectionMatrix = new BABYLON.Matrix();
  22259. _this._doNotComputeProjectionMatrix = false;
  22260. _this._worldMatrix = BABYLON.Matrix.Identity();
  22261. _this._postProcesses = new Array();
  22262. _this._transformMatrix = BABYLON.Matrix.Zero();
  22263. _this._activeMeshes = new BABYLON.SmartArray(256);
  22264. _this._globalPosition = BABYLON.Vector3.Zero();
  22265. _this._refreshFrustumPlanes = true;
  22266. _this.getScene().addCamera(_this);
  22267. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22268. _this.getScene().activeCamera = _this;
  22269. }
  22270. _this.position = position;
  22271. return _this;
  22272. }
  22273. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22274. get: function () {
  22275. return Camera._PERSPECTIVE_CAMERA;
  22276. },
  22277. enumerable: true,
  22278. configurable: true
  22279. });
  22280. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22281. get: function () {
  22282. return Camera._ORTHOGRAPHIC_CAMERA;
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22288. /**
  22289. * This is the default FOV mode for perspective cameras.
  22290. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22291. *
  22292. */
  22293. get: function () {
  22294. return Camera._FOVMODE_VERTICAL_FIXED;
  22295. },
  22296. enumerable: true,
  22297. configurable: true
  22298. });
  22299. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22300. /**
  22301. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22302. *
  22303. */
  22304. get: function () {
  22305. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22311. get: function () {
  22312. return Camera._RIG_MODE_NONE;
  22313. },
  22314. enumerable: true,
  22315. configurable: true
  22316. });
  22317. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22318. get: function () {
  22319. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22325. get: function () {
  22326. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22327. },
  22328. enumerable: true,
  22329. configurable: true
  22330. });
  22331. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22332. get: function () {
  22333. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22334. },
  22335. enumerable: true,
  22336. configurable: true
  22337. });
  22338. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22339. get: function () {
  22340. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22341. },
  22342. enumerable: true,
  22343. configurable: true
  22344. });
  22345. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22346. get: function () {
  22347. return Camera._RIG_MODE_VR;
  22348. },
  22349. enumerable: true,
  22350. configurable: true
  22351. });
  22352. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22353. get: function () {
  22354. return Camera._RIG_MODE_WEBVR;
  22355. },
  22356. enumerable: true,
  22357. configurable: true
  22358. });
  22359. /**
  22360. * Store current camera state (fov, position, etc..)
  22361. */
  22362. Camera.prototype.storeState = function () {
  22363. this._stateStored = true;
  22364. this._storedFov = this.fov;
  22365. return this;
  22366. };
  22367. /**
  22368. * Restores the camera state values if it has been stored. You must call storeState() first
  22369. */
  22370. Camera.prototype._restoreStateValues = function () {
  22371. if (!this._stateStored) {
  22372. return false;
  22373. }
  22374. this.fov = this._storedFov;
  22375. return true;
  22376. };
  22377. /**
  22378. * Restored camera state. You must call storeState() first
  22379. */
  22380. Camera.prototype.restoreState = function () {
  22381. if (this._restoreStateValues()) {
  22382. this.onRestoreStateObservable.notifyObservers(this);
  22383. return true;
  22384. }
  22385. return false;
  22386. };
  22387. Camera.prototype.getClassName = function () {
  22388. return "Camera";
  22389. };
  22390. /**
  22391. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22392. */
  22393. Camera.prototype.toString = function (fullDetails) {
  22394. var ret = "Name: " + this.name;
  22395. ret += ", type: " + this.getClassName();
  22396. if (this.animations) {
  22397. for (var i = 0; i < this.animations.length; i++) {
  22398. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22399. }
  22400. }
  22401. if (fullDetails) {
  22402. }
  22403. return ret;
  22404. };
  22405. Object.defineProperty(Camera.prototype, "globalPosition", {
  22406. get: function () {
  22407. return this._globalPosition;
  22408. },
  22409. enumerable: true,
  22410. configurable: true
  22411. });
  22412. Camera.prototype.getActiveMeshes = function () {
  22413. return this._activeMeshes;
  22414. };
  22415. Camera.prototype.isActiveMesh = function (mesh) {
  22416. return (this._activeMeshes.indexOf(mesh) !== -1);
  22417. };
  22418. /**
  22419. * Is this camera ready to be used/rendered
  22420. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22421. * @return true if the camera is ready
  22422. */
  22423. Camera.prototype.isReady = function (completeCheck) {
  22424. if (completeCheck === void 0) { completeCheck = false; }
  22425. if (completeCheck) {
  22426. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22427. var pp = _a[_i];
  22428. if (pp && !pp.isReady()) {
  22429. return false;
  22430. }
  22431. }
  22432. }
  22433. return _super.prototype.isReady.call(this, completeCheck);
  22434. };
  22435. //Cache
  22436. Camera.prototype._initCache = function () {
  22437. _super.prototype._initCache.call(this);
  22438. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22439. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22440. this._cache.mode = undefined;
  22441. this._cache.minZ = undefined;
  22442. this._cache.maxZ = undefined;
  22443. this._cache.fov = undefined;
  22444. this._cache.fovMode = undefined;
  22445. this._cache.aspectRatio = undefined;
  22446. this._cache.orthoLeft = undefined;
  22447. this._cache.orthoRight = undefined;
  22448. this._cache.orthoBottom = undefined;
  22449. this._cache.orthoTop = undefined;
  22450. this._cache.renderWidth = undefined;
  22451. this._cache.renderHeight = undefined;
  22452. };
  22453. Camera.prototype._updateCache = function (ignoreParentClass) {
  22454. if (!ignoreParentClass) {
  22455. _super.prototype._updateCache.call(this);
  22456. }
  22457. this._cache.position.copyFrom(this.position);
  22458. this._cache.upVector.copyFrom(this.upVector);
  22459. };
  22460. // Synchronized
  22461. Camera.prototype._isSynchronized = function () {
  22462. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22463. };
  22464. Camera.prototype._isSynchronizedViewMatrix = function () {
  22465. if (!_super.prototype._isSynchronized.call(this))
  22466. return false;
  22467. return this._cache.position.equals(this.position)
  22468. && this._cache.upVector.equals(this.upVector)
  22469. && this.isSynchronizedWithParent();
  22470. };
  22471. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22472. var check = this._cache.mode === this.mode
  22473. && this._cache.minZ === this.minZ
  22474. && this._cache.maxZ === this.maxZ;
  22475. if (!check) {
  22476. return false;
  22477. }
  22478. var engine = this.getEngine();
  22479. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22480. check = this._cache.fov === this.fov
  22481. && this._cache.fovMode === this.fovMode
  22482. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22483. }
  22484. else {
  22485. check = this._cache.orthoLeft === this.orthoLeft
  22486. && this._cache.orthoRight === this.orthoRight
  22487. && this._cache.orthoBottom === this.orthoBottom
  22488. && this._cache.orthoTop === this.orthoTop
  22489. && this._cache.renderWidth === engine.getRenderWidth()
  22490. && this._cache.renderHeight === engine.getRenderHeight();
  22491. }
  22492. return check;
  22493. };
  22494. // Controls
  22495. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22496. };
  22497. Camera.prototype.detachControl = function (element) {
  22498. };
  22499. Camera.prototype.update = function () {
  22500. this._checkInputs();
  22501. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22502. this._updateRigCameras();
  22503. }
  22504. };
  22505. Camera.prototype._checkInputs = function () {
  22506. this.onAfterCheckInputsObservable.notifyObservers(this);
  22507. };
  22508. Object.defineProperty(Camera.prototype, "rigCameras", {
  22509. get: function () {
  22510. return this._rigCameras;
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22516. get: function () {
  22517. return this._rigPostProcess;
  22518. },
  22519. enumerable: true,
  22520. configurable: true
  22521. });
  22522. /**
  22523. * Internal, gets the first post proces.
  22524. * @returns the first post process to be run on this camera.
  22525. */
  22526. Camera.prototype._getFirstPostProcess = function () {
  22527. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22528. if (this._postProcesses[ppIndex] !== null) {
  22529. return this._postProcesses[ppIndex];
  22530. }
  22531. }
  22532. return null;
  22533. };
  22534. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22535. // invalidate framebuffer
  22536. var firstPostProcess = this._getFirstPostProcess();
  22537. if (firstPostProcess) {
  22538. firstPostProcess.markTextureDirty();
  22539. }
  22540. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22541. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22542. var cam = this._rigCameras[i];
  22543. var rigPostProcess = cam._rigPostProcess;
  22544. // for VR rig, there does not have to be a post process
  22545. if (rigPostProcess) {
  22546. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22547. if (isPass) {
  22548. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22549. cam.isIntermediate = this._postProcesses.length === 0;
  22550. }
  22551. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22552. rigPostProcess.markTextureDirty();
  22553. }
  22554. else {
  22555. cam._postProcesses = this._postProcesses.slice(0);
  22556. }
  22557. }
  22558. };
  22559. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22560. if (insertAt === void 0) { insertAt = null; }
  22561. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22562. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22563. return 0;
  22564. }
  22565. if (insertAt == null || insertAt < 0) {
  22566. this._postProcesses.push(postProcess);
  22567. }
  22568. else if (this._postProcesses[insertAt] === null) {
  22569. this._postProcesses[insertAt] = postProcess;
  22570. }
  22571. else {
  22572. this._postProcesses.splice(insertAt, 0, postProcess);
  22573. }
  22574. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22575. return this._postProcesses.indexOf(postProcess);
  22576. };
  22577. Camera.prototype.detachPostProcess = function (postProcess) {
  22578. var idx = this._postProcesses.indexOf(postProcess);
  22579. if (idx !== -1) {
  22580. this._postProcesses[idx] = null;
  22581. }
  22582. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22583. };
  22584. Camera.prototype.getWorldMatrix = function () {
  22585. if (this._isSynchronizedViewMatrix()) {
  22586. return this._worldMatrix;
  22587. }
  22588. // Getting the the view matrix will also compute the world matrix.
  22589. this.getViewMatrix();
  22590. return this._worldMatrix;
  22591. };
  22592. Camera.prototype._getViewMatrix = function () {
  22593. return BABYLON.Matrix.Identity();
  22594. };
  22595. Camera.prototype.getViewMatrix = function (force) {
  22596. if (!force && this._isSynchronizedViewMatrix()) {
  22597. return this._computedViewMatrix;
  22598. }
  22599. this.updateCache();
  22600. this._computedViewMatrix = this._getViewMatrix();
  22601. this._currentRenderId = this.getScene().getRenderId();
  22602. this._childRenderId = this._currentRenderId;
  22603. this._refreshFrustumPlanes = true;
  22604. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22605. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22606. }
  22607. this.onViewMatrixChangedObservable.notifyObservers(this);
  22608. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22609. return this._computedViewMatrix;
  22610. };
  22611. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22612. this._doNotComputeProjectionMatrix = true;
  22613. if (projection !== undefined) {
  22614. this._projectionMatrix = projection;
  22615. }
  22616. };
  22617. ;
  22618. Camera.prototype.unfreezeProjectionMatrix = function () {
  22619. this._doNotComputeProjectionMatrix = false;
  22620. };
  22621. ;
  22622. Camera.prototype.getProjectionMatrix = function (force) {
  22623. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22624. return this._projectionMatrix;
  22625. }
  22626. // Cache
  22627. this._cache.mode = this.mode;
  22628. this._cache.minZ = this.minZ;
  22629. this._cache.maxZ = this.maxZ;
  22630. // Matrix
  22631. this._refreshFrustumPlanes = true;
  22632. var engine = this.getEngine();
  22633. var scene = this.getScene();
  22634. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22635. this._cache.fov = this.fov;
  22636. this._cache.fovMode = this.fovMode;
  22637. this._cache.aspectRatio = engine.getAspectRatio(this);
  22638. if (this.minZ <= 0) {
  22639. this.minZ = 0.1;
  22640. }
  22641. if (scene.useRightHandedSystem) {
  22642. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22643. }
  22644. else {
  22645. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22646. }
  22647. }
  22648. else {
  22649. var halfWidth = engine.getRenderWidth() / 2.0;
  22650. var halfHeight = engine.getRenderHeight() / 2.0;
  22651. if (scene.useRightHandedSystem) {
  22652. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22653. }
  22654. else {
  22655. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22656. }
  22657. this._cache.orthoLeft = this.orthoLeft;
  22658. this._cache.orthoRight = this.orthoRight;
  22659. this._cache.orthoBottom = this.orthoBottom;
  22660. this._cache.orthoTop = this.orthoTop;
  22661. this._cache.renderWidth = engine.getRenderWidth();
  22662. this._cache.renderHeight = engine.getRenderHeight();
  22663. }
  22664. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22665. return this._projectionMatrix;
  22666. };
  22667. Camera.prototype.getTranformationMatrix = function () {
  22668. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22669. return this._transformMatrix;
  22670. };
  22671. Camera.prototype.updateFrustumPlanes = function () {
  22672. if (!this._refreshFrustumPlanes) {
  22673. return;
  22674. }
  22675. this.getTranformationMatrix();
  22676. if (!this._frustumPlanes) {
  22677. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22678. }
  22679. else {
  22680. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22681. }
  22682. this._refreshFrustumPlanes = false;
  22683. };
  22684. Camera.prototype.isInFrustum = function (target) {
  22685. this.updateFrustumPlanes();
  22686. return target.isInFrustum(this._frustumPlanes);
  22687. };
  22688. Camera.prototype.isCompletelyInFrustum = function (target) {
  22689. this.updateFrustumPlanes();
  22690. return target.isCompletelyInFrustum(this._frustumPlanes);
  22691. };
  22692. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22693. if (length === void 0) { length = 100; }
  22694. if (!transform) {
  22695. transform = this.getWorldMatrix();
  22696. }
  22697. if (!origin) {
  22698. origin = this.position;
  22699. }
  22700. var forward = new BABYLON.Vector3(0, 0, 1);
  22701. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22702. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22703. return new BABYLON.Ray(origin, direction, length);
  22704. };
  22705. /**
  22706. * Releases resources associated with this node.
  22707. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22708. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22709. */
  22710. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22711. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22712. // Observables
  22713. this.onViewMatrixChangedObservable.clear();
  22714. this.onProjectionMatrixChangedObservable.clear();
  22715. this.onAfterCheckInputsObservable.clear();
  22716. this.onRestoreStateObservable.clear();
  22717. // Inputs
  22718. if (this.inputs) {
  22719. this.inputs.clear();
  22720. }
  22721. // Animations
  22722. this.getScene().stopAnimation(this);
  22723. // Remove from scene
  22724. this.getScene().removeCamera(this);
  22725. while (this._rigCameras.length > 0) {
  22726. var camera = this._rigCameras.pop();
  22727. if (camera) {
  22728. camera.dispose();
  22729. }
  22730. }
  22731. // Postprocesses
  22732. if (this._rigPostProcess) {
  22733. this._rigPostProcess.dispose(this);
  22734. this._rigPostProcess = null;
  22735. this._postProcesses = [];
  22736. }
  22737. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22738. this._rigPostProcess = null;
  22739. this._postProcesses = [];
  22740. }
  22741. else {
  22742. var i = this._postProcesses.length;
  22743. while (--i >= 0) {
  22744. var postProcess = this._postProcesses[i];
  22745. if (postProcess) {
  22746. postProcess.dispose(this);
  22747. }
  22748. }
  22749. }
  22750. // Render targets
  22751. var i = this.customRenderTargets.length;
  22752. while (--i >= 0) {
  22753. this.customRenderTargets[i].dispose();
  22754. }
  22755. this.customRenderTargets = [];
  22756. // Active Meshes
  22757. this._activeMeshes.dispose();
  22758. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22759. };
  22760. Object.defineProperty(Camera.prototype, "leftCamera", {
  22761. // ---- Camera rigs section ----
  22762. get: function () {
  22763. if (this._rigCameras.length < 1) {
  22764. return null;
  22765. }
  22766. return this._rigCameras[0];
  22767. },
  22768. enumerable: true,
  22769. configurable: true
  22770. });
  22771. Object.defineProperty(Camera.prototype, "rightCamera", {
  22772. get: function () {
  22773. if (this._rigCameras.length < 2) {
  22774. return null;
  22775. }
  22776. return this._rigCameras[1];
  22777. },
  22778. enumerable: true,
  22779. configurable: true
  22780. });
  22781. Camera.prototype.getLeftTarget = function () {
  22782. if (this._rigCameras.length < 1) {
  22783. return null;
  22784. }
  22785. return this._rigCameras[0].getTarget();
  22786. };
  22787. Camera.prototype.getRightTarget = function () {
  22788. if (this._rigCameras.length < 2) {
  22789. return null;
  22790. }
  22791. return this._rigCameras[1].getTarget();
  22792. };
  22793. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22794. if (this.cameraRigMode === mode) {
  22795. return;
  22796. }
  22797. while (this._rigCameras.length > 0) {
  22798. var camera = this._rigCameras.pop();
  22799. if (camera) {
  22800. camera.dispose();
  22801. }
  22802. }
  22803. this.cameraRigMode = mode;
  22804. this._cameraRigParams = {};
  22805. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22806. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22807. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22808. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22809. // create the rig cameras, unless none
  22810. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22811. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22812. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22813. if (leftCamera && rightCamera) {
  22814. this._rigCameras.push(leftCamera);
  22815. this._rigCameras.push(rightCamera);
  22816. }
  22817. }
  22818. switch (this.cameraRigMode) {
  22819. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22820. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22821. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22822. break;
  22823. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22824. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22825. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22826. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22827. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22828. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22829. break;
  22830. case Camera.RIG_MODE_VR:
  22831. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22832. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22833. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22834. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22835. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22836. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22837. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22838. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22839. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22840. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22841. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22842. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22843. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22844. if (metrics.compensateDistortion) {
  22845. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22846. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22847. }
  22848. break;
  22849. case Camera.RIG_MODE_WEBVR:
  22850. if (rigParams.vrDisplay) {
  22851. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22852. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22853. //Left eye
  22854. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22855. this._rigCameras[0].setCameraRigParameter("left", true);
  22856. //leaving this for future reference
  22857. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22858. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22859. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22860. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22861. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22862. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22863. this._rigCameras[0].parent = this;
  22864. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22865. //Right eye
  22866. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22867. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22868. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22869. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22870. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22871. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22872. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22873. this._rigCameras[1].parent = this;
  22874. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22875. if (Camera.UseAlternateWebVRRendering) {
  22876. this._rigCameras[1]._skipRendering = true;
  22877. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22878. }
  22879. }
  22880. break;
  22881. }
  22882. this._cascadePostProcessesToRigCams();
  22883. this.update();
  22884. };
  22885. Camera.prototype._getVRProjectionMatrix = function () {
  22886. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22887. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22888. return this._projectionMatrix;
  22889. };
  22890. Camera.prototype._updateCameraRotationMatrix = function () {
  22891. //Here for WebVR
  22892. };
  22893. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22894. //Here for WebVR
  22895. };
  22896. /**
  22897. * This function MUST be overwritten by the different WebVR cameras available.
  22898. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22899. */
  22900. Camera.prototype._getWebVRProjectionMatrix = function () {
  22901. return BABYLON.Matrix.Identity();
  22902. };
  22903. /**
  22904. * This function MUST be overwritten by the different WebVR cameras available.
  22905. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22906. */
  22907. Camera.prototype._getWebVRViewMatrix = function () {
  22908. return BABYLON.Matrix.Identity();
  22909. };
  22910. Camera.prototype.setCameraRigParameter = function (name, value) {
  22911. if (!this._cameraRigParams) {
  22912. this._cameraRigParams = {};
  22913. }
  22914. this._cameraRigParams[name] = value;
  22915. //provisionnally:
  22916. if (name === "interaxialDistance") {
  22917. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22918. }
  22919. };
  22920. /**
  22921. * needs to be overridden by children so sub has required properties to be copied
  22922. */
  22923. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22924. return null;
  22925. };
  22926. /**
  22927. * May need to be overridden by children
  22928. */
  22929. Camera.prototype._updateRigCameras = function () {
  22930. for (var i = 0; i < this._rigCameras.length; i++) {
  22931. this._rigCameras[i].minZ = this.minZ;
  22932. this._rigCameras[i].maxZ = this.maxZ;
  22933. this._rigCameras[i].fov = this.fov;
  22934. }
  22935. // only update viewport when ANAGLYPH
  22936. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22937. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22938. }
  22939. };
  22940. Camera.prototype._setupInputs = function () {
  22941. };
  22942. Camera.prototype.serialize = function () {
  22943. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22944. // Type
  22945. serializationObject.type = this.getClassName();
  22946. // Parent
  22947. if (this.parent) {
  22948. serializationObject.parentId = this.parent.id;
  22949. }
  22950. if (this.inputs) {
  22951. this.inputs.serialize(serializationObject);
  22952. }
  22953. // Animations
  22954. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22955. serializationObject.ranges = this.serializeAnimationRanges();
  22956. return serializationObject;
  22957. };
  22958. Camera.prototype.clone = function (name) {
  22959. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22960. };
  22961. Camera.prototype.getDirection = function (localAxis) {
  22962. var result = BABYLON.Vector3.Zero();
  22963. this.getDirectionToRef(localAxis, result);
  22964. return result;
  22965. };
  22966. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22967. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22968. };
  22969. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22970. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22971. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22972. switch (type) {
  22973. case "ArcRotateCamera":
  22974. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22975. case "DeviceOrientationCamera":
  22976. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22977. case "FollowCamera":
  22978. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22979. case "ArcFollowCamera":
  22980. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22981. case "GamepadCamera":
  22982. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22983. case "TouchCamera":
  22984. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22985. case "VirtualJoysticksCamera":
  22986. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22987. case "WebVRFreeCamera":
  22988. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22989. case "WebVRGamepadCamera":
  22990. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22991. case "VRDeviceOrientationFreeCamera":
  22992. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22993. case "VRDeviceOrientationGamepadCamera":
  22994. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22995. case "AnaglyphArcRotateCamera":
  22996. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22997. case "AnaglyphFreeCamera":
  22998. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22999. case "AnaglyphGamepadCamera":
  23000. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23001. case "AnaglyphUniversalCamera":
  23002. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23003. case "StereoscopicArcRotateCamera":
  23004. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23005. case "StereoscopicFreeCamera":
  23006. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23007. case "StereoscopicGamepadCamera":
  23008. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23009. case "StereoscopicUniversalCamera":
  23010. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23011. case "FreeCamera": // Forcing Universal here
  23012. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23013. default: // Universal Camera is the default value
  23014. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23015. }
  23016. };
  23017. Camera.prototype.computeWorldMatrix = function () {
  23018. return this.getWorldMatrix();
  23019. };
  23020. Camera.Parse = function (parsedCamera, scene) {
  23021. var type = parsedCamera.type;
  23022. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23023. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23024. // Parent
  23025. if (parsedCamera.parentId) {
  23026. camera._waitingParentId = parsedCamera.parentId;
  23027. }
  23028. //If camera has an input manager, let it parse inputs settings
  23029. if (camera.inputs) {
  23030. camera.inputs.parse(parsedCamera);
  23031. camera._setupInputs();
  23032. }
  23033. if (camera.setPosition) { // need to force position
  23034. camera.position.copyFromFloats(0, 0, 0);
  23035. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23036. }
  23037. // Target
  23038. if (parsedCamera.target) {
  23039. if (camera.setTarget) {
  23040. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23041. }
  23042. }
  23043. // Apply 3d rig, when found
  23044. if (parsedCamera.cameraRigMode) {
  23045. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23046. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23047. }
  23048. // Animations
  23049. if (parsedCamera.animations) {
  23050. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23051. var parsedAnimation = parsedCamera.animations[animationIndex];
  23052. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23053. }
  23054. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23055. }
  23056. if (parsedCamera.autoAnimate) {
  23057. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23058. }
  23059. return camera;
  23060. };
  23061. // Statics
  23062. Camera._PERSPECTIVE_CAMERA = 0;
  23063. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23064. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23065. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23066. Camera._RIG_MODE_NONE = 0;
  23067. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23068. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23069. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23070. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23071. Camera._RIG_MODE_VR = 20;
  23072. Camera._RIG_MODE_WEBVR = 21;
  23073. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23074. Camera.UseAlternateWebVRRendering = false;
  23075. __decorate([
  23076. BABYLON.serializeAsVector3()
  23077. ], Camera.prototype, "position", void 0);
  23078. __decorate([
  23079. BABYLON.serializeAsVector3()
  23080. ], Camera.prototype, "upVector", void 0);
  23081. __decorate([
  23082. BABYLON.serialize()
  23083. ], Camera.prototype, "orthoLeft", void 0);
  23084. __decorate([
  23085. BABYLON.serialize()
  23086. ], Camera.prototype, "orthoRight", void 0);
  23087. __decorate([
  23088. BABYLON.serialize()
  23089. ], Camera.prototype, "orthoBottom", void 0);
  23090. __decorate([
  23091. BABYLON.serialize()
  23092. ], Camera.prototype, "orthoTop", void 0);
  23093. __decorate([
  23094. BABYLON.serialize()
  23095. ], Camera.prototype, "fov", void 0);
  23096. __decorate([
  23097. BABYLON.serialize()
  23098. ], Camera.prototype, "minZ", void 0);
  23099. __decorate([
  23100. BABYLON.serialize()
  23101. ], Camera.prototype, "maxZ", void 0);
  23102. __decorate([
  23103. BABYLON.serialize()
  23104. ], Camera.prototype, "inertia", void 0);
  23105. __decorate([
  23106. BABYLON.serialize()
  23107. ], Camera.prototype, "mode", void 0);
  23108. __decorate([
  23109. BABYLON.serialize()
  23110. ], Camera.prototype, "layerMask", void 0);
  23111. __decorate([
  23112. BABYLON.serialize()
  23113. ], Camera.prototype, "fovMode", void 0);
  23114. __decorate([
  23115. BABYLON.serialize()
  23116. ], Camera.prototype, "cameraRigMode", void 0);
  23117. __decorate([
  23118. BABYLON.serialize()
  23119. ], Camera.prototype, "interaxialDistance", void 0);
  23120. __decorate([
  23121. BABYLON.serialize()
  23122. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23123. return Camera;
  23124. }(BABYLON.Node));
  23125. BABYLON.Camera = Camera;
  23126. })(BABYLON || (BABYLON = {}));
  23127. //# sourceMappingURL=babylon.camera.js.map
  23128. var BABYLON;
  23129. (function (BABYLON) {
  23130. var RenderingManager = /** @class */ (function () {
  23131. function RenderingManager(scene) {
  23132. this._renderingGroups = new Array();
  23133. this._autoClearDepthStencil = {};
  23134. this._customOpaqueSortCompareFn = {};
  23135. this._customAlphaTestSortCompareFn = {};
  23136. this._customTransparentSortCompareFn = {};
  23137. this._renderinGroupInfo = null;
  23138. this._scene = scene;
  23139. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23140. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23141. }
  23142. }
  23143. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23144. if (depth === void 0) { depth = true; }
  23145. if (stencil === void 0) { stencil = true; }
  23146. if (this._depthStencilBufferAlreadyCleaned) {
  23147. return;
  23148. }
  23149. this._scene.getEngine().clear(null, false, depth, stencil);
  23150. this._depthStencilBufferAlreadyCleaned = true;
  23151. };
  23152. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23153. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23154. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23155. var info = null;
  23156. if (observable) {
  23157. if (!this._renderinGroupInfo) {
  23158. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23159. }
  23160. info = this._renderinGroupInfo;
  23161. info.scene = this._scene;
  23162. info.camera = this._scene.activeCamera;
  23163. }
  23164. // Dispatch sprites
  23165. if (renderSprites) {
  23166. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23167. var manager = this._scene.spriteManagers[index];
  23168. this.dispatchSprites(manager);
  23169. }
  23170. }
  23171. // Render
  23172. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23173. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23174. var renderingGroup = this._renderingGroups[index];
  23175. if (!renderingGroup && !observable)
  23176. continue;
  23177. var renderingGroupMask = 0;
  23178. // Fire PRECLEAR stage
  23179. if (observable && info) {
  23180. renderingGroupMask = Math.pow(2, index);
  23181. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23182. info.renderingGroupId = index;
  23183. observable.notifyObservers(info, renderingGroupMask);
  23184. }
  23185. // Clear depth/stencil if needed
  23186. if (RenderingManager.AUTOCLEAR) {
  23187. var autoClear = this._autoClearDepthStencil[index];
  23188. if (autoClear && autoClear.autoClear) {
  23189. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23190. }
  23191. }
  23192. if (observable && info) {
  23193. // Fire PREOPAQUE stage
  23194. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23195. observable.notifyObservers(info, renderingGroupMask);
  23196. // Fire PRETRANSPARENT stage
  23197. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23198. observable.notifyObservers(info, renderingGroupMask);
  23199. }
  23200. if (renderingGroup)
  23201. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23202. // Fire POSTTRANSPARENT stage
  23203. if (observable && info) {
  23204. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23205. observable.notifyObservers(info, renderingGroupMask);
  23206. }
  23207. }
  23208. };
  23209. RenderingManager.prototype.reset = function () {
  23210. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23211. var renderingGroup = this._renderingGroups[index];
  23212. if (renderingGroup) {
  23213. renderingGroup.prepare();
  23214. }
  23215. }
  23216. };
  23217. RenderingManager.prototype.dispose = function () {
  23218. this.freeRenderingGroups();
  23219. this._renderingGroups.length = 0;
  23220. };
  23221. /**
  23222. * Clear the info related to rendering groups preventing retention points during dispose.
  23223. */
  23224. RenderingManager.prototype.freeRenderingGroups = function () {
  23225. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23226. var renderingGroup = this._renderingGroups[index];
  23227. if (renderingGroup) {
  23228. renderingGroup.dispose();
  23229. }
  23230. }
  23231. };
  23232. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23233. if (this._renderingGroups[renderingGroupId] === undefined) {
  23234. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23235. }
  23236. };
  23237. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23238. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23239. this._prepareRenderingGroup(renderingGroupId);
  23240. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23241. };
  23242. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23243. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23244. this._prepareRenderingGroup(renderingGroupId);
  23245. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23246. };
  23247. /**
  23248. * @param subMesh The submesh to dispatch
  23249. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23250. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23251. */
  23252. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23253. if (mesh === undefined) {
  23254. mesh = subMesh.getMesh();
  23255. }
  23256. var renderingGroupId = mesh.renderingGroupId || 0;
  23257. this._prepareRenderingGroup(renderingGroupId);
  23258. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23259. };
  23260. /**
  23261. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23262. * This allowed control for front to back rendering or reversly depending of the special needs.
  23263. *
  23264. * @param renderingGroupId The rendering group id corresponding to its index
  23265. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23266. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23267. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23268. */
  23269. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23270. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23271. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23272. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23273. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23274. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23275. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23276. if (this._renderingGroups[renderingGroupId]) {
  23277. var group = this._renderingGroups[renderingGroupId];
  23278. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23279. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23280. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23281. }
  23282. };
  23283. /**
  23284. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23285. *
  23286. * @param renderingGroupId The rendering group id corresponding to its index
  23287. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23288. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23289. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23290. */
  23291. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23292. if (depth === void 0) { depth = true; }
  23293. if (stencil === void 0) { stencil = true; }
  23294. this._autoClearDepthStencil[renderingGroupId] = {
  23295. autoClear: autoClearDepthStencil,
  23296. depth: depth,
  23297. stencil: stencil
  23298. };
  23299. };
  23300. /**
  23301. * The max id used for rendering groups (not included)
  23302. */
  23303. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23304. /**
  23305. * The min id used for rendering groups (included)
  23306. */
  23307. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23308. /**
  23309. * Used to globally prevent autoclearing scenes.
  23310. */
  23311. RenderingManager.AUTOCLEAR = true;
  23312. return RenderingManager;
  23313. }());
  23314. BABYLON.RenderingManager = RenderingManager;
  23315. })(BABYLON || (BABYLON = {}));
  23316. //# sourceMappingURL=babylon.renderingManager.js.map
  23317. var BABYLON;
  23318. (function (BABYLON) {
  23319. var RenderingGroup = /** @class */ (function () {
  23320. /**
  23321. * Creates a new rendering group.
  23322. * @param index The rendering group index
  23323. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23324. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23325. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23326. */
  23327. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23328. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23329. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23330. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23331. this.index = index;
  23332. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23333. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23334. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23335. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23336. this._particleSystems = new BABYLON.SmartArray(256);
  23337. this._spriteManagers = new BABYLON.SmartArray(256);
  23338. this._edgesRenderers = new BABYLON.SmartArray(16);
  23339. this._scene = scene;
  23340. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23341. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23342. this.transparentSortCompareFn = transparentSortCompareFn;
  23343. }
  23344. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23345. /**
  23346. * Set the opaque sort comparison function.
  23347. * If null the sub meshes will be render in the order they were created
  23348. */
  23349. set: function (value) {
  23350. this._opaqueSortCompareFn = value;
  23351. if (value) {
  23352. this._renderOpaque = this.renderOpaqueSorted;
  23353. }
  23354. else {
  23355. this._renderOpaque = RenderingGroup.renderUnsorted;
  23356. }
  23357. },
  23358. enumerable: true,
  23359. configurable: true
  23360. });
  23361. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23362. /**
  23363. * Set the alpha test sort comparison function.
  23364. * If null the sub meshes will be render in the order they were created
  23365. */
  23366. set: function (value) {
  23367. this._alphaTestSortCompareFn = value;
  23368. if (value) {
  23369. this._renderAlphaTest = this.renderAlphaTestSorted;
  23370. }
  23371. else {
  23372. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23373. }
  23374. },
  23375. enumerable: true,
  23376. configurable: true
  23377. });
  23378. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23379. /**
  23380. * Set the transparent sort comparison function.
  23381. * If null the sub meshes will be render in the order they were created
  23382. */
  23383. set: function (value) {
  23384. if (value) {
  23385. this._transparentSortCompareFn = value;
  23386. }
  23387. else {
  23388. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23389. }
  23390. this._renderTransparent = this.renderTransparentSorted;
  23391. },
  23392. enumerable: true,
  23393. configurable: true
  23394. });
  23395. /**
  23396. * Render all the sub meshes contained in the group.
  23397. * @param customRenderFunction Used to override the default render behaviour of the group.
  23398. * @returns true if rendered some submeshes.
  23399. */
  23400. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23401. if (customRenderFunction) {
  23402. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23403. return;
  23404. }
  23405. var engine = this._scene.getEngine();
  23406. // Depth only
  23407. if (this._depthOnlySubMeshes.length !== 0) {
  23408. engine.setColorWrite(false);
  23409. this._renderAlphaTest(this._depthOnlySubMeshes);
  23410. engine.setColorWrite(true);
  23411. }
  23412. // Opaque
  23413. if (this._opaqueSubMeshes.length !== 0) {
  23414. this._renderOpaque(this._opaqueSubMeshes);
  23415. }
  23416. // Alpha test
  23417. if (this._alphaTestSubMeshes.length !== 0) {
  23418. this._renderAlphaTest(this._alphaTestSubMeshes);
  23419. }
  23420. var stencilState = engine.getStencilBuffer();
  23421. engine.setStencilBuffer(false);
  23422. // Sprites
  23423. if (renderSprites) {
  23424. this._renderSprites();
  23425. }
  23426. // Particles
  23427. if (renderParticles) {
  23428. this._renderParticles(activeMeshes);
  23429. }
  23430. if (this.onBeforeTransparentRendering) {
  23431. this.onBeforeTransparentRendering();
  23432. }
  23433. // Transparent
  23434. if (this._transparentSubMeshes.length !== 0) {
  23435. this._renderTransparent(this._transparentSubMeshes);
  23436. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23437. }
  23438. // Set back stencil to false in case it changes before the edge renderer.
  23439. engine.setStencilBuffer(false);
  23440. // Edges
  23441. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23442. this._edgesRenderers.data[edgesRendererIndex].render();
  23443. }
  23444. // Restore Stencil state.
  23445. engine.setStencilBuffer(stencilState);
  23446. };
  23447. /**
  23448. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23449. * @param subMeshes The submeshes to render
  23450. */
  23451. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23452. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23453. };
  23454. /**
  23455. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23456. * @param subMeshes The submeshes to render
  23457. */
  23458. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23459. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23460. };
  23461. /**
  23462. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23463. * @param subMeshes The submeshes to render
  23464. */
  23465. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23466. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23467. };
  23468. /**
  23469. * Renders the submeshes in a specified order.
  23470. * @param subMeshes The submeshes to sort before render
  23471. * @param sortCompareFn The comparison function use to sort
  23472. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23473. * @param transparent Specifies to activate blending if true
  23474. */
  23475. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23476. var subIndex = 0;
  23477. var subMesh;
  23478. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23479. for (; subIndex < subMeshes.length; subIndex++) {
  23480. subMesh = subMeshes.data[subIndex];
  23481. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23482. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23483. }
  23484. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23485. if (sortCompareFn) {
  23486. sortedArray.sort(sortCompareFn);
  23487. }
  23488. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23489. subMesh = sortedArray[subIndex];
  23490. if (transparent) {
  23491. var material = subMesh.getMaterial();
  23492. if (material && material.needDepthPrePass) {
  23493. var engine = material.getScene().getEngine();
  23494. engine.setColorWrite(false);
  23495. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23496. subMesh.render(false);
  23497. engine.setColorWrite(true);
  23498. }
  23499. }
  23500. subMesh.render(transparent);
  23501. }
  23502. };
  23503. /**
  23504. * Renders the submeshes in the order they were dispatched (no sort applied).
  23505. * @param subMeshes The submeshes to render
  23506. */
  23507. RenderingGroup.renderUnsorted = function (subMeshes) {
  23508. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23509. var submesh = subMeshes.data[subIndex];
  23510. submesh.render(false);
  23511. }
  23512. };
  23513. /**
  23514. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23515. * are rendered back to front if in the same alpha index.
  23516. *
  23517. * @param a The first submesh
  23518. * @param b The second submesh
  23519. * @returns The result of the comparison
  23520. */
  23521. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23522. // Alpha index first
  23523. if (a._alphaIndex > b._alphaIndex) {
  23524. return 1;
  23525. }
  23526. if (a._alphaIndex < b._alphaIndex) {
  23527. return -1;
  23528. }
  23529. // Then distance to camera
  23530. return RenderingGroup.backToFrontSortCompare(a, b);
  23531. };
  23532. /**
  23533. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23534. * are rendered back to front.
  23535. *
  23536. * @param a The first submesh
  23537. * @param b The second submesh
  23538. * @returns The result of the comparison
  23539. */
  23540. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23541. // Then distance to camera
  23542. if (a._distanceToCamera < b._distanceToCamera) {
  23543. return 1;
  23544. }
  23545. if (a._distanceToCamera > b._distanceToCamera) {
  23546. return -1;
  23547. }
  23548. return 0;
  23549. };
  23550. /**
  23551. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23552. * are rendered front to back (prevent overdraw).
  23553. *
  23554. * @param a The first submesh
  23555. * @param b The second submesh
  23556. * @returns The result of the comparison
  23557. */
  23558. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23559. // Then distance to camera
  23560. if (a._distanceToCamera < b._distanceToCamera) {
  23561. return -1;
  23562. }
  23563. if (a._distanceToCamera > b._distanceToCamera) {
  23564. return 1;
  23565. }
  23566. return 0;
  23567. };
  23568. /**
  23569. * Resets the different lists of submeshes to prepare a new frame.
  23570. */
  23571. RenderingGroup.prototype.prepare = function () {
  23572. this._opaqueSubMeshes.reset();
  23573. this._transparentSubMeshes.reset();
  23574. this._alphaTestSubMeshes.reset();
  23575. this._depthOnlySubMeshes.reset();
  23576. this._particleSystems.reset();
  23577. this._spriteManagers.reset();
  23578. this._edgesRenderers.reset();
  23579. };
  23580. RenderingGroup.prototype.dispose = function () {
  23581. this._opaqueSubMeshes.dispose();
  23582. this._transparentSubMeshes.dispose();
  23583. this._alphaTestSubMeshes.dispose();
  23584. this._depthOnlySubMeshes.dispose();
  23585. this._particleSystems.dispose();
  23586. this._spriteManagers.dispose();
  23587. this._edgesRenderers.dispose();
  23588. };
  23589. /**
  23590. * Inserts the submesh in its correct queue depending on its material.
  23591. * @param subMesh The submesh to dispatch
  23592. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23593. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23594. */
  23595. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23596. // Get mesh and materials if not provided
  23597. if (mesh === undefined) {
  23598. mesh = subMesh.getMesh();
  23599. }
  23600. if (material === undefined) {
  23601. material = subMesh.getMaterial();
  23602. }
  23603. if (material === null || material === undefined) {
  23604. return;
  23605. }
  23606. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23607. this._transparentSubMeshes.push(subMesh);
  23608. }
  23609. else if (material.needAlphaTesting()) { // Alpha test
  23610. if (material.needDepthPrePass) {
  23611. this._depthOnlySubMeshes.push(subMesh);
  23612. }
  23613. this._alphaTestSubMeshes.push(subMesh);
  23614. }
  23615. else {
  23616. if (material.needDepthPrePass) {
  23617. this._depthOnlySubMeshes.push(subMesh);
  23618. }
  23619. this._opaqueSubMeshes.push(subMesh); // Opaque
  23620. }
  23621. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23622. this._edgesRenderers.push(mesh._edgesRenderer);
  23623. }
  23624. };
  23625. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23626. this._spriteManagers.push(spriteManager);
  23627. };
  23628. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23629. this._particleSystems.push(particleSystem);
  23630. };
  23631. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23632. if (this._particleSystems.length === 0) {
  23633. return;
  23634. }
  23635. // Particles
  23636. var activeCamera = this._scene.activeCamera;
  23637. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23638. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23639. var particleSystem = this._particleSystems.data[particleIndex];
  23640. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23641. continue;
  23642. }
  23643. var emitter = particleSystem.emitter;
  23644. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23645. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23646. }
  23647. }
  23648. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23649. };
  23650. RenderingGroup.prototype._renderSprites = function () {
  23651. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23652. return;
  23653. }
  23654. // Sprites
  23655. var activeCamera = this._scene.activeCamera;
  23656. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23657. for (var id = 0; id < this._spriteManagers.length; id++) {
  23658. var spriteManager = this._spriteManagers.data[id];
  23659. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23660. spriteManager.render();
  23661. }
  23662. }
  23663. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23664. };
  23665. return RenderingGroup;
  23666. }());
  23667. BABYLON.RenderingGroup = RenderingGroup;
  23668. })(BABYLON || (BABYLON = {}));
  23669. //# sourceMappingURL=babylon.renderingGroup.js.map
  23670. var BABYLON;
  23671. (function (BABYLON) {
  23672. /** @hidden */
  23673. var ClickInfo = /** @class */ (function () {
  23674. function ClickInfo() {
  23675. this._singleClick = false;
  23676. this._doubleClick = false;
  23677. this._hasSwiped = false;
  23678. this._ignore = false;
  23679. }
  23680. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23681. get: function () {
  23682. return this._singleClick;
  23683. },
  23684. set: function (b) {
  23685. this._singleClick = b;
  23686. },
  23687. enumerable: true,
  23688. configurable: true
  23689. });
  23690. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23691. get: function () {
  23692. return this._doubleClick;
  23693. },
  23694. set: function (b) {
  23695. this._doubleClick = b;
  23696. },
  23697. enumerable: true,
  23698. configurable: true
  23699. });
  23700. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23701. get: function () {
  23702. return this._hasSwiped;
  23703. },
  23704. set: function (b) {
  23705. this._hasSwiped = b;
  23706. },
  23707. enumerable: true,
  23708. configurable: true
  23709. });
  23710. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23711. get: function () {
  23712. return this._ignore;
  23713. },
  23714. set: function (b) {
  23715. this._ignore = b;
  23716. },
  23717. enumerable: true,
  23718. configurable: true
  23719. });
  23720. return ClickInfo;
  23721. }());
  23722. /**
  23723. * This class is used by the onRenderingGroupObservable
  23724. */
  23725. var RenderingGroupInfo = /** @class */ (function () {
  23726. function RenderingGroupInfo() {
  23727. }
  23728. /**
  23729. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23730. * This stage will be fired no matter what
  23731. */
  23732. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23733. /**
  23734. * Called before opaque object are rendered.
  23735. * This stage will be fired only if there's 3D Opaque content to render
  23736. */
  23737. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23738. /**
  23739. * Called after the opaque objects are rendered and before the transparent ones
  23740. * This stage will be fired only if there's 3D transparent content to render
  23741. */
  23742. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23743. /**
  23744. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23745. * This stage will be fired no matter what
  23746. */
  23747. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23748. return RenderingGroupInfo;
  23749. }());
  23750. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23751. /**
  23752. * Represents a scene to be rendered by the engine.
  23753. * @see http://doc.babylonjs.com/features/scene
  23754. */
  23755. var Scene = /** @class */ (function () {
  23756. /**
  23757. * Creates a new Scene
  23758. * @param engine defines the engine to use to render this scene
  23759. */
  23760. function Scene(engine) {
  23761. // Members
  23762. /**
  23763. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23764. */
  23765. this.autoClear = true;
  23766. /**
  23767. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23768. */
  23769. this.autoClearDepthAndStencil = true;
  23770. /**
  23771. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23772. */
  23773. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23774. /**
  23775. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23776. */
  23777. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23778. this._forceWireframe = false;
  23779. this._forcePointsCloud = false;
  23780. /**
  23781. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23782. */
  23783. this.forceShowBoundingBoxes = false;
  23784. /**
  23785. * Gets or sets a boolean indicating if animations are enabled
  23786. */
  23787. this.animationsEnabled = true;
  23788. this._animationPropertiesOverride = null;
  23789. /**
  23790. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23791. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23792. */
  23793. this.useConstantAnimationDeltaTime = false;
  23794. /**
  23795. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23796. * Please note that it requires to run a ray cast through the scene on every frame
  23797. */
  23798. this.constantlyUpdateMeshUnderPointer = false;
  23799. /**
  23800. * Defines the HTML cursor to use when hovering over interactive elements
  23801. */
  23802. this.hoverCursor = "pointer";
  23803. /**
  23804. * Defines the HTML default cursor to use (empty by default)
  23805. */
  23806. this.defaultCursor = "";
  23807. /**
  23808. * This is used to call preventDefault() on pointer down
  23809. * in order to block unwanted artifacts like system double clicks
  23810. */
  23811. this.preventDefaultOnPointerDown = true;
  23812. // Metadata
  23813. /**
  23814. * Gets or sets user defined metadata
  23815. */
  23816. this.metadata = null;
  23817. /**
  23818. * Use this array to add regular expressions used to disable offline support for specific urls
  23819. */
  23820. this.disableOfflineSupportExceptionRules = new Array();
  23821. /**
  23822. * An event triggered when the scene is disposed.
  23823. */
  23824. this.onDisposeObservable = new BABYLON.Observable();
  23825. this._onDisposeObserver = null;
  23826. /**
  23827. * An event triggered before rendering the scene (right after animations and physics)
  23828. */
  23829. this.onBeforeRenderObservable = new BABYLON.Observable();
  23830. this._onBeforeRenderObserver = null;
  23831. /**
  23832. * An event triggered after rendering the scene
  23833. */
  23834. this.onAfterRenderObservable = new BABYLON.Observable();
  23835. this._onAfterRenderObserver = null;
  23836. /**
  23837. * An event triggered before animating the scene
  23838. */
  23839. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23840. /**
  23841. * An event triggered after animations processing
  23842. */
  23843. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23844. /**
  23845. * An event triggered before draw calls are ready to be sent
  23846. */
  23847. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23848. /**
  23849. * An event triggered after draw calls have been sent
  23850. */
  23851. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23852. /**
  23853. * An event triggered when physic simulation is about to be run
  23854. */
  23855. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23856. /**
  23857. * An event triggered when physic simulation has been done
  23858. */
  23859. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23860. /**
  23861. * An event triggered when the scene is ready
  23862. */
  23863. this.onReadyObservable = new BABYLON.Observable();
  23864. /**
  23865. * An event triggered before rendering a camera
  23866. */
  23867. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23868. this._onBeforeCameraRenderObserver = null;
  23869. /**
  23870. * An event triggered after rendering a camera
  23871. */
  23872. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23873. this._onAfterCameraRenderObserver = null;
  23874. /**
  23875. * An event triggered when active meshes evaluation is about to start
  23876. */
  23877. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23878. /**
  23879. * An event triggered when active meshes evaluation is done
  23880. */
  23881. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23882. /**
  23883. * An event triggered when particles rendering is about to start
  23884. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23885. */
  23886. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23887. /**
  23888. * An event triggered when particles rendering is done
  23889. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23890. */
  23891. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23892. /**
  23893. * An event triggered when sprites rendering is about to start
  23894. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23895. */
  23896. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23897. /**
  23898. * An event triggered when sprites rendering is done
  23899. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23900. */
  23901. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23904. */
  23905. this.onDataLoadedObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered when a camera is created
  23908. */
  23909. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered when a camera is removed
  23912. */
  23913. this.onCameraRemovedObservable = new BABYLON.Observable();
  23914. /**
  23915. * An event triggered when a light is created
  23916. */
  23917. this.onNewLightAddedObservable = new BABYLON.Observable();
  23918. /**
  23919. * An event triggered when a light is removed
  23920. */
  23921. this.onLightRemovedObservable = new BABYLON.Observable();
  23922. /**
  23923. * An event triggered when a geometry is created
  23924. */
  23925. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23926. /**
  23927. * An event triggered when a geometry is removed
  23928. */
  23929. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23930. /**
  23931. * An event triggered when a transform node is created
  23932. */
  23933. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23934. /**
  23935. * An event triggered when a transform node is removed
  23936. */
  23937. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23938. /**
  23939. * An event triggered when a mesh is created
  23940. */
  23941. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23942. /**
  23943. * An event triggered when a mesh is removed
  23944. */
  23945. this.onMeshRemovedObservable = new BABYLON.Observable();
  23946. /**
  23947. * An event triggered when render targets are about to be rendered
  23948. * Can happen multiple times per frame.
  23949. */
  23950. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23951. /**
  23952. * An event triggered when render targets were rendered.
  23953. * Can happen multiple times per frame.
  23954. */
  23955. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23956. /**
  23957. * An event triggered before calculating deterministic simulation step
  23958. */
  23959. this.onBeforeStepObservable = new BABYLON.Observable();
  23960. /**
  23961. * An event triggered after calculating deterministic simulation step
  23962. */
  23963. this.onAfterStepObservable = new BABYLON.Observable();
  23964. /**
  23965. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23966. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23967. * 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)
  23968. */
  23969. this.onRenderingGroupObservable = new BABYLON.Observable();
  23970. // Animations
  23971. /**
  23972. * Gets a list of Animations associated with the scene
  23973. */
  23974. this.animations = [];
  23975. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23976. /**
  23977. * 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).
  23978. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23979. */
  23980. this.onPrePointerObservable = new BABYLON.Observable();
  23981. /**
  23982. * Observable event triggered each time an input event is received from the rendering canvas
  23983. */
  23984. this.onPointerObservable = new BABYLON.Observable();
  23985. this._meshPickProceed = false;
  23986. this._currentPickResult = null;
  23987. this._previousPickResult = null;
  23988. this._totalPointersPressed = 0;
  23989. this._doubleClickOccured = false;
  23990. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23991. this.cameraToUseForPointers = null;
  23992. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23993. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23994. this._startingPointerTime = 0;
  23995. this._previousStartingPointerTime = 0;
  23996. this._pointerCaptures = {};
  23997. // Deterministic lockstep
  23998. this._timeAccumulator = 0;
  23999. this._currentStepId = 0;
  24000. this._currentInternalStep = 0;
  24001. // Keyboard
  24002. /**
  24003. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24004. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24005. */
  24006. this.onPreKeyboardObservable = new BABYLON.Observable();
  24007. /**
  24008. * Observable event triggered each time an keyboard event is received from the hosting window
  24009. */
  24010. this.onKeyboardObservable = new BABYLON.Observable();
  24011. // Coordinates system
  24012. this._useRightHandedSystem = false;
  24013. // Fog
  24014. this._fogEnabled = true;
  24015. this._fogMode = Scene.FOGMODE_NONE;
  24016. /**
  24017. * Gets or sets the fog color to use
  24018. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24019. */
  24020. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24021. /**
  24022. * Gets or sets the fog density to use
  24023. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24024. */
  24025. this.fogDensity = 0.1;
  24026. /**
  24027. * Gets or sets the fog start distance to use
  24028. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24029. */
  24030. this.fogStart = 0;
  24031. /**
  24032. * Gets or sets the fog end distance to use
  24033. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24034. */
  24035. this.fogEnd = 1000.0;
  24036. // Lights
  24037. this._shadowsEnabled = true;
  24038. this._lightsEnabled = true;
  24039. /**
  24040. * All of the lights added to this scene
  24041. * @see http://doc.babylonjs.com/babylon101/lights
  24042. */
  24043. this.lights = new Array();
  24044. // Cameras
  24045. /** All of the cameras added to this scene.
  24046. * @see http://doc.babylonjs.com/babylon101/cameras
  24047. */
  24048. this.cameras = new Array();
  24049. /** All of the active cameras added to this scene. */
  24050. this.activeCameras = new Array();
  24051. // Meshes
  24052. /**
  24053. * All of the tranform nodes added to this scene
  24054. * @see http://doc.babylonjs.com/how_to/transformnode
  24055. */
  24056. this.transformNodes = new Array();
  24057. /**
  24058. * All of the (abstract) meshes added to this scene
  24059. */
  24060. this.meshes = new Array();
  24061. /**
  24062. * All of the animation groups added to this scene
  24063. * @see http://doc.babylonjs.com/how_to/group
  24064. */
  24065. this.animationGroups = new Array();
  24066. // Geometries
  24067. this._geometries = new Array();
  24068. /**
  24069. * All of the materials added to this scene
  24070. * @see http://doc.babylonjs.com/babylon101/materials
  24071. */
  24072. this.materials = new Array();
  24073. /**
  24074. * All of the multi-materials added to this scene
  24075. * @see http://doc.babylonjs.com/how_to/multi_materials
  24076. */
  24077. this.multiMaterials = new Array();
  24078. // Textures
  24079. this._texturesEnabled = true;
  24080. /**
  24081. * All of the textures added to this scene
  24082. */
  24083. this.textures = new Array();
  24084. // Particles
  24085. /**
  24086. * Gets or sets a boolean indicating if particles are enabled on this scene
  24087. */
  24088. this.particlesEnabled = true;
  24089. /**
  24090. * All of the particle systems added to this scene
  24091. * @see http://doc.babylonjs.com/babylon101/particles
  24092. */
  24093. this.particleSystems = new Array();
  24094. // Sprites
  24095. /**
  24096. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24097. */
  24098. this.spritesEnabled = true;
  24099. /**
  24100. * All of the sprite managers added to this scene
  24101. * @see http://doc.babylonjs.com/babylon101/sprites
  24102. */
  24103. this.spriteManagers = new Array();
  24104. /**
  24105. * The list of layers (background and foreground) of the scene
  24106. */
  24107. this.layers = new Array();
  24108. /**
  24109. * The list of effect layers (highlights/glow) added to the scene
  24110. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24111. * @see http://doc.babylonjs.com/how_to/glow_layer
  24112. */
  24113. this.effectLayers = new Array();
  24114. // Skeletons
  24115. this._skeletonsEnabled = true;
  24116. /**
  24117. * The list of skeletons added to the scene
  24118. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24119. */
  24120. this.skeletons = new Array();
  24121. // Morph targets
  24122. /**
  24123. * The list of morph target managers added to the scene
  24124. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24125. */
  24126. this.morphTargetManagers = new Array();
  24127. // Lens flares
  24128. /**
  24129. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24130. */
  24131. this.lensFlaresEnabled = true;
  24132. /**
  24133. * The list of lens flare system added to the scene
  24134. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24135. */
  24136. this.lensFlareSystems = new Array();
  24137. // Collisions
  24138. /**
  24139. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24140. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24141. */
  24142. this.collisionsEnabled = true;
  24143. /**
  24144. * Defines the gravity applied to this scene (used only for collisions)
  24145. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24146. */
  24147. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24148. // Postprocesses
  24149. /**
  24150. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24151. */
  24152. this.postProcessesEnabled = true;
  24153. /**
  24154. * The list of postprocesses added to the scene
  24155. */
  24156. this.postProcesses = new Array();
  24157. // Customs render targets
  24158. /**
  24159. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24160. */
  24161. this.renderTargetsEnabled = true;
  24162. /**
  24163. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24164. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24165. */
  24166. this.dumpNextRenderTargets = false;
  24167. /**
  24168. * The list of user defined render targets added to the scene
  24169. */
  24170. this.customRenderTargets = new Array();
  24171. /**
  24172. * Gets the list of meshes imported to the scene through SceneLoader
  24173. */
  24174. this.importedMeshesFiles = new Array();
  24175. // Probes
  24176. /**
  24177. * Gets or sets a boolean indicating if probes are enabled on this scene
  24178. */
  24179. this.probesEnabled = true;
  24180. /**
  24181. * The list of reflection probes added to the scene
  24182. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24183. */
  24184. this.reflectionProbes = new Array();
  24185. /** @hidden */
  24186. this._actionManagers = new Array();
  24187. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24188. // Procedural textures
  24189. /**
  24190. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24191. */
  24192. this.proceduralTexturesEnabled = true;
  24193. /**
  24194. * The list of procedural textures added to the scene
  24195. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24196. */
  24197. this.proceduralTextures = new Array();
  24198. /**
  24199. * The list of sound tracks added to the scene
  24200. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24201. */
  24202. this.soundTracks = new Array();
  24203. this._audioEnabled = true;
  24204. this._headphone = false;
  24205. // Performance counters
  24206. this._totalVertices = new BABYLON.PerfCounter();
  24207. /** @hidden */
  24208. this._activeIndices = new BABYLON.PerfCounter();
  24209. /** @hidden */
  24210. this._activeParticles = new BABYLON.PerfCounter();
  24211. /** @hidden */
  24212. this._activeBones = new BABYLON.PerfCounter();
  24213. this._animationTime = 0;
  24214. /**
  24215. * Gets or sets a general scale for animation speed
  24216. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24217. */
  24218. this.animationTimeScale = 1;
  24219. this._renderId = 0;
  24220. this._executeWhenReadyTimeoutId = -1;
  24221. this._intermediateRendering = false;
  24222. this._viewUpdateFlag = -1;
  24223. this._projectionUpdateFlag = -1;
  24224. this._alternateViewUpdateFlag = -1;
  24225. this._alternateProjectionUpdateFlag = -1;
  24226. /** @hidden */
  24227. this._toBeDisposed = new BABYLON.SmartArray(256);
  24228. this._activeRequests = new Array();
  24229. this._pendingData = new Array();
  24230. this._isDisposed = false;
  24231. /**
  24232. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24233. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24234. */
  24235. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24236. this._activeMeshes = new BABYLON.SmartArray(256);
  24237. this._processedMaterials = new BABYLON.SmartArray(256);
  24238. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24239. /** @hidden */
  24240. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24241. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24242. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24243. /** @hidden */
  24244. this._activeAnimatables = new Array();
  24245. this._transformMatrix = BABYLON.Matrix.Zero();
  24246. this._useAlternateCameraConfiguration = false;
  24247. this._alternateRendering = false;
  24248. /**
  24249. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24250. * This is useful if there are more lights that the maximum simulteanous authorized
  24251. */
  24252. this.requireLightSorting = false;
  24253. this._depthRenderer = {};
  24254. this._activeMeshesFrozen = false;
  24255. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24256. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24257. this._engine.scenes.push(this);
  24258. this._uid = null;
  24259. this._renderingManager = new BABYLON.RenderingManager(this);
  24260. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24261. if (BABYLON.OutlineRenderer) {
  24262. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24263. }
  24264. if (BABYLON.Tools.IsWindowObjectExist()) {
  24265. this.attachControl();
  24266. }
  24267. //simplification queue
  24268. if (BABYLON.SimplificationQueue) {
  24269. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24270. }
  24271. //collision coordinator initialization. For now legacy per default.
  24272. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24273. // Uniform Buffer
  24274. this._createUbo();
  24275. // Default Image processing definition.
  24276. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24277. }
  24278. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24279. /** The fog is deactivated */
  24280. get: function () {
  24281. return Scene._FOGMODE_NONE;
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24287. /** The fog density is following an exponential function */
  24288. get: function () {
  24289. return Scene._FOGMODE_EXP;
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24295. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24296. get: function () {
  24297. return Scene._FOGMODE_EXP2;
  24298. },
  24299. enumerable: true,
  24300. configurable: true
  24301. });
  24302. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24303. /** The fog density is following a linear function. */
  24304. get: function () {
  24305. return Scene._FOGMODE_LINEAR;
  24306. },
  24307. enumerable: true,
  24308. configurable: true
  24309. });
  24310. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24311. /**
  24312. * Texture used in all pbr material as the reflection texture.
  24313. * As in the majority of the scene they are the same (exception for multi room and so on),
  24314. * this is easier to reference from here than from all the materials.
  24315. */
  24316. get: function () {
  24317. return this._environmentTexture;
  24318. },
  24319. /**
  24320. * Texture used in all pbr material as the reflection texture.
  24321. * As in the majority of the scene they are the same (exception for multi room and so on),
  24322. * this is easier to set here than in all the materials.
  24323. */
  24324. set: function (value) {
  24325. if (this._environmentTexture === value) {
  24326. return;
  24327. }
  24328. this._environmentTexture = value;
  24329. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24330. },
  24331. enumerable: true,
  24332. configurable: true
  24333. });
  24334. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24335. /**
  24336. * Default image processing configuration used either in the rendering
  24337. * Forward main pass or through the imageProcessingPostProcess if present.
  24338. * As in the majority of the scene they are the same (exception for multi camera),
  24339. * this is easier to reference from here than from all the materials and post process.
  24340. *
  24341. * No setter as we it is a shared configuration, you can set the values instead.
  24342. */
  24343. get: function () {
  24344. return this._imageProcessingConfiguration;
  24345. },
  24346. enumerable: true,
  24347. configurable: true
  24348. });
  24349. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24350. get: function () {
  24351. return this._forceWireframe;
  24352. },
  24353. /**
  24354. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24355. */
  24356. set: function (value) {
  24357. if (this._forceWireframe === value) {
  24358. return;
  24359. }
  24360. this._forceWireframe = value;
  24361. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24367. get: function () {
  24368. return this._forcePointsCloud;
  24369. },
  24370. /**
  24371. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24372. */
  24373. set: function (value) {
  24374. if (this._forcePointsCloud === value) {
  24375. return;
  24376. }
  24377. this._forcePointsCloud = value;
  24378. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24379. },
  24380. enumerable: true,
  24381. configurable: true
  24382. });
  24383. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24384. /**
  24385. * Gets or sets the animation properties override
  24386. */
  24387. get: function () {
  24388. return this._animationPropertiesOverride;
  24389. },
  24390. set: function (value) {
  24391. this._animationPropertiesOverride = value;
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(Scene.prototype, "onDispose", {
  24397. /** Sets a function to be executed when this scene is disposed. */
  24398. set: function (callback) {
  24399. if (this._onDisposeObserver) {
  24400. this.onDisposeObservable.remove(this._onDisposeObserver);
  24401. }
  24402. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24403. },
  24404. enumerable: true,
  24405. configurable: true
  24406. });
  24407. Object.defineProperty(Scene.prototype, "beforeRender", {
  24408. /** Sets a function to be executed before rendering this scene */
  24409. set: function (callback) {
  24410. if (this._onBeforeRenderObserver) {
  24411. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24412. }
  24413. if (callback) {
  24414. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24415. }
  24416. },
  24417. enumerable: true,
  24418. configurable: true
  24419. });
  24420. Object.defineProperty(Scene.prototype, "afterRender", {
  24421. /** Sets a function to be executed after rendering this scene */
  24422. set: function (callback) {
  24423. if (this._onAfterRenderObserver) {
  24424. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24425. }
  24426. if (callback) {
  24427. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24428. }
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24434. /** Sets a function to be executed before rendering a camera*/
  24435. set: function (callback) {
  24436. if (this._onBeforeCameraRenderObserver) {
  24437. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24438. }
  24439. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24440. },
  24441. enumerable: true,
  24442. configurable: true
  24443. });
  24444. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24445. /** Sets a function to be executed after rendering a camera*/
  24446. set: function (callback) {
  24447. if (this._onAfterCameraRenderObserver) {
  24448. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24449. }
  24450. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24456. /**
  24457. * Gets the gamepad manager associated with the scene
  24458. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24459. */
  24460. get: function () {
  24461. if (!this._gamepadManager) {
  24462. this._gamepadManager = new BABYLON.GamepadManager(this);
  24463. }
  24464. return this._gamepadManager;
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24470. /**
  24471. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24472. */
  24473. get: function () {
  24474. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24480. get: function () {
  24481. return this._useRightHandedSystem;
  24482. },
  24483. /**
  24484. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24485. */
  24486. set: function (value) {
  24487. if (this._useRightHandedSystem === value) {
  24488. return;
  24489. }
  24490. this._useRightHandedSystem = value;
  24491. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24492. },
  24493. enumerable: true,
  24494. configurable: true
  24495. });
  24496. /**
  24497. * Sets the step Id used by deterministic lock step
  24498. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24499. * @param newStepId defines the step Id
  24500. */
  24501. Scene.prototype.setStepId = function (newStepId) {
  24502. this._currentStepId = newStepId;
  24503. };
  24504. ;
  24505. /**
  24506. * Gets the step Id used by deterministic lock step
  24507. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24508. * @returns the step Id
  24509. */
  24510. Scene.prototype.getStepId = function () {
  24511. return this._currentStepId;
  24512. };
  24513. ;
  24514. /**
  24515. * Gets the internal step used by deterministic lock step
  24516. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24517. * @returns the internal step
  24518. */
  24519. Scene.prototype.getInternalStep = function () {
  24520. return this._currentInternalStep;
  24521. };
  24522. ;
  24523. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24524. get: function () {
  24525. return this._fogEnabled;
  24526. },
  24527. /**
  24528. * Gets or sets a boolean indicating if fog is enabled on this scene
  24529. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24530. */
  24531. set: function (value) {
  24532. if (this._fogEnabled === value) {
  24533. return;
  24534. }
  24535. this._fogEnabled = value;
  24536. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24537. },
  24538. enumerable: true,
  24539. configurable: true
  24540. });
  24541. Object.defineProperty(Scene.prototype, "fogMode", {
  24542. get: function () {
  24543. return this._fogMode;
  24544. },
  24545. /**
  24546. * Gets or sets the fog mode to use
  24547. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24548. */
  24549. set: function (value) {
  24550. if (this._fogMode === value) {
  24551. return;
  24552. }
  24553. this._fogMode = value;
  24554. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24560. get: function () {
  24561. return this._shadowsEnabled;
  24562. },
  24563. /**
  24564. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24565. */
  24566. set: function (value) {
  24567. if (this._shadowsEnabled === value) {
  24568. return;
  24569. }
  24570. this._shadowsEnabled = value;
  24571. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24572. },
  24573. enumerable: true,
  24574. configurable: true
  24575. });
  24576. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24577. get: function () {
  24578. return this._lightsEnabled;
  24579. },
  24580. /**
  24581. * Gets or sets a boolean indicating if lights are enabled on this scene
  24582. */
  24583. set: function (value) {
  24584. if (this._lightsEnabled === value) {
  24585. return;
  24586. }
  24587. this._lightsEnabled = value;
  24588. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24594. /** The default material used on meshes when no material is affected */
  24595. get: function () {
  24596. if (!this._defaultMaterial) {
  24597. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24598. }
  24599. return this._defaultMaterial;
  24600. },
  24601. /** The default material used on meshes when no material is affected */
  24602. set: function (value) {
  24603. this._defaultMaterial = value;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24609. get: function () {
  24610. return this._texturesEnabled;
  24611. },
  24612. /**
  24613. * Gets or sets a boolean indicating if textures are enabled on this scene
  24614. */
  24615. set: function (value) {
  24616. if (this._texturesEnabled === value) {
  24617. return;
  24618. }
  24619. this._texturesEnabled = value;
  24620. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24626. get: function () {
  24627. return this._skeletonsEnabled;
  24628. },
  24629. /**
  24630. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24631. */
  24632. set: function (value) {
  24633. if (this._skeletonsEnabled === value) {
  24634. return;
  24635. }
  24636. this._skeletonsEnabled = value;
  24637. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24643. /**
  24644. * Gets the postprocess render pipeline manager
  24645. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24646. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24647. */
  24648. get: function () {
  24649. if (!this._postProcessRenderPipelineManager) {
  24650. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24651. }
  24652. return this._postProcessRenderPipelineManager;
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24658. /**
  24659. * Gets the main soundtrack associated with the scene
  24660. */
  24661. get: function () {
  24662. if (!this._mainSoundTrack) {
  24663. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24664. }
  24665. return this._mainSoundTrack;
  24666. },
  24667. enumerable: true,
  24668. configurable: true
  24669. });
  24670. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24671. /** @hidden */
  24672. get: function () {
  24673. return this._alternateRendering;
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24679. /**
  24680. * Gets the list of frustum planes (built from the active camera)
  24681. */
  24682. get: function () {
  24683. return this._frustumPlanes;
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24689. /**
  24690. * Gets the current geometry buffer associated to the scene.
  24691. */
  24692. get: function () {
  24693. return this._geometryBufferRenderer;
  24694. },
  24695. /**
  24696. * Sets the current geometry buffer for the scene.
  24697. */
  24698. set: function (geometryBufferRenderer) {
  24699. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24700. this._geometryBufferRenderer = geometryBufferRenderer;
  24701. }
  24702. },
  24703. enumerable: true,
  24704. configurable: true
  24705. });
  24706. Object.defineProperty(Scene.prototype, "debugLayer", {
  24707. /**
  24708. * Gets the debug layer (aka Inspector) associated with the scene
  24709. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24710. */
  24711. get: function () {
  24712. if (!this._debugLayer) {
  24713. this._debugLayer = new BABYLON.DebugLayer(this);
  24714. }
  24715. return this._debugLayer;
  24716. },
  24717. enumerable: true,
  24718. configurable: true
  24719. });
  24720. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24721. /**
  24722. * Gets a boolean indicating if collisions are processed on a web worker
  24723. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24724. */
  24725. get: function () {
  24726. return this._workerCollisions;
  24727. },
  24728. set: function (enabled) {
  24729. if (!BABYLON.CollisionCoordinatorLegacy) {
  24730. return;
  24731. }
  24732. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24733. this._workerCollisions = enabled;
  24734. if (this.collisionCoordinator) {
  24735. this.collisionCoordinator.destroy();
  24736. }
  24737. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24738. this.collisionCoordinator.init(this);
  24739. },
  24740. enumerable: true,
  24741. configurable: true
  24742. });
  24743. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24744. /**
  24745. * Gets the octree used to boost mesh selection (picking)
  24746. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24747. */
  24748. get: function () {
  24749. return this._selectionOctree;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24755. /**
  24756. * Gets the mesh that is currently under the pointer
  24757. */
  24758. get: function () {
  24759. return this._pointerOverMesh;
  24760. },
  24761. enumerable: true,
  24762. configurable: true
  24763. });
  24764. Object.defineProperty(Scene.prototype, "pointerX", {
  24765. /**
  24766. * Gets the current on-screen X position of the pointer
  24767. */
  24768. get: function () {
  24769. return this._pointerX;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(Scene.prototype, "pointerY", {
  24775. /**
  24776. * Gets the current on-screen Y position of the pointer
  24777. */
  24778. get: function () {
  24779. return this._pointerY;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. /**
  24785. * Gets the cached material (ie. the latest rendered one)
  24786. * @returns the cached material
  24787. */
  24788. Scene.prototype.getCachedMaterial = function () {
  24789. return this._cachedMaterial;
  24790. };
  24791. /**
  24792. * Gets the cached effect (ie. the latest rendered one)
  24793. * @returns the cached effect
  24794. */
  24795. Scene.prototype.getCachedEffect = function () {
  24796. return this._cachedEffect;
  24797. };
  24798. /**
  24799. * Gets the cached visibility state (ie. the latest rendered one)
  24800. * @returns the cached visibility state
  24801. */
  24802. Scene.prototype.getCachedVisibility = function () {
  24803. return this._cachedVisibility;
  24804. };
  24805. /**
  24806. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24807. * @param material defines the current material
  24808. * @param effect defines the current effect
  24809. * @param visibility defines the current visibility state
  24810. * @returns true if one parameter is not cached
  24811. */
  24812. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24813. if (visibility === void 0) { visibility = 1; }
  24814. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24815. };
  24816. /**
  24817. * Gets the bounding box renderer associated with the scene
  24818. * @returns a BoundingBoxRenderer
  24819. */
  24820. Scene.prototype.getBoundingBoxRenderer = function () {
  24821. if (!this._boundingBoxRenderer) {
  24822. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24823. }
  24824. return this._boundingBoxRenderer;
  24825. };
  24826. /**
  24827. * Gets the outline renderer associated with the scene
  24828. * @returns a OutlineRenderer
  24829. */
  24830. Scene.prototype.getOutlineRenderer = function () {
  24831. return this._outlineRenderer;
  24832. };
  24833. /**
  24834. * Gets the engine associated with the scene
  24835. * @returns an Engine
  24836. */
  24837. Scene.prototype.getEngine = function () {
  24838. return this._engine;
  24839. };
  24840. /**
  24841. * Gets the total number of vertices rendered per frame
  24842. * @returns the total number of vertices rendered per frame
  24843. */
  24844. Scene.prototype.getTotalVertices = function () {
  24845. return this._totalVertices.current;
  24846. };
  24847. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24848. /**
  24849. * Gets the performance counter for total vertices
  24850. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24851. */
  24852. get: function () {
  24853. return this._totalVertices;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. /**
  24859. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24860. * @returns the total number of active indices rendered per frame
  24861. */
  24862. Scene.prototype.getActiveIndices = function () {
  24863. return this._activeIndices.current;
  24864. };
  24865. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24866. /**
  24867. * Gets the performance counter for active indices
  24868. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24869. */
  24870. get: function () {
  24871. return this._activeIndices;
  24872. },
  24873. enumerable: true,
  24874. configurable: true
  24875. });
  24876. /**
  24877. * Gets the total number of active particles rendered per frame
  24878. * @returns the total number of active particles rendered per frame
  24879. */
  24880. Scene.prototype.getActiveParticles = function () {
  24881. return this._activeParticles.current;
  24882. };
  24883. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24884. /**
  24885. * Gets the performance counter for active particles
  24886. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24887. */
  24888. get: function () {
  24889. return this._activeParticles;
  24890. },
  24891. enumerable: true,
  24892. configurable: true
  24893. });
  24894. /**
  24895. * Gets the total number of active bones rendered per frame
  24896. * @returns the total number of active bones rendered per frame
  24897. */
  24898. Scene.prototype.getActiveBones = function () {
  24899. return this._activeBones.current;
  24900. };
  24901. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24902. /**
  24903. * Gets the performance counter for active bones
  24904. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24905. */
  24906. get: function () {
  24907. return this._activeBones;
  24908. },
  24909. enumerable: true,
  24910. configurable: true
  24911. });
  24912. /** @hidden */
  24913. Scene.prototype.getInterFramePerfCounter = function () {
  24914. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24915. return 0;
  24916. };
  24917. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24918. /** @hidden */
  24919. get: function () {
  24920. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24921. return null;
  24922. },
  24923. enumerable: true,
  24924. configurable: true
  24925. });
  24926. /** @hidden */
  24927. Scene.prototype.getLastFrameDuration = function () {
  24928. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24929. return 0;
  24930. };
  24931. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24932. /** @hidden */
  24933. get: function () {
  24934. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24935. return null;
  24936. },
  24937. enumerable: true,
  24938. configurable: true
  24939. });
  24940. /** @hidden */
  24941. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24942. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24943. return 0;
  24944. };
  24945. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24946. /** @hidden */
  24947. get: function () {
  24948. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24949. return null;
  24950. },
  24951. enumerable: true,
  24952. configurable: true
  24953. });
  24954. /**
  24955. * Gets the array of active meshes
  24956. * @returns an array of AbstractMesh
  24957. */
  24958. Scene.prototype.getActiveMeshes = function () {
  24959. return this._activeMeshes;
  24960. };
  24961. /** @hidden */
  24962. Scene.prototype.getRenderTargetsDuration = function () {
  24963. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24964. return 0;
  24965. };
  24966. /** @hidden */
  24967. Scene.prototype.getRenderDuration = function () {
  24968. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24969. return 0;
  24970. };
  24971. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24972. /** @hidden */
  24973. get: function () {
  24974. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24975. return null;
  24976. },
  24977. enumerable: true,
  24978. configurable: true
  24979. });
  24980. /** @hidden */
  24981. Scene.prototype.getParticlesDuration = function () {
  24982. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24983. return 0;
  24984. };
  24985. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24986. /** @hidden */
  24987. get: function () {
  24988. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24989. return null;
  24990. },
  24991. enumerable: true,
  24992. configurable: true
  24993. });
  24994. /** @hidden */
  24995. Scene.prototype.getSpritesDuration = function () {
  24996. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24997. return 0;
  24998. };
  24999. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25000. /** @hidden */
  25001. get: function () {
  25002. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25003. return null;
  25004. },
  25005. enumerable: true,
  25006. configurable: true
  25007. });
  25008. /**
  25009. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25010. * @returns a number
  25011. */
  25012. Scene.prototype.getAnimationRatio = function () {
  25013. return this._animationRatio;
  25014. };
  25015. /**
  25016. * Gets an unique Id for the current frame
  25017. * @returns a number
  25018. */
  25019. Scene.prototype.getRenderId = function () {
  25020. return this._renderId;
  25021. };
  25022. /** Call this function if you want to manually increment the render Id*/
  25023. Scene.prototype.incrementRenderId = function () {
  25024. this._renderId++;
  25025. };
  25026. Scene.prototype._updatePointerPosition = function (evt) {
  25027. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25028. if (!canvasRect) {
  25029. return;
  25030. }
  25031. this._pointerX = evt.clientX - canvasRect.left;
  25032. this._pointerY = evt.clientY - canvasRect.top;
  25033. this._unTranslatedPointerX = this._pointerX;
  25034. this._unTranslatedPointerY = this._pointerY;
  25035. };
  25036. Scene.prototype._createUbo = function () {
  25037. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25038. this._sceneUbo.addUniform("viewProjection", 16);
  25039. this._sceneUbo.addUniform("view", 16);
  25040. };
  25041. Scene.prototype._createAlternateUbo = function () {
  25042. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25043. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25044. this._alternateSceneUbo.addUniform("view", 16);
  25045. };
  25046. // Pointers handling
  25047. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25048. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25049. if (result) {
  25050. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25051. }
  25052. return result;
  25053. };
  25054. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25055. if (pointerInfo.pickInfo) {
  25056. if (!pointerInfo.pickInfo.ray) {
  25057. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25058. }
  25059. }
  25060. };
  25061. /**
  25062. * Use this method to simulate a pointer move on a mesh
  25063. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25064. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25065. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25066. * @returns the current scene
  25067. */
  25068. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25069. var evt = new PointerEvent("pointermove", pointerEventInit);
  25070. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25071. return this;
  25072. }
  25073. return this._processPointerMove(pickResult, evt);
  25074. };
  25075. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25076. var canvas = this._engine.getRenderingCanvas();
  25077. if (!canvas) {
  25078. return this;
  25079. }
  25080. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25081. this.setPointerOverSprite(null);
  25082. this.setPointerOverMesh(pickResult.pickedMesh);
  25083. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25084. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25085. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25086. }
  25087. else {
  25088. canvas.style.cursor = this.hoverCursor;
  25089. }
  25090. }
  25091. else {
  25092. canvas.style.cursor = this.defaultCursor;
  25093. }
  25094. }
  25095. else {
  25096. this.setPointerOverMesh(null);
  25097. // Sprites
  25098. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25099. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25100. this.setPointerOverSprite(pickResult.pickedSprite);
  25101. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25102. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25103. }
  25104. else {
  25105. canvas.style.cursor = this.hoverCursor;
  25106. }
  25107. }
  25108. else {
  25109. this.setPointerOverSprite(null);
  25110. // Restore pointer
  25111. canvas.style.cursor = this.defaultCursor;
  25112. }
  25113. }
  25114. if (pickResult) {
  25115. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25116. if (this.onPointerMove) {
  25117. this.onPointerMove(evt, pickResult, type);
  25118. }
  25119. if (this.onPointerObservable.hasObservers()) {
  25120. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25121. this._setRayOnPointerInfo(pi);
  25122. this.onPointerObservable.notifyObservers(pi, type);
  25123. }
  25124. }
  25125. return this;
  25126. };
  25127. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25128. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25129. if (pickResult) {
  25130. pi.ray = pickResult.ray;
  25131. }
  25132. this.onPrePointerObservable.notifyObservers(pi, type);
  25133. if (pi.skipOnPointerObservable) {
  25134. return true;
  25135. }
  25136. else {
  25137. return false;
  25138. }
  25139. };
  25140. /**
  25141. * Use this method to simulate a pointer down on a mesh
  25142. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25143. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25144. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25145. * @returns the current scene
  25146. */
  25147. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25148. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25149. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25150. return this;
  25151. }
  25152. return this._processPointerDown(pickResult, evt);
  25153. };
  25154. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25155. var _this = this;
  25156. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25157. this._pickedDownMesh = pickResult.pickedMesh;
  25158. var actionManager = pickResult.pickedMesh.actionManager;
  25159. if (actionManager) {
  25160. if (actionManager.hasPickTriggers) {
  25161. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25162. switch (evt.button) {
  25163. case 0:
  25164. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25165. break;
  25166. case 1:
  25167. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25168. break;
  25169. case 2:
  25170. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25171. break;
  25172. }
  25173. }
  25174. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25175. window.setTimeout(function () {
  25176. 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);
  25177. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25178. if (_this._totalPointersPressed !== 0 &&
  25179. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25180. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25181. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25182. _this._startingPointerTime = 0;
  25183. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25184. }
  25185. }
  25186. }, Scene.LongPressDelay);
  25187. }
  25188. }
  25189. }
  25190. if (pickResult) {
  25191. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25192. if (this.onPointerDown) {
  25193. this.onPointerDown(evt, pickResult, type);
  25194. }
  25195. if (this.onPointerObservable.hasObservers()) {
  25196. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25197. this._setRayOnPointerInfo(pi);
  25198. this.onPointerObservable.notifyObservers(pi, type);
  25199. }
  25200. }
  25201. return this;
  25202. };
  25203. /**
  25204. * Use this method to simulate a pointer up on a mesh
  25205. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25206. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25207. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25208. * @returns the current scene
  25209. */
  25210. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25211. var evt = new PointerEvent("pointerup", pointerEventInit);
  25212. var clickInfo = new ClickInfo();
  25213. clickInfo.singleClick = true;
  25214. clickInfo.ignore = true;
  25215. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25216. return this;
  25217. }
  25218. return this._processPointerUp(pickResult, evt, clickInfo);
  25219. };
  25220. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25221. if (pickResult && pickResult && pickResult.pickedMesh) {
  25222. this._pickedUpMesh = pickResult.pickedMesh;
  25223. if (this._pickedDownMesh === this._pickedUpMesh) {
  25224. if (this.onPointerPick) {
  25225. this.onPointerPick(evt, pickResult);
  25226. }
  25227. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25228. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25229. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25230. this._setRayOnPointerInfo(pi);
  25231. this.onPointerObservable.notifyObservers(pi, type_1);
  25232. }
  25233. }
  25234. if (pickResult.pickedMesh.actionManager) {
  25235. if (clickInfo.ignore) {
  25236. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. }
  25238. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25239. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25240. }
  25241. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25242. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25243. }
  25244. }
  25245. }
  25246. if (this._pickedDownMesh &&
  25247. this._pickedDownMesh.actionManager &&
  25248. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25249. this._pickedDownMesh !== this._pickedUpMesh) {
  25250. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25251. }
  25252. var type = BABYLON.PointerEventTypes.POINTERUP;
  25253. if (this.onPointerObservable.hasObservers()) {
  25254. if (!clickInfo.ignore) {
  25255. if (!clickInfo.hasSwiped) {
  25256. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25257. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25258. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25259. this._setRayOnPointerInfo(pi);
  25260. this.onPointerObservable.notifyObservers(pi, type_2);
  25261. }
  25262. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25263. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25264. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25265. this._setRayOnPointerInfo(pi);
  25266. this.onPointerObservable.notifyObservers(pi, type_3);
  25267. }
  25268. }
  25269. }
  25270. else {
  25271. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25272. this._setRayOnPointerInfo(pi);
  25273. this.onPointerObservable.notifyObservers(pi, type);
  25274. }
  25275. }
  25276. if (this.onPointerUp) {
  25277. this.onPointerUp(evt, pickResult, type);
  25278. }
  25279. return this;
  25280. };
  25281. /**
  25282. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25283. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25284. * @returns true if the pointer was captured
  25285. */
  25286. Scene.prototype.isPointerCaptured = function (pointerId) {
  25287. if (pointerId === void 0) { pointerId = 0; }
  25288. return this._pointerCaptures[pointerId];
  25289. };
  25290. /**
  25291. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25292. * @param attachUp defines if you want to attach events to pointerup
  25293. * @param attachDown defines if you want to attach events to pointerdown
  25294. * @param attachMove defines if you want to attach events to pointermove
  25295. */
  25296. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25297. var _this = this;
  25298. if (attachUp === void 0) { attachUp = true; }
  25299. if (attachDown === void 0) { attachDown = true; }
  25300. if (attachMove === void 0) { attachMove = true; }
  25301. this._initActionManager = function (act, clickInfo) {
  25302. if (!_this._meshPickProceed) {
  25303. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25304. _this._currentPickResult = pickResult;
  25305. if (pickResult) {
  25306. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25307. }
  25308. _this._meshPickProceed = true;
  25309. }
  25310. return act;
  25311. };
  25312. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25313. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25314. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25315. btn !== _this._previousButtonPressed) {
  25316. _this._doubleClickOccured = false;
  25317. clickInfo.singleClick = true;
  25318. clickInfo.ignore = false;
  25319. cb(clickInfo, _this._currentPickResult);
  25320. }
  25321. };
  25322. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25323. var clickInfo = new ClickInfo();
  25324. _this._currentPickResult = null;
  25325. var act = null;
  25326. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25327. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25328. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25329. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25330. act = _this._initActionManager(act, clickInfo);
  25331. if (act)
  25332. checkPicking = act.hasPickTriggers;
  25333. }
  25334. if (checkPicking) {
  25335. var btn = evt.button;
  25336. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25337. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25338. if (!clickInfo.hasSwiped) {
  25339. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25340. if (!checkSingleClickImmediately) {
  25341. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25342. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25343. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25344. act = _this._initActionManager(act, clickInfo);
  25345. if (act)
  25346. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25347. }
  25348. }
  25349. if (checkSingleClickImmediately) {
  25350. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25351. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25352. btn !== _this._previousButtonPressed) {
  25353. clickInfo.singleClick = true;
  25354. cb(clickInfo, _this._currentPickResult);
  25355. }
  25356. }
  25357. // at least one double click is required to be check and exclusive double click is enabled
  25358. else {
  25359. // wait that no double click has been raised during the double click delay
  25360. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25361. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25362. }
  25363. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25364. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25365. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25366. act = _this._initActionManager(act, clickInfo);
  25367. if (act)
  25368. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25369. }
  25370. if (checkDoubleClick) {
  25371. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25372. if (btn === _this._previousButtonPressed &&
  25373. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25374. !_this._doubleClickOccured) {
  25375. // pointer has not moved for 2 clicks, it's a double click
  25376. if (!clickInfo.hasSwiped &&
  25377. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25378. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25379. _this._previousStartingPointerTime = 0;
  25380. _this._doubleClickOccured = true;
  25381. clickInfo.doubleClick = true;
  25382. clickInfo.ignore = false;
  25383. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25384. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25385. }
  25386. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25387. cb(clickInfo, _this._currentPickResult);
  25388. }
  25389. // if the two successive clicks are too far, it's just two simple clicks
  25390. else {
  25391. _this._doubleClickOccured = false;
  25392. _this._previousStartingPointerTime = _this._startingPointerTime;
  25393. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25394. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25395. _this._previousButtonPressed = btn;
  25396. if (Scene.ExclusiveDoubleClickMode) {
  25397. if (_this._previousDelayedSimpleClickTimeout) {
  25398. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25399. }
  25400. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25401. cb(clickInfo, _this._previousPickResult);
  25402. }
  25403. else {
  25404. cb(clickInfo, _this._currentPickResult);
  25405. }
  25406. }
  25407. }
  25408. // just the first click of the double has been raised
  25409. else {
  25410. _this._doubleClickOccured = false;
  25411. _this._previousStartingPointerTime = _this._startingPointerTime;
  25412. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25413. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25414. _this._previousButtonPressed = btn;
  25415. }
  25416. }
  25417. }
  25418. }
  25419. clickInfo.ignore = true;
  25420. cb(clickInfo, _this._currentPickResult);
  25421. };
  25422. this._spritePredicate = function (sprite) {
  25423. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25424. };
  25425. this._onPointerMove = function (evt) {
  25426. _this._updatePointerPosition(evt);
  25427. // PreObservable support
  25428. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25429. return;
  25430. }
  25431. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25432. return;
  25433. }
  25434. if (!_this.pointerMovePredicate) {
  25435. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25436. }
  25437. // Meshes
  25438. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25439. _this._processPointerMove(pickResult, evt);
  25440. };
  25441. this._onPointerDown = function (evt) {
  25442. _this._totalPointersPressed++;
  25443. _this._pickedDownMesh = null;
  25444. _this._meshPickProceed = false;
  25445. _this._updatePointerPosition(evt);
  25446. if (_this.preventDefaultOnPointerDown && canvas) {
  25447. evt.preventDefault();
  25448. canvas.focus();
  25449. }
  25450. // PreObservable support
  25451. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25452. return;
  25453. }
  25454. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25455. return;
  25456. }
  25457. _this._pointerCaptures[evt.pointerId] = true;
  25458. _this._startingPointerPosition.x = _this._pointerX;
  25459. _this._startingPointerPosition.y = _this._pointerY;
  25460. _this._startingPointerTime = Date.now();
  25461. if (!_this.pointerDownPredicate) {
  25462. _this.pointerDownPredicate = function (mesh) {
  25463. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25464. };
  25465. }
  25466. // Meshes
  25467. _this._pickedDownMesh = null;
  25468. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25469. _this._processPointerDown(pickResult, evt);
  25470. // Sprites
  25471. _this._pickedDownSprite = null;
  25472. if (_this.spriteManagers.length > 0) {
  25473. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25474. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25475. if (pickResult.pickedSprite.actionManager) {
  25476. _this._pickedDownSprite = pickResult.pickedSprite;
  25477. switch (evt.button) {
  25478. case 0:
  25479. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25480. break;
  25481. case 1:
  25482. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25483. break;
  25484. case 2:
  25485. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25486. break;
  25487. }
  25488. if (pickResult.pickedSprite.actionManager) {
  25489. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25490. }
  25491. }
  25492. }
  25493. }
  25494. };
  25495. this._onPointerUp = function (evt) {
  25496. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25497. return; // So we need to test it the pointer down was pressed before.
  25498. }
  25499. _this._totalPointersPressed--;
  25500. _this._pickedUpMesh = null;
  25501. _this._meshPickProceed = false;
  25502. _this._updatePointerPosition(evt);
  25503. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25504. // PreObservable support
  25505. if (_this.onPrePointerObservable.hasObservers()) {
  25506. if (!clickInfo.ignore) {
  25507. if (!clickInfo.hasSwiped) {
  25508. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25509. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25510. return;
  25511. }
  25512. }
  25513. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25514. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25515. return;
  25516. }
  25517. }
  25518. }
  25519. }
  25520. else {
  25521. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25522. return;
  25523. }
  25524. }
  25525. }
  25526. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25527. return;
  25528. }
  25529. _this._pointerCaptures[evt.pointerId] = false;
  25530. if (!_this.pointerUpPredicate) {
  25531. _this.pointerUpPredicate = function (mesh) {
  25532. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25533. };
  25534. }
  25535. // Meshes
  25536. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25537. _this._initActionManager(null, clickInfo);
  25538. }
  25539. if (!pickResult) {
  25540. pickResult = _this._currentPickResult;
  25541. }
  25542. _this._processPointerUp(pickResult, evt, clickInfo);
  25543. // Sprites
  25544. if (!clickInfo.ignore) {
  25545. if (_this.spriteManagers.length > 0) {
  25546. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25547. if (spritePickResult) {
  25548. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25549. if (spritePickResult.pickedSprite.actionManager) {
  25550. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25551. if (spritePickResult.pickedSprite.actionManager) {
  25552. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25553. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25554. }
  25555. }
  25556. }
  25557. }
  25558. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25559. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25560. }
  25561. }
  25562. }
  25563. }
  25564. _this._previousPickResult = _this._currentPickResult;
  25565. });
  25566. };
  25567. this._onKeyDown = function (evt) {
  25568. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25569. if (_this.onPreKeyboardObservable.hasObservers()) {
  25570. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25571. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25572. if (pi.skipOnPointerObservable) {
  25573. return;
  25574. }
  25575. }
  25576. if (_this.onKeyboardObservable.hasObservers()) {
  25577. var pi = new BABYLON.KeyboardInfo(type, evt);
  25578. _this.onKeyboardObservable.notifyObservers(pi, type);
  25579. }
  25580. if (_this.actionManager) {
  25581. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25582. }
  25583. };
  25584. this._onKeyUp = function (evt) {
  25585. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25586. if (_this.onPreKeyboardObservable.hasObservers()) {
  25587. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25588. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25589. if (pi.skipOnPointerObservable) {
  25590. return;
  25591. }
  25592. }
  25593. if (_this.onKeyboardObservable.hasObservers()) {
  25594. var pi = new BABYLON.KeyboardInfo(type, evt);
  25595. _this.onKeyboardObservable.notifyObservers(pi, type);
  25596. }
  25597. if (_this.actionManager) {
  25598. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25599. }
  25600. };
  25601. var engine = this.getEngine();
  25602. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25603. if (!canvas) {
  25604. return;
  25605. }
  25606. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25607. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25608. });
  25609. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25610. if (!canvas) {
  25611. return;
  25612. }
  25613. canvas.removeEventListener("keydown", _this._onKeyDown);
  25614. canvas.removeEventListener("keyup", _this._onKeyUp);
  25615. });
  25616. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25617. var canvas = this._engine.getRenderingCanvas();
  25618. if (!canvas) {
  25619. return;
  25620. }
  25621. if (attachMove) {
  25622. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25623. // Wheel
  25624. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25625. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25626. }
  25627. if (attachDown) {
  25628. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25629. }
  25630. if (attachUp) {
  25631. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25632. }
  25633. canvas.tabIndex = 1;
  25634. };
  25635. /** Detaches all event handlers*/
  25636. Scene.prototype.detachControl = function () {
  25637. var engine = this.getEngine();
  25638. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25639. var canvas = engine.getRenderingCanvas();
  25640. if (!canvas) {
  25641. return;
  25642. }
  25643. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25644. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25645. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25646. if (this._onCanvasBlurObserver) {
  25647. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25648. }
  25649. if (this._onCanvasFocusObserver) {
  25650. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25651. }
  25652. // Wheel
  25653. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25654. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25655. // Keyboard
  25656. canvas.removeEventListener("keydown", this._onKeyDown);
  25657. canvas.removeEventListener("keyup", this._onKeyUp);
  25658. // Observables
  25659. this.onKeyboardObservable.clear();
  25660. this.onPreKeyboardObservable.clear();
  25661. this.onPointerObservable.clear();
  25662. this.onPrePointerObservable.clear();
  25663. };
  25664. /**
  25665. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25666. * Delay loaded resources are not taking in account
  25667. * @return true if all required resources are ready
  25668. */
  25669. Scene.prototype.isReady = function () {
  25670. if (this._isDisposed) {
  25671. return false;
  25672. }
  25673. if (this._pendingData.length > 0) {
  25674. return false;
  25675. }
  25676. var index;
  25677. var engine = this.getEngine();
  25678. // Geometries
  25679. for (index = 0; index < this._geometries.length; index++) {
  25680. var geometry = this._geometries[index];
  25681. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25682. return false;
  25683. }
  25684. }
  25685. // Meshes
  25686. for (index = 0; index < this.meshes.length; index++) {
  25687. var mesh = this.meshes[index];
  25688. if (!mesh.isEnabled()) {
  25689. continue;
  25690. }
  25691. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25692. continue;
  25693. }
  25694. if (!mesh.isReady(true)) {
  25695. return false;
  25696. }
  25697. // Effect layers
  25698. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25699. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25700. var layer = _a[_i];
  25701. if (!layer.hasMesh(mesh)) {
  25702. continue;
  25703. }
  25704. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25705. var subMesh = _c[_b];
  25706. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25707. return false;
  25708. }
  25709. }
  25710. }
  25711. }
  25712. // Post-processes
  25713. if (this.activeCameras && this.activeCameras.length > 0) {
  25714. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25715. var camera = _e[_d];
  25716. if (!camera.isReady(true)) {
  25717. return false;
  25718. }
  25719. }
  25720. }
  25721. else if (this.activeCamera) {
  25722. if (!this.activeCamera.isReady(true)) {
  25723. return false;
  25724. }
  25725. }
  25726. // Particles
  25727. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25728. var particleSystem = _g[_f];
  25729. if (!particleSystem.isReady()) {
  25730. return false;
  25731. }
  25732. }
  25733. return true;
  25734. };
  25735. /** Resets all cached information relative to material (including effect and visibility) */
  25736. Scene.prototype.resetCachedMaterial = function () {
  25737. this._cachedMaterial = null;
  25738. this._cachedEffect = null;
  25739. this._cachedVisibility = null;
  25740. };
  25741. /**
  25742. * Registers a function to be called before every frame render
  25743. * @param func defines the function to register
  25744. */
  25745. Scene.prototype.registerBeforeRender = function (func) {
  25746. this.onBeforeRenderObservable.add(func);
  25747. };
  25748. /**
  25749. * Unregisters a function called before every frame render
  25750. * @param func defines the function to unregister
  25751. */
  25752. Scene.prototype.unregisterBeforeRender = function (func) {
  25753. this.onBeforeRenderObservable.removeCallback(func);
  25754. };
  25755. /**
  25756. * Registers a function to be called after every frame render
  25757. * @param func defines the function to register
  25758. */
  25759. Scene.prototype.registerAfterRender = function (func) {
  25760. this.onAfterRenderObservable.add(func);
  25761. };
  25762. /**
  25763. * Unregisters a function called after every frame render
  25764. * @param func defines the function to unregister
  25765. */
  25766. Scene.prototype.unregisterAfterRender = function (func) {
  25767. this.onAfterRenderObservable.removeCallback(func);
  25768. };
  25769. Scene.prototype._executeOnceBeforeRender = function (func) {
  25770. var _this = this;
  25771. var execFunc = function () {
  25772. func();
  25773. setTimeout(function () {
  25774. _this.unregisterBeforeRender(execFunc);
  25775. });
  25776. };
  25777. this.registerBeforeRender(execFunc);
  25778. };
  25779. /**
  25780. * The provided function will run before render once and will be disposed afterwards.
  25781. * A timeout delay can be provided so that the function will be executed in N ms.
  25782. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25783. * @param func The function to be executed.
  25784. * @param timeout optional delay in ms
  25785. */
  25786. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25787. var _this = this;
  25788. if (timeout !== undefined) {
  25789. setTimeout(function () {
  25790. _this._executeOnceBeforeRender(func);
  25791. }, timeout);
  25792. }
  25793. else {
  25794. this._executeOnceBeforeRender(func);
  25795. }
  25796. };
  25797. /** @hidden */
  25798. Scene.prototype._addPendingData = function (data) {
  25799. this._pendingData.push(data);
  25800. };
  25801. /** @hidden */
  25802. Scene.prototype._removePendingData = function (data) {
  25803. var wasLoading = this.isLoading;
  25804. var index = this._pendingData.indexOf(data);
  25805. if (index !== -1) {
  25806. this._pendingData.splice(index, 1);
  25807. }
  25808. if (wasLoading && !this.isLoading) {
  25809. this.onDataLoadedObservable.notifyObservers(this);
  25810. }
  25811. };
  25812. /**
  25813. * Returns the number of items waiting to be loaded
  25814. * @returns the number of items waiting to be loaded
  25815. */
  25816. Scene.prototype.getWaitingItemsCount = function () {
  25817. return this._pendingData.length;
  25818. };
  25819. Object.defineProperty(Scene.prototype, "isLoading", {
  25820. /**
  25821. * Returns a boolean indicating if the scene is still loading data
  25822. */
  25823. get: function () {
  25824. return this._pendingData.length > 0;
  25825. },
  25826. enumerable: true,
  25827. configurable: true
  25828. });
  25829. /**
  25830. * Registers a function to be executed when the scene is ready
  25831. * @param {Function} func - the function to be executed
  25832. */
  25833. Scene.prototype.executeWhenReady = function (func) {
  25834. var _this = this;
  25835. this.onReadyObservable.add(func);
  25836. if (this._executeWhenReadyTimeoutId !== -1) {
  25837. return;
  25838. }
  25839. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25840. _this._checkIsReady();
  25841. }, 150);
  25842. };
  25843. /**
  25844. * Returns a promise that resolves when the scene is ready
  25845. * @returns A promise that resolves when the scene is ready
  25846. */
  25847. Scene.prototype.whenReadyAsync = function () {
  25848. var _this = this;
  25849. return new Promise(function (resolve) {
  25850. _this.executeWhenReady(function () {
  25851. resolve();
  25852. });
  25853. });
  25854. };
  25855. /** @hidden */
  25856. Scene.prototype._checkIsReady = function () {
  25857. var _this = this;
  25858. if (this.isReady()) {
  25859. this.onReadyObservable.notifyObservers(this);
  25860. this.onReadyObservable.clear();
  25861. this._executeWhenReadyTimeoutId = -1;
  25862. return;
  25863. }
  25864. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25865. _this._checkIsReady();
  25866. }, 150);
  25867. };
  25868. // Animations
  25869. /**
  25870. * Will start the animation sequence of a given target
  25871. * @param target defines the target
  25872. * @param from defines from which frame should animation start
  25873. * @param to defines until which frame should animation run.
  25874. * @param weight defines the weight to apply to the animation (1.0 by default)
  25875. * @param loop defines if the animation loops
  25876. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25877. * @param onAnimationEnd defines the function to be executed when the animation ends
  25878. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25879. * @returns the animatable object created for this animation
  25880. */
  25881. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25882. if (weight === void 0) { weight = 1.0; }
  25883. if (speedRatio === void 0) { speedRatio = 1.0; }
  25884. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25885. returnedAnimatable.weight = weight;
  25886. return returnedAnimatable;
  25887. };
  25888. /**
  25889. * Will start the animation sequence of a given target
  25890. * @param target defines the target
  25891. * @param from defines from which frame should animation start
  25892. * @param to defines until which frame should animation run.
  25893. * @param loop defines if the animation loops
  25894. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25895. * @param onAnimationEnd defines the function to be executed when the animation ends
  25896. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25897. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25898. * @returns the animatable object created for this animation
  25899. */
  25900. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25901. if (speedRatio === void 0) { speedRatio = 1.0; }
  25902. if (stopCurrent === void 0) { stopCurrent = true; }
  25903. if (from > to && speedRatio > 0) {
  25904. speedRatio *= -1;
  25905. }
  25906. if (stopCurrent) {
  25907. this.stopAnimation(target);
  25908. }
  25909. if (!animatable) {
  25910. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25911. }
  25912. // Local animations
  25913. if (target.animations) {
  25914. animatable.appendAnimations(target, target.animations);
  25915. }
  25916. // Children animations
  25917. if (target.getAnimatables) {
  25918. var animatables = target.getAnimatables();
  25919. for (var index = 0; index < animatables.length; index++) {
  25920. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25921. }
  25922. }
  25923. animatable.reset();
  25924. return animatable;
  25925. };
  25926. /**
  25927. * Begin a new animation on a given node
  25928. * @param target defines the target where the animation will take place
  25929. * @param animations defines the list of animations to start
  25930. * @param from defines the initial value
  25931. * @param to defines the final value
  25932. * @param loop defines if you want animation to loop (off by default)
  25933. * @param speedRatio defines the speed ratio to apply to all animations
  25934. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25935. * @returns the list of created animatables
  25936. */
  25937. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25938. if (speedRatio === undefined) {
  25939. speedRatio = 1.0;
  25940. }
  25941. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25942. return animatable;
  25943. };
  25944. /**
  25945. * Begin a new animation on a given node and its hierarchy
  25946. * @param target defines the root node where the animation will take place
  25947. * @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.
  25948. * @param animations defines the list of animations to start
  25949. * @param from defines the initial value
  25950. * @param to defines the final value
  25951. * @param loop defines if you want animation to loop (off by default)
  25952. * @param speedRatio defines the speed ratio to apply to all animations
  25953. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25954. * @returns the list of animatables created for all nodes
  25955. */
  25956. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25957. var children = target.getDescendants(directDescendantsOnly);
  25958. var result = [];
  25959. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25960. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25961. var child = children_1[_i];
  25962. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25963. }
  25964. return result;
  25965. };
  25966. /**
  25967. * Gets the animatable associated with a specific target
  25968. * @param target defines the target of the animatable
  25969. * @returns the required animatable if found
  25970. */
  25971. Scene.prototype.getAnimatableByTarget = function (target) {
  25972. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25973. if (this._activeAnimatables[index].target === target) {
  25974. return this._activeAnimatables[index];
  25975. }
  25976. }
  25977. return null;
  25978. };
  25979. /**
  25980. * Gets all animatables associated with a given target
  25981. * @param target defines the target to look animatables for
  25982. * @returns an array of Animatables
  25983. */
  25984. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25985. var result = [];
  25986. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25987. if (this._activeAnimatables[index].target === target) {
  25988. result.push(this._activeAnimatables[index]);
  25989. }
  25990. }
  25991. return result;
  25992. };
  25993. Object.defineProperty(Scene.prototype, "animatables", {
  25994. /**
  25995. * Gets all animatable attached to the scene
  25996. */
  25997. get: function () {
  25998. return this._activeAnimatables;
  25999. },
  26000. enumerable: true,
  26001. configurable: true
  26002. });
  26003. /**
  26004. * Will stop the animation of the given target
  26005. * @param target - the target
  26006. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26007. */
  26008. Scene.prototype.stopAnimation = function (target, animationName) {
  26009. var animatables = this.getAllAnimatablesByTarget(target);
  26010. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26011. var animatable = animatables_1[_i];
  26012. animatable.stop(animationName);
  26013. }
  26014. };
  26015. /**
  26016. * Stops and removes all animations that have been applied to the scene
  26017. */
  26018. Scene.prototype.stopAllAnimations = function () {
  26019. if (this._activeAnimatables) {
  26020. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26021. this._activeAnimatables[i].stop();
  26022. }
  26023. this._activeAnimatables = [];
  26024. }
  26025. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26026. var group = _a[_i];
  26027. group.stop();
  26028. }
  26029. };
  26030. Scene.prototype._animate = function () {
  26031. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26032. return;
  26033. }
  26034. // Getting time
  26035. var now = BABYLON.Tools.Now;
  26036. if (!this._animationTimeLast) {
  26037. if (this._pendingData.length > 0) {
  26038. return;
  26039. }
  26040. this._animationTimeLast = now;
  26041. }
  26042. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26043. this._animationTime += deltaTime;
  26044. this._animationTimeLast = now;
  26045. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26046. this._activeAnimatables[index]._animate(this._animationTime);
  26047. }
  26048. // Late animation bindings
  26049. this._processLateAnimationBindings();
  26050. };
  26051. /** @hidden */
  26052. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26053. var target = runtimeAnimation.target;
  26054. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26055. if (!target._lateAnimationHolders) {
  26056. target._lateAnimationHolders = {};
  26057. }
  26058. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26059. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26060. totalWeight: 0,
  26061. animations: [],
  26062. originalValue: originalValue
  26063. };
  26064. }
  26065. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26066. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26067. };
  26068. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26069. var normalizer = 1.0;
  26070. var finalPosition = BABYLON.Tmp.Vector3[0];
  26071. var finalScaling = BABYLON.Tmp.Vector3[1];
  26072. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26073. var startIndex = 0;
  26074. var originalAnimation = holder.animations[0];
  26075. var originalValue = holder.originalValue;
  26076. var scale = 1;
  26077. if (holder.totalWeight < 1.0) {
  26078. // We need to mix the original value in
  26079. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26080. scale = 1.0 - holder.totalWeight;
  26081. }
  26082. else {
  26083. startIndex = 1;
  26084. // We need to normalize the weights
  26085. normalizer = holder.totalWeight;
  26086. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26087. scale = originalAnimation.weight / normalizer;
  26088. if (scale == 1) {
  26089. return originalAnimation.currentValue;
  26090. }
  26091. }
  26092. finalScaling.scaleInPlace(scale);
  26093. finalPosition.scaleInPlace(scale);
  26094. finalQuaternion.scaleInPlace(scale);
  26095. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26096. var runtimeAnimation = holder.animations[animIndex];
  26097. var scale = runtimeAnimation.weight / normalizer;
  26098. var currentPosition = BABYLON.Tmp.Vector3[2];
  26099. var currentScaling = BABYLON.Tmp.Vector3[3];
  26100. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26101. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26102. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26103. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26104. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26105. }
  26106. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26107. return originalAnimation._workValue;
  26108. };
  26109. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26110. var originalAnimation = holder.animations[0];
  26111. var originalValue = holder.originalValue;
  26112. if (holder.animations.length === 1) {
  26113. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26114. }
  26115. var normalizer = 1.0;
  26116. var quaternions;
  26117. var weights;
  26118. if (holder.totalWeight < 1.0) {
  26119. var scale = 1.0 - holder.totalWeight;
  26120. quaternions = [];
  26121. weights = [];
  26122. quaternions.push(originalValue);
  26123. weights.push(scale);
  26124. }
  26125. else {
  26126. if (holder.animations.length === 2) { // Slerp as soon as we can
  26127. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26128. }
  26129. quaternions = [];
  26130. weights = [];
  26131. normalizer = holder.totalWeight;
  26132. }
  26133. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26134. var runtimeAnimation = holder.animations[animIndex];
  26135. quaternions.push(runtimeAnimation.currentValue);
  26136. weights.push(runtimeAnimation.weight / normalizer);
  26137. }
  26138. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26139. var cumulativeAmount = 0;
  26140. var cumulativeQuaternion = null;
  26141. for (var index = 0; index < quaternions.length;) {
  26142. if (!cumulativeQuaternion) {
  26143. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26144. cumulativeAmount = weights[index] + weights[index + 1];
  26145. index += 2;
  26146. continue;
  26147. }
  26148. cumulativeAmount += weights[index];
  26149. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26150. index++;
  26151. }
  26152. return cumulativeQuaternion;
  26153. };
  26154. Scene.prototype._processLateAnimationBindings = function () {
  26155. if (!this._registeredForLateAnimationBindings.length) {
  26156. return;
  26157. }
  26158. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26159. var target = this._registeredForLateAnimationBindings.data[index];
  26160. for (var path in target._lateAnimationHolders) {
  26161. var holder = target._lateAnimationHolders[path];
  26162. var originalAnimation = holder.animations[0];
  26163. var originalValue = holder.originalValue;
  26164. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26165. var finalValue = void 0;
  26166. if (matrixDecomposeMode) {
  26167. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26168. }
  26169. else {
  26170. var quaternionMode = originalValue.w !== undefined;
  26171. if (quaternionMode) {
  26172. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26173. }
  26174. else {
  26175. var startIndex = 0;
  26176. var normalizer = 1.0;
  26177. if (holder.totalWeight < 1.0) {
  26178. // We need to mix the original value in
  26179. if (originalValue.scale) {
  26180. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26181. }
  26182. else {
  26183. finalValue = originalValue * (1.0 - holder.totalWeight);
  26184. }
  26185. }
  26186. else {
  26187. // We need to normalize the weights
  26188. normalizer = holder.totalWeight;
  26189. var scale_1 = originalAnimation.weight / normalizer;
  26190. if (scale_1 !== 1) {
  26191. if (originalAnimation.currentValue.scale) {
  26192. finalValue = originalAnimation.currentValue.scale(scale_1);
  26193. }
  26194. else {
  26195. finalValue = originalAnimation.currentValue * scale_1;
  26196. }
  26197. }
  26198. else {
  26199. finalValue = originalAnimation.currentValue;
  26200. }
  26201. startIndex = 1;
  26202. }
  26203. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26204. var runtimeAnimation = holder.animations[animIndex];
  26205. var scale = runtimeAnimation.weight / normalizer;
  26206. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26207. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26208. }
  26209. else {
  26210. finalValue += runtimeAnimation.currentValue * scale;
  26211. }
  26212. }
  26213. }
  26214. }
  26215. target[path] = finalValue;
  26216. }
  26217. target._lateAnimationHolders = {};
  26218. }
  26219. this._registeredForLateAnimationBindings.reset();
  26220. };
  26221. // Matrix
  26222. /** @hidden */
  26223. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26224. this._useAlternateCameraConfiguration = active;
  26225. };
  26226. /**
  26227. * Gets the current view matrix
  26228. * @returns a Matrix
  26229. */
  26230. Scene.prototype.getViewMatrix = function () {
  26231. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26232. };
  26233. /**
  26234. * Gets the current projection matrix
  26235. * @returns a Matrix
  26236. */
  26237. Scene.prototype.getProjectionMatrix = function () {
  26238. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26239. };
  26240. /**
  26241. * Gets the current transform matrix
  26242. * @returns a Matrix made of View * Projection
  26243. */
  26244. Scene.prototype.getTransformMatrix = function () {
  26245. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26246. };
  26247. /**
  26248. * Sets the current transform matrix
  26249. * @param view defines the View matrix to use
  26250. * @param projection defines the Projection matrix to use
  26251. */
  26252. Scene.prototype.setTransformMatrix = function (view, projection) {
  26253. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26254. return;
  26255. }
  26256. this._viewUpdateFlag = view.updateFlag;
  26257. this._projectionUpdateFlag = projection.updateFlag;
  26258. this._viewMatrix = view;
  26259. this._projectionMatrix = projection;
  26260. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26261. // Update frustum
  26262. if (!this._frustumPlanes) {
  26263. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26264. }
  26265. else {
  26266. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26267. }
  26268. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26269. var otherCamera = this.activeCamera._alternateCamera;
  26270. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26271. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26272. }
  26273. if (this._sceneUbo.useUbo) {
  26274. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26275. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26276. this._sceneUbo.update();
  26277. }
  26278. };
  26279. /** @hidden */
  26280. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26281. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26282. return;
  26283. }
  26284. this._alternateViewUpdateFlag = view.updateFlag;
  26285. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26286. this._alternateViewMatrix = view;
  26287. this._alternateProjectionMatrix = projection;
  26288. if (!this._alternateTransformMatrix) {
  26289. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26290. }
  26291. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26292. if (!this._alternateSceneUbo) {
  26293. this._createAlternateUbo();
  26294. }
  26295. if (this._alternateSceneUbo.useUbo) {
  26296. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26297. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26298. this._alternateSceneUbo.update();
  26299. }
  26300. };
  26301. /**
  26302. * Gets the uniform buffer used to store scene data
  26303. * @returns a UniformBuffer
  26304. */
  26305. Scene.prototype.getSceneUniformBuffer = function () {
  26306. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26307. };
  26308. /**
  26309. * Gets an unique (relatively to the current scene) Id
  26310. * @returns an unique number for the scene
  26311. */
  26312. Scene.prototype.getUniqueId = function () {
  26313. var result = Scene._uniqueIdCounter;
  26314. Scene._uniqueIdCounter++;
  26315. return result;
  26316. };
  26317. /**
  26318. * Add a mesh to the list of scene's meshes
  26319. * @param newMesh defines the mesh to add
  26320. * @param recursive if all child meshes should also be added to the scene
  26321. */
  26322. Scene.prototype.addMesh = function (newMesh, recursive) {
  26323. var _this = this;
  26324. if (recursive === void 0) { recursive = false; }
  26325. this.meshes.push(newMesh);
  26326. //notify the collision coordinator
  26327. if (this.collisionCoordinator) {
  26328. this.collisionCoordinator.onMeshAdded(newMesh);
  26329. }
  26330. newMesh._resyncLightSources();
  26331. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26332. if (recursive) {
  26333. newMesh.getChildMeshes().forEach(function (m) {
  26334. _this.addMesh(m);
  26335. });
  26336. }
  26337. };
  26338. /**
  26339. * Remove a mesh for the list of scene's meshes
  26340. * @param toRemove defines the mesh to remove
  26341. * @param recursive if all child meshes should also be removed from the scene
  26342. * @returns the index where the mesh was in the mesh list
  26343. */
  26344. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26345. var _this = this;
  26346. if (recursive === void 0) { recursive = false; }
  26347. var index = this.meshes.indexOf(toRemove);
  26348. if (index !== -1) {
  26349. // Remove from the scene if mesh found
  26350. this.meshes.splice(index, 1);
  26351. }
  26352. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26353. if (recursive) {
  26354. toRemove.getChildMeshes().forEach(function (m) {
  26355. _this.removeMesh(m);
  26356. });
  26357. }
  26358. return index;
  26359. };
  26360. /**
  26361. * Add a transform node to the list of scene's transform nodes
  26362. * @param newTransformNode defines the transform node to add
  26363. */
  26364. Scene.prototype.addTransformNode = function (newTransformNode) {
  26365. this.transformNodes.push(newTransformNode);
  26366. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26367. };
  26368. /**
  26369. * Remove a transform node for the list of scene's transform nodes
  26370. * @param toRemove defines the transform node to remove
  26371. * @returns the index where the transform node was in the transform node list
  26372. */
  26373. Scene.prototype.removeTransformNode = function (toRemove) {
  26374. var index = this.transformNodes.indexOf(toRemove);
  26375. if (index !== -1) {
  26376. // Remove from the scene if found
  26377. this.transformNodes.splice(index, 1);
  26378. }
  26379. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26380. return index;
  26381. };
  26382. /**
  26383. * Remove a skeleton for the list of scene's skeletons
  26384. * @param toRemove defines the skeleton to remove
  26385. * @returns the index where the skeleton was in the skeleton list
  26386. */
  26387. Scene.prototype.removeSkeleton = function (toRemove) {
  26388. var index = this.skeletons.indexOf(toRemove);
  26389. if (index !== -1) {
  26390. // Remove from the scene if found
  26391. this.skeletons.splice(index, 1);
  26392. }
  26393. return index;
  26394. };
  26395. /**
  26396. * Remove a morph target for the list of scene's morph targets
  26397. * @param toRemove defines the morph target to remove
  26398. * @returns the index where the morph target was in the morph target list
  26399. */
  26400. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26401. var index = this.morphTargetManagers.indexOf(toRemove);
  26402. if (index !== -1) {
  26403. // Remove from the scene if found
  26404. this.morphTargetManagers.splice(index, 1);
  26405. }
  26406. return index;
  26407. };
  26408. /**
  26409. * Remove a light for the list of scene's lights
  26410. * @param toRemove defines the light to remove
  26411. * @returns the index where the light was in the light list
  26412. */
  26413. Scene.prototype.removeLight = function (toRemove) {
  26414. var index = this.lights.indexOf(toRemove);
  26415. if (index !== -1) {
  26416. // Remove from meshes
  26417. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26418. var mesh = _a[_i];
  26419. mesh._removeLightSource(toRemove);
  26420. }
  26421. // Remove from the scene if mesh found
  26422. this.lights.splice(index, 1);
  26423. this.sortLightsByPriority();
  26424. }
  26425. this.onLightRemovedObservable.notifyObservers(toRemove);
  26426. return index;
  26427. };
  26428. /**
  26429. * Remove a camera for the list of scene's cameras
  26430. * @param toRemove defines the camera to remove
  26431. * @returns the index where the camera was in the camera list
  26432. */
  26433. Scene.prototype.removeCamera = function (toRemove) {
  26434. var index = this.cameras.indexOf(toRemove);
  26435. if (index !== -1) {
  26436. // Remove from the scene if mesh found
  26437. this.cameras.splice(index, 1);
  26438. }
  26439. // Remove from activeCameras
  26440. var index2 = this.activeCameras.indexOf(toRemove);
  26441. if (index2 !== -1) {
  26442. // Remove from the scene if mesh found
  26443. this.activeCameras.splice(index2, 1);
  26444. }
  26445. // Reset the activeCamera
  26446. if (this.activeCamera === toRemove) {
  26447. if (this.cameras.length > 0) {
  26448. this.activeCamera = this.cameras[0];
  26449. }
  26450. else {
  26451. this.activeCamera = null;
  26452. }
  26453. }
  26454. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26455. return index;
  26456. };
  26457. /**
  26458. * Remove a particle system for the list of scene's particle systems
  26459. * @param toRemove defines the particle system to remove
  26460. * @returns the index where the particle system was in the particle system list
  26461. */
  26462. Scene.prototype.removeParticleSystem = function (toRemove) {
  26463. var index = this.particleSystems.indexOf(toRemove);
  26464. if (index !== -1) {
  26465. this.particleSystems.splice(index, 1);
  26466. }
  26467. return index;
  26468. };
  26469. /**
  26470. * Remove a animation for the list of scene's animations
  26471. * @param toRemove defines the animation to remove
  26472. * @returns the index where the animation was in the animation list
  26473. */
  26474. Scene.prototype.removeAnimation = function (toRemove) {
  26475. var index = this.animations.indexOf(toRemove);
  26476. if (index !== -1) {
  26477. this.animations.splice(index, 1);
  26478. }
  26479. return index;
  26480. };
  26481. /**
  26482. * Removes the given animation group from this scene.
  26483. * @param toRemove The animation group to remove
  26484. * @returns The index of the removed animation group
  26485. */
  26486. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26487. var index = this.animationGroups.indexOf(toRemove);
  26488. if (index !== -1) {
  26489. this.animationGroups.splice(index, 1);
  26490. }
  26491. return index;
  26492. };
  26493. /**
  26494. * Removes the given multi-material from this scene.
  26495. * @param toRemove The multi-material to remove
  26496. * @returns The index of the removed multi-material
  26497. */
  26498. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26499. var index = this.multiMaterials.indexOf(toRemove);
  26500. if (index !== -1) {
  26501. this.multiMaterials.splice(index, 1);
  26502. }
  26503. return index;
  26504. };
  26505. /**
  26506. * Removes the given material from this scene.
  26507. * @param toRemove The material to remove
  26508. * @returns The index of the removed material
  26509. */
  26510. Scene.prototype.removeMaterial = function (toRemove) {
  26511. var index = this.materials.indexOf(toRemove);
  26512. if (index !== -1) {
  26513. this.materials.splice(index, 1);
  26514. }
  26515. return index;
  26516. };
  26517. /**
  26518. * Removes the given lens flare system from this scene.
  26519. * @param toRemove The lens flare system to remove
  26520. * @returns The index of the removed lens flare system
  26521. */
  26522. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26523. var index = this.lensFlareSystems.indexOf(toRemove);
  26524. if (index !== -1) {
  26525. this.lensFlareSystems.splice(index, 1);
  26526. }
  26527. return index;
  26528. };
  26529. /**
  26530. * Removes the given action manager from this scene.
  26531. * @param toRemove The action manager to remove
  26532. * @returns The index of the removed action manager
  26533. */
  26534. Scene.prototype.removeActionManager = function (toRemove) {
  26535. var index = this._actionManagers.indexOf(toRemove);
  26536. if (index !== -1) {
  26537. this._actionManagers.splice(index, 1);
  26538. }
  26539. return index;
  26540. };
  26541. /**
  26542. * Removes the given effect layer from this scene.
  26543. * @param toRemove defines the effect layer to remove
  26544. * @returns the index of the removed effect layer
  26545. */
  26546. Scene.prototype.removeEffectLayer = function (toRemove) {
  26547. var index = this.effectLayers.indexOf(toRemove);
  26548. if (index !== -1) {
  26549. this.effectLayers.splice(index, 1);
  26550. }
  26551. return index;
  26552. };
  26553. /**
  26554. * Removes the given texture from this scene.
  26555. * @param toRemove The texture to remove
  26556. * @returns The index of the removed texture
  26557. */
  26558. Scene.prototype.removeTexture = function (toRemove) {
  26559. var index = this.textures.indexOf(toRemove);
  26560. if (index !== -1) {
  26561. this.textures.splice(index, 1);
  26562. }
  26563. return index;
  26564. };
  26565. /**
  26566. * Adds the given light to this scene
  26567. * @param newLight The light to add
  26568. */
  26569. Scene.prototype.addLight = function (newLight) {
  26570. this.lights.push(newLight);
  26571. this.sortLightsByPriority();
  26572. // Add light to all meshes (To support if the light is removed and then readded)
  26573. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26574. var mesh = _a[_i];
  26575. if (mesh._lightSources.indexOf(newLight) === -1) {
  26576. mesh._lightSources.push(newLight);
  26577. mesh._resyncLightSources();
  26578. }
  26579. }
  26580. this.onNewLightAddedObservable.notifyObservers(newLight);
  26581. };
  26582. /**
  26583. * Sorts the list list based on light priorities
  26584. */
  26585. Scene.prototype.sortLightsByPriority = function () {
  26586. if (this.requireLightSorting) {
  26587. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26588. }
  26589. };
  26590. /**
  26591. * Adds the given camera to this scene
  26592. * @param newCamera The camera to add
  26593. */
  26594. Scene.prototype.addCamera = function (newCamera) {
  26595. this.cameras.push(newCamera);
  26596. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26597. };
  26598. /**
  26599. * Adds the given skeleton to this scene
  26600. * @param newSkeleton The skeleton to add
  26601. */
  26602. Scene.prototype.addSkeleton = function (newSkeleton) {
  26603. this.skeletons.push(newSkeleton);
  26604. };
  26605. /**
  26606. * Adds the given particle system to this scene
  26607. * @param newParticleSystem The particle system to add
  26608. */
  26609. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26610. this.particleSystems.push(newParticleSystem);
  26611. };
  26612. /**
  26613. * Adds the given animation to this scene
  26614. * @param newAnimation The animation to add
  26615. */
  26616. Scene.prototype.addAnimation = function (newAnimation) {
  26617. this.animations.push(newAnimation);
  26618. };
  26619. /**
  26620. * Adds the given animation group to this scene.
  26621. * @param newAnimationGroup The animation group to add
  26622. */
  26623. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26624. this.animationGroups.push(newAnimationGroup);
  26625. };
  26626. /**
  26627. * Adds the given multi-material to this scene
  26628. * @param newMultiMaterial The multi-material to add
  26629. */
  26630. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26631. this.multiMaterials.push(newMultiMaterial);
  26632. };
  26633. /**
  26634. * Adds the given material to this scene
  26635. * @param newMaterial The material to add
  26636. */
  26637. Scene.prototype.addMaterial = function (newMaterial) {
  26638. this.materials.push(newMaterial);
  26639. };
  26640. /**
  26641. * Adds the given morph target to this scene
  26642. * @param newMorphTargetManager The morph target to add
  26643. */
  26644. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26645. this.morphTargetManagers.push(newMorphTargetManager);
  26646. };
  26647. /**
  26648. * Adds the given geometry to this scene
  26649. * @param newGeometry The geometry to add
  26650. */
  26651. Scene.prototype.addGeometry = function (newGeometry) {
  26652. this._geometries.push(newGeometry);
  26653. };
  26654. /**
  26655. * Adds the given lens flare system to this scene
  26656. * @param newLensFlareSystem The lens flare system to add
  26657. */
  26658. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26659. this.lensFlareSystems.push(newLensFlareSystem);
  26660. };
  26661. /**
  26662. * Adds the given effect layer to this scene
  26663. * @param newEffectLayer defines the effect layer to add
  26664. */
  26665. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26666. this.effectLayers.push(newEffectLayer);
  26667. };
  26668. /**
  26669. * Adds the given action manager to this scene
  26670. * @param newActionManager The action manager to add
  26671. */
  26672. Scene.prototype.addActionManager = function (newActionManager) {
  26673. this._actionManagers.push(newActionManager);
  26674. };
  26675. /**
  26676. * Adds the given texture to this scene.
  26677. * @param newTexture The texture to add
  26678. */
  26679. Scene.prototype.addTexture = function (newTexture) {
  26680. this.textures.push(newTexture);
  26681. };
  26682. /**
  26683. * Switch active camera
  26684. * @param newCamera defines the new active camera
  26685. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26686. */
  26687. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26688. if (attachControl === void 0) { attachControl = true; }
  26689. var canvas = this._engine.getRenderingCanvas();
  26690. if (!canvas) {
  26691. return;
  26692. }
  26693. if (this.activeCamera) {
  26694. this.activeCamera.detachControl(canvas);
  26695. }
  26696. this.activeCamera = newCamera;
  26697. if (attachControl) {
  26698. newCamera.attachControl(canvas);
  26699. }
  26700. };
  26701. /**
  26702. * sets the active camera of the scene using its ID
  26703. * @param id defines the camera's ID
  26704. * @return the new active camera or null if none found.
  26705. */
  26706. Scene.prototype.setActiveCameraByID = function (id) {
  26707. var camera = this.getCameraByID(id);
  26708. if (camera) {
  26709. this.activeCamera = camera;
  26710. return camera;
  26711. }
  26712. return null;
  26713. };
  26714. /**
  26715. * sets the active camera of the scene using its name
  26716. * @param name defines the camera's name
  26717. * @returns the new active camera or null if none found.
  26718. */
  26719. Scene.prototype.setActiveCameraByName = function (name) {
  26720. var camera = this.getCameraByName(name);
  26721. if (camera) {
  26722. this.activeCamera = camera;
  26723. return camera;
  26724. }
  26725. return null;
  26726. };
  26727. /**
  26728. * get an animation group using its name
  26729. * @param name defines the material's name
  26730. * @return the animation group or null if none found.
  26731. */
  26732. Scene.prototype.getAnimationGroupByName = function (name) {
  26733. for (var index = 0; index < this.animationGroups.length; index++) {
  26734. if (this.animationGroups[index].name === name) {
  26735. return this.animationGroups[index];
  26736. }
  26737. }
  26738. return null;
  26739. };
  26740. /**
  26741. * get a material using its id
  26742. * @param id defines the material's ID
  26743. * @return the material or null if none found.
  26744. */
  26745. Scene.prototype.getMaterialByID = function (id) {
  26746. for (var index = 0; index < this.materials.length; index++) {
  26747. if (this.materials[index].id === id) {
  26748. return this.materials[index];
  26749. }
  26750. }
  26751. return null;
  26752. };
  26753. /**
  26754. * Gets a material using its name
  26755. * @param name defines the material's name
  26756. * @return the material or null if none found.
  26757. */
  26758. Scene.prototype.getMaterialByName = function (name) {
  26759. for (var index = 0; index < this.materials.length; index++) {
  26760. if (this.materials[index].name === name) {
  26761. return this.materials[index];
  26762. }
  26763. }
  26764. return null;
  26765. };
  26766. /**
  26767. * Gets a lens flare system using its name
  26768. * @param name defines the name to look for
  26769. * @returns the lens flare system or null if not found
  26770. */
  26771. Scene.prototype.getLensFlareSystemByName = function (name) {
  26772. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26773. if (this.lensFlareSystems[index].name === name) {
  26774. return this.lensFlareSystems[index];
  26775. }
  26776. }
  26777. return null;
  26778. };
  26779. /**
  26780. * Gets a lens flare system using its id
  26781. * @param id defines the id to look for
  26782. * @returns the lens flare system or null if not found
  26783. */
  26784. Scene.prototype.getLensFlareSystemByID = function (id) {
  26785. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26786. if (this.lensFlareSystems[index].id === id) {
  26787. return this.lensFlareSystems[index];
  26788. }
  26789. }
  26790. return null;
  26791. };
  26792. /**
  26793. * Gets a camera using its id
  26794. * @param id defines the id to look for
  26795. * @returns the camera or null if not found
  26796. */
  26797. Scene.prototype.getCameraByID = function (id) {
  26798. for (var index = 0; index < this.cameras.length; index++) {
  26799. if (this.cameras[index].id === id) {
  26800. return this.cameras[index];
  26801. }
  26802. }
  26803. return null;
  26804. };
  26805. /**
  26806. * Gets a camera using its unique id
  26807. * @param uniqueId defines the unique id to look for
  26808. * @returns the camera or null if not found
  26809. */
  26810. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26811. for (var index = 0; index < this.cameras.length; index++) {
  26812. if (this.cameras[index].uniqueId === uniqueId) {
  26813. return this.cameras[index];
  26814. }
  26815. }
  26816. return null;
  26817. };
  26818. /**
  26819. * Gets a camera using its name
  26820. * @param name defines the camera's name
  26821. * @return the camera or null if none found.
  26822. */
  26823. Scene.prototype.getCameraByName = function (name) {
  26824. for (var index = 0; index < this.cameras.length; index++) {
  26825. if (this.cameras[index].name === name) {
  26826. return this.cameras[index];
  26827. }
  26828. }
  26829. return null;
  26830. };
  26831. /**
  26832. * Gets a bone using its id
  26833. * @param id defines the bone's id
  26834. * @return the bone or null if not found
  26835. */
  26836. Scene.prototype.getBoneByID = function (id) {
  26837. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26838. var skeleton = this.skeletons[skeletonIndex];
  26839. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26840. if (skeleton.bones[boneIndex].id === id) {
  26841. return skeleton.bones[boneIndex];
  26842. }
  26843. }
  26844. }
  26845. return null;
  26846. };
  26847. /**
  26848. * Gets a bone using its id
  26849. * @param name defines the bone's name
  26850. * @return the bone or null if not found
  26851. */
  26852. Scene.prototype.getBoneByName = function (name) {
  26853. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26854. var skeleton = this.skeletons[skeletonIndex];
  26855. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26856. if (skeleton.bones[boneIndex].name === name) {
  26857. return skeleton.bones[boneIndex];
  26858. }
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * Gets a light node using its name
  26865. * @param name defines the the light's name
  26866. * @return the light or null if none found.
  26867. */
  26868. Scene.prototype.getLightByName = function (name) {
  26869. for (var index = 0; index < this.lights.length; index++) {
  26870. if (this.lights[index].name === name) {
  26871. return this.lights[index];
  26872. }
  26873. }
  26874. return null;
  26875. };
  26876. /**
  26877. * Gets a light node using its id
  26878. * @param id defines the light's id
  26879. * @return the light or null if none found.
  26880. */
  26881. Scene.prototype.getLightByID = function (id) {
  26882. for (var index = 0; index < this.lights.length; index++) {
  26883. if (this.lights[index].id === id) {
  26884. return this.lights[index];
  26885. }
  26886. }
  26887. return null;
  26888. };
  26889. /**
  26890. * Gets a light node using its scene-generated unique ID
  26891. * @param uniqueId defines the light's unique id
  26892. * @return the light or null if none found.
  26893. */
  26894. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26895. for (var index = 0; index < this.lights.length; index++) {
  26896. if (this.lights[index].uniqueId === uniqueId) {
  26897. return this.lights[index];
  26898. }
  26899. }
  26900. return null;
  26901. };
  26902. /**
  26903. * Gets a particle system by id
  26904. * @param id defines the particle system id
  26905. * @return the corresponding system or null if none found
  26906. */
  26907. Scene.prototype.getParticleSystemByID = function (id) {
  26908. for (var index = 0; index < this.particleSystems.length; index++) {
  26909. if (this.particleSystems[index].id === id) {
  26910. return this.particleSystems[index];
  26911. }
  26912. }
  26913. return null;
  26914. };
  26915. /**
  26916. * Gets a geometry using its ID
  26917. * @param id defines the geometry's id
  26918. * @return the geometry or null if none found.
  26919. */
  26920. Scene.prototype.getGeometryByID = function (id) {
  26921. for (var index = 0; index < this._geometries.length; index++) {
  26922. if (this._geometries[index].id === id) {
  26923. return this._geometries[index];
  26924. }
  26925. }
  26926. return null;
  26927. };
  26928. /**
  26929. * Add a new geometry to this scene
  26930. * @param geometry defines the geometry to be added to the scene.
  26931. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26932. * @return a boolean defining if the geometry was added or not
  26933. */
  26934. Scene.prototype.pushGeometry = function (geometry, force) {
  26935. if (!force && this.getGeometryByID(geometry.id)) {
  26936. return false;
  26937. }
  26938. this._geometries.push(geometry);
  26939. //notify the collision coordinator
  26940. if (this.collisionCoordinator) {
  26941. this.collisionCoordinator.onGeometryAdded(geometry);
  26942. }
  26943. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26944. return true;
  26945. };
  26946. /**
  26947. * Removes an existing geometry
  26948. * @param geometry defines the geometry to be removed from the scene
  26949. * @return a boolean defining if the geometry was removed or not
  26950. */
  26951. Scene.prototype.removeGeometry = function (geometry) {
  26952. var index = this._geometries.indexOf(geometry);
  26953. if (index > -1) {
  26954. this._geometries.splice(index, 1);
  26955. //notify the collision coordinator
  26956. if (this.collisionCoordinator) {
  26957. this.collisionCoordinator.onGeometryDeleted(geometry);
  26958. }
  26959. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26960. return true;
  26961. }
  26962. return false;
  26963. };
  26964. /**
  26965. * Gets the list of geometries attached to the scene
  26966. * @returns an array of Geometry
  26967. */
  26968. Scene.prototype.getGeometries = function () {
  26969. return this._geometries;
  26970. };
  26971. /**
  26972. * Gets the first added mesh found of a given ID
  26973. * @param id defines the id to search for
  26974. * @return the mesh found or null if not found at all
  26975. */
  26976. Scene.prototype.getMeshByID = function (id) {
  26977. for (var index = 0; index < this.meshes.length; index++) {
  26978. if (this.meshes[index].id === id) {
  26979. return this.meshes[index];
  26980. }
  26981. }
  26982. return null;
  26983. };
  26984. /**
  26985. * Gets a list of meshes using their id
  26986. * @param id defines the id to search for
  26987. * @returns a list of meshes
  26988. */
  26989. Scene.prototype.getMeshesByID = function (id) {
  26990. return this.meshes.filter(function (m) {
  26991. return m.id === id;
  26992. });
  26993. };
  26994. /**
  26995. * Gets the first added transform node found of a given ID
  26996. * @param id defines the id to search for
  26997. * @return the found transform node or null if not found at all.
  26998. */
  26999. Scene.prototype.getTransformNodeByID = function (id) {
  27000. for (var index = 0; index < this.transformNodes.length; index++) {
  27001. if (this.transformNodes[index].id === id) {
  27002. return this.transformNodes[index];
  27003. }
  27004. }
  27005. return null;
  27006. };
  27007. /**
  27008. * Gets a list of transform nodes using their id
  27009. * @param id defines the id to search for
  27010. * @returns a list of transform nodes
  27011. */
  27012. Scene.prototype.getTransformNodesByID = function (id) {
  27013. return this.transformNodes.filter(function (m) {
  27014. return m.id === id;
  27015. });
  27016. };
  27017. /**
  27018. * Gets a mesh with its auto-generated unique id
  27019. * @param uniqueId defines the unique id to search for
  27020. * @return the found mesh or null if not found at all.
  27021. */
  27022. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27023. for (var index = 0; index < this.meshes.length; index++) {
  27024. if (this.meshes[index].uniqueId === uniqueId) {
  27025. return this.meshes[index];
  27026. }
  27027. }
  27028. return null;
  27029. };
  27030. /**
  27031. * Gets a the last added mesh using a given id
  27032. * @param id defines the id to search for
  27033. * @return the found mesh or null if not found at all.
  27034. */
  27035. Scene.prototype.getLastMeshByID = function (id) {
  27036. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27037. if (this.meshes[index].id === id) {
  27038. return this.meshes[index];
  27039. }
  27040. }
  27041. return null;
  27042. };
  27043. /**
  27044. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27045. * @param id defines the id to search for
  27046. * @return the found node or null if not found at all
  27047. */
  27048. Scene.prototype.getLastEntryByID = function (id) {
  27049. var index;
  27050. for (index = this.meshes.length - 1; index >= 0; index--) {
  27051. if (this.meshes[index].id === id) {
  27052. return this.meshes[index];
  27053. }
  27054. }
  27055. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27056. if (this.transformNodes[index].id === id) {
  27057. return this.transformNodes[index];
  27058. }
  27059. }
  27060. for (index = this.cameras.length - 1; index >= 0; index--) {
  27061. if (this.cameras[index].id === id) {
  27062. return this.cameras[index];
  27063. }
  27064. }
  27065. for (index = this.lights.length - 1; index >= 0; index--) {
  27066. if (this.lights[index].id === id) {
  27067. return this.lights[index];
  27068. }
  27069. }
  27070. return null;
  27071. };
  27072. /**
  27073. * Gets a node (Mesh, Camera, Light) using a given id
  27074. * @param id defines the id to search for
  27075. * @return the found node or null if not found at all
  27076. */
  27077. Scene.prototype.getNodeByID = function (id) {
  27078. var mesh = this.getMeshByID(id);
  27079. if (mesh) {
  27080. return mesh;
  27081. }
  27082. var light = this.getLightByID(id);
  27083. if (light) {
  27084. return light;
  27085. }
  27086. var camera = this.getCameraByID(id);
  27087. if (camera) {
  27088. return camera;
  27089. }
  27090. var bone = this.getBoneByID(id);
  27091. return bone;
  27092. };
  27093. /**
  27094. * Gets a node (Mesh, Camera, Light) using a given name
  27095. * @param name defines the name to search for
  27096. * @return the found node or null if not found at all.
  27097. */
  27098. Scene.prototype.getNodeByName = function (name) {
  27099. var mesh = this.getMeshByName(name);
  27100. if (mesh) {
  27101. return mesh;
  27102. }
  27103. var light = this.getLightByName(name);
  27104. if (light) {
  27105. return light;
  27106. }
  27107. var camera = this.getCameraByName(name);
  27108. if (camera) {
  27109. return camera;
  27110. }
  27111. var bone = this.getBoneByName(name);
  27112. return bone;
  27113. };
  27114. /**
  27115. * Gets a mesh using a given name
  27116. * @param name defines the name to search for
  27117. * @return the found mesh or null if not found at all.
  27118. */
  27119. Scene.prototype.getMeshByName = function (name) {
  27120. for (var index = 0; index < this.meshes.length; index++) {
  27121. if (this.meshes[index].name === name) {
  27122. return this.meshes[index];
  27123. }
  27124. }
  27125. return null;
  27126. };
  27127. /**
  27128. * Gets a transform node using a given name
  27129. * @param name defines the name to search for
  27130. * @return the found transform node or null if not found at all.
  27131. */
  27132. Scene.prototype.getTransformNodeByName = function (name) {
  27133. for (var index = 0; index < this.transformNodes.length; index++) {
  27134. if (this.transformNodes[index].name === name) {
  27135. return this.transformNodes[index];
  27136. }
  27137. }
  27138. return null;
  27139. };
  27140. /**
  27141. * Gets a sound using a given name
  27142. * @param name defines the name to search for
  27143. * @return the found sound or null if not found at all.
  27144. */
  27145. Scene.prototype.getSoundByName = function (name) {
  27146. var index;
  27147. if (BABYLON.AudioEngine) {
  27148. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27149. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27150. return this.mainSoundTrack.soundCollection[index];
  27151. }
  27152. }
  27153. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27154. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27155. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27156. return this.soundTracks[sdIndex].soundCollection[index];
  27157. }
  27158. }
  27159. }
  27160. }
  27161. return null;
  27162. };
  27163. /**
  27164. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27165. * @param id defines the id to search for
  27166. * @return the found skeleton or null if not found at all.
  27167. */
  27168. Scene.prototype.getLastSkeletonByID = function (id) {
  27169. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27170. if (this.skeletons[index].id === id) {
  27171. return this.skeletons[index];
  27172. }
  27173. }
  27174. return null;
  27175. };
  27176. /**
  27177. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27178. * @param id defines the id to search for
  27179. * @return the found skeleton or null if not found at all.
  27180. */
  27181. Scene.prototype.getSkeletonById = function (id) {
  27182. for (var index = 0; index < this.skeletons.length; index++) {
  27183. if (this.skeletons[index].id === id) {
  27184. return this.skeletons[index];
  27185. }
  27186. }
  27187. return null;
  27188. };
  27189. /**
  27190. * Gets a skeleton using a given name
  27191. * @param name defines the name to search for
  27192. * @return the found skeleton or null if not found at all.
  27193. */
  27194. Scene.prototype.getSkeletonByName = function (name) {
  27195. for (var index = 0; index < this.skeletons.length; index++) {
  27196. if (this.skeletons[index].name === name) {
  27197. return this.skeletons[index];
  27198. }
  27199. }
  27200. return null;
  27201. };
  27202. /**
  27203. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27204. * @param id defines the id to search for
  27205. * @return the found morph target manager or null if not found at all.
  27206. */
  27207. Scene.prototype.getMorphTargetManagerById = function (id) {
  27208. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27209. if (this.morphTargetManagers[index].uniqueId === id) {
  27210. return this.morphTargetManagers[index];
  27211. }
  27212. }
  27213. return null;
  27214. };
  27215. /**
  27216. * Gets a boolean indicating if the given mesh is active
  27217. * @param mesh defines the mesh to look for
  27218. * @returns true if the mesh is in the active list
  27219. */
  27220. Scene.prototype.isActiveMesh = function (mesh) {
  27221. return (this._activeMeshes.indexOf(mesh) !== -1);
  27222. };
  27223. /**
  27224. * Return a the first highlight layer of the scene with a given name.
  27225. * @param name The name of the highlight layer to look for.
  27226. * @return The highlight layer if found otherwise null.
  27227. */
  27228. Scene.prototype.getHighlightLayerByName = function (name) {
  27229. for (var index = 0; index < this.effectLayers.length; index++) {
  27230. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27231. return this.effectLayers[index];
  27232. }
  27233. }
  27234. return null;
  27235. };
  27236. /**
  27237. * Return a the first highlight layer of the scene with a given name.
  27238. * @param name The name of the highlight layer to look for.
  27239. * @return The highlight layer if found otherwise null.
  27240. */
  27241. Scene.prototype.getGlowLayerByName = function (name) {
  27242. for (var index = 0; index < this.effectLayers.length; index++) {
  27243. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27244. return this.effectLayers[index];
  27245. }
  27246. }
  27247. return null;
  27248. };
  27249. Object.defineProperty(Scene.prototype, "uid", {
  27250. /**
  27251. * Return a unique id as a string which can serve as an identifier for the scene
  27252. */
  27253. get: function () {
  27254. if (!this._uid) {
  27255. this._uid = BABYLON.Tools.RandomId();
  27256. }
  27257. return this._uid;
  27258. },
  27259. enumerable: true,
  27260. configurable: true
  27261. });
  27262. /**
  27263. * Add an externaly attached data from its key.
  27264. * This method call will fail and return false, if such key already exists.
  27265. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27266. * @param key the unique key that identifies the data
  27267. * @param data the data object to associate to the key for this Engine instance
  27268. * @return true if no such key were already present and the data was added successfully, false otherwise
  27269. */
  27270. Scene.prototype.addExternalData = function (key, data) {
  27271. if (!this._externalData) {
  27272. this._externalData = new BABYLON.StringDictionary();
  27273. }
  27274. return this._externalData.add(key, data);
  27275. };
  27276. /**
  27277. * Get an externaly attached data from its key
  27278. * @param key the unique key that identifies the data
  27279. * @return the associated data, if present (can be null), or undefined if not present
  27280. */
  27281. Scene.prototype.getExternalData = function (key) {
  27282. if (!this._externalData) {
  27283. return null;
  27284. }
  27285. return this._externalData.get(key);
  27286. };
  27287. /**
  27288. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27289. * @param key the unique key that identifies the data
  27290. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27291. * @return the associated data, can be null if the factory returned null.
  27292. */
  27293. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27294. if (!this._externalData) {
  27295. this._externalData = new BABYLON.StringDictionary();
  27296. }
  27297. return this._externalData.getOrAddWithFactory(key, factory);
  27298. };
  27299. /**
  27300. * Remove an externaly attached data from the Engine instance
  27301. * @param key the unique key that identifies the data
  27302. * @return true if the data was successfully removed, false if it doesn't exist
  27303. */
  27304. Scene.prototype.removeExternalData = function (key) {
  27305. return this._externalData.remove(key);
  27306. };
  27307. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27308. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27309. if (mesh.showSubMeshesBoundingBox) {
  27310. var boundingInfo = subMesh.getBoundingInfo();
  27311. if (boundingInfo !== null && boundingInfo !== undefined) {
  27312. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27313. }
  27314. }
  27315. var material = subMesh.getMaterial();
  27316. if (material !== null && material !== undefined) {
  27317. // Render targets
  27318. if (material.getRenderTargetTextures !== undefined) {
  27319. if (this._processedMaterials.indexOf(material) === -1) {
  27320. this._processedMaterials.push(material);
  27321. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27322. }
  27323. }
  27324. // Dispatch
  27325. this._activeIndices.addCount(subMesh.indexCount, false);
  27326. this._renderingManager.dispatch(subMesh, mesh, material);
  27327. }
  27328. }
  27329. };
  27330. /**
  27331. * Clear the processed materials smart array preventing retention point in material dispose.
  27332. */
  27333. Scene.prototype.freeProcessedMaterials = function () {
  27334. this._processedMaterials.dispose();
  27335. };
  27336. /**
  27337. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27338. */
  27339. Scene.prototype.freeActiveMeshes = function () {
  27340. this._activeMeshes.dispose();
  27341. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27342. this.activeCamera._activeMeshes.dispose();
  27343. }
  27344. if (this.activeCameras) {
  27345. for (var i = 0; i < this.activeCameras.length; i++) {
  27346. var activeCamera = this.activeCameras[i];
  27347. if (activeCamera && activeCamera._activeMeshes) {
  27348. activeCamera._activeMeshes.dispose();
  27349. }
  27350. }
  27351. }
  27352. };
  27353. /**
  27354. * Clear the info related to rendering groups preventing retention points during dispose.
  27355. */
  27356. Scene.prototype.freeRenderingGroups = function () {
  27357. if (this._renderingManager) {
  27358. this._renderingManager.freeRenderingGroups();
  27359. }
  27360. if (this.textures) {
  27361. for (var i = 0; i < this.textures.length; i++) {
  27362. var texture = this.textures[i];
  27363. if (texture && texture.renderList) {
  27364. texture.freeRenderingGroups();
  27365. }
  27366. }
  27367. }
  27368. };
  27369. /** @hidden */
  27370. Scene.prototype._isInIntermediateRendering = function () {
  27371. return this._intermediateRendering;
  27372. };
  27373. /**
  27374. * Defines the current active mesh candidate provider
  27375. * @param provider defines the provider to use
  27376. */
  27377. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27378. this._activeMeshCandidateProvider = provider;
  27379. };
  27380. /**
  27381. * Gets the current active mesh candidate provider
  27382. * @returns the current active mesh candidate provider
  27383. */
  27384. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27385. return this._activeMeshCandidateProvider;
  27386. };
  27387. /**
  27388. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27389. * @returns the current scene
  27390. */
  27391. Scene.prototype.freezeActiveMeshes = function () {
  27392. if (!this.activeCamera) {
  27393. return this;
  27394. }
  27395. if (!this._frustumPlanes) {
  27396. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27397. }
  27398. this._evaluateActiveMeshes();
  27399. this._activeMeshesFrozen = true;
  27400. return this;
  27401. };
  27402. /**
  27403. * Use this function to restart evaluating active meshes on every frame
  27404. * @returns the current scene
  27405. */
  27406. Scene.prototype.unfreezeActiveMeshes = function () {
  27407. this._activeMeshesFrozen = false;
  27408. return this;
  27409. };
  27410. Scene.prototype._evaluateActiveMeshes = function () {
  27411. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27412. return;
  27413. }
  27414. if (!this.activeCamera) {
  27415. return;
  27416. }
  27417. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27418. this.activeCamera._activeMeshes.reset();
  27419. this._activeMeshes.reset();
  27420. this._renderingManager.reset();
  27421. this._processedMaterials.reset();
  27422. this._activeParticleSystems.reset();
  27423. this._activeSkeletons.reset();
  27424. this._softwareSkinnedMeshes.reset();
  27425. if (this._boundingBoxRenderer) {
  27426. this._boundingBoxRenderer.reset();
  27427. }
  27428. // Meshes
  27429. var meshes;
  27430. var len;
  27431. var checkIsEnabled = true;
  27432. // Determine mesh candidates
  27433. if (this._activeMeshCandidateProvider !== undefined) {
  27434. // Use _activeMeshCandidateProvider
  27435. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27436. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27437. if (meshes !== undefined) {
  27438. len = meshes.length;
  27439. }
  27440. else {
  27441. len = 0;
  27442. }
  27443. }
  27444. else if (this._selectionOctree !== undefined) {
  27445. // Octree
  27446. var selection = this._selectionOctree.select(this._frustumPlanes);
  27447. meshes = selection.data;
  27448. len = selection.length;
  27449. }
  27450. else {
  27451. // Full scene traversal
  27452. len = this.meshes.length;
  27453. meshes = this.meshes;
  27454. }
  27455. // Check each mesh
  27456. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27457. mesh = meshes[meshIndex];
  27458. if (mesh.isBlocked) {
  27459. continue;
  27460. }
  27461. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27462. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27463. continue;
  27464. }
  27465. mesh.computeWorldMatrix();
  27466. // Intersections
  27467. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27468. this._meshesForIntersections.pushNoDuplicate(mesh);
  27469. }
  27470. // Switch to current LOD
  27471. meshLOD = mesh.getLOD(this.activeCamera);
  27472. if (meshLOD === undefined || meshLOD === null) {
  27473. continue;
  27474. }
  27475. mesh._preActivate();
  27476. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27477. this._activeMeshes.push(mesh);
  27478. this.activeCamera._activeMeshes.push(mesh);
  27479. mesh._activate(this._renderId);
  27480. if (meshLOD !== mesh) {
  27481. meshLOD._activate(this._renderId);
  27482. }
  27483. this._activeMesh(mesh, meshLOD);
  27484. }
  27485. }
  27486. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27487. // Particle systems
  27488. if (this.particlesEnabled) {
  27489. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27490. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27491. var particleSystem = this.particleSystems[particleIndex];
  27492. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27493. continue;
  27494. }
  27495. var emitter = particleSystem.emitter;
  27496. if (!emitter.position || emitter.isEnabled()) {
  27497. this._activeParticleSystems.push(particleSystem);
  27498. particleSystem.animate();
  27499. this._renderingManager.dispatchParticles(particleSystem);
  27500. }
  27501. }
  27502. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27503. }
  27504. };
  27505. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27506. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27507. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27508. mesh.skeleton.prepare();
  27509. }
  27510. if (!mesh.computeBonesUsingShaders) {
  27511. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27512. }
  27513. }
  27514. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27515. var boundingInfo = sourceMesh.getBoundingInfo();
  27516. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27517. }
  27518. if (mesh !== undefined && mesh !== null
  27519. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27520. // Submeshes Octrees
  27521. var len;
  27522. var subMeshes;
  27523. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27524. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27525. len = intersections.length;
  27526. subMeshes = intersections.data;
  27527. }
  27528. else {
  27529. subMeshes = mesh.subMeshes;
  27530. len = subMeshes.length;
  27531. }
  27532. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27533. subMesh = subMeshes[subIndex];
  27534. this._evaluateSubMesh(subMesh, mesh);
  27535. }
  27536. }
  27537. };
  27538. /**
  27539. * Update the transform matrix to update from the current active camera
  27540. * @param force defines a boolean used to force the update even if cache is up to date
  27541. */
  27542. Scene.prototype.updateTransformMatrix = function (force) {
  27543. if (!this.activeCamera) {
  27544. return;
  27545. }
  27546. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27547. };
  27548. /**
  27549. * 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)
  27550. * @param alternateCamera defines the camera to use
  27551. */
  27552. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27553. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27554. };
  27555. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27556. if (camera && camera._skipRendering) {
  27557. return;
  27558. }
  27559. var engine = this._engine;
  27560. this.activeCamera = camera;
  27561. if (!this.activeCamera)
  27562. throw new Error("Active camera not set");
  27563. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27564. // Viewport
  27565. engine.setViewport(this.activeCamera.viewport);
  27566. // Camera
  27567. this.resetCachedMaterial();
  27568. this._renderId++;
  27569. this.updateTransformMatrix();
  27570. if (camera._alternateCamera) {
  27571. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27572. this._alternateRendering = true;
  27573. }
  27574. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27575. // Meshes
  27576. this._evaluateActiveMeshes();
  27577. // Software skinning
  27578. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27579. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27580. mesh.applySkeleton(mesh.skeleton);
  27581. }
  27582. // Render targets
  27583. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27584. var needsRestoreFrameBuffer = false;
  27585. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27586. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27587. }
  27588. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27589. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27590. }
  27591. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27592. this._intermediateRendering = true;
  27593. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27594. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27595. var renderTarget = this._renderTargets.data[renderIndex];
  27596. if (renderTarget._shouldRender()) {
  27597. this._renderId++;
  27598. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27599. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27600. }
  27601. }
  27602. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27603. this._intermediateRendering = false;
  27604. this._renderId++;
  27605. needsRestoreFrameBuffer = true; // Restore back buffer
  27606. }
  27607. // Render EffecttLayer Texture
  27608. var stencilState = this._engine.getStencilBuffer();
  27609. var renderEffects = false;
  27610. var needStencil = false;
  27611. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27612. this._intermediateRendering = true;
  27613. for (var i = 0; i < this.effectLayers.length; i++) {
  27614. var effectLayer = this.effectLayers[i];
  27615. if (effectLayer.shouldRender() &&
  27616. (!effectLayer.camera ||
  27617. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27618. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27619. renderEffects = true;
  27620. needStencil = needStencil || effectLayer.needStencil();
  27621. var renderTarget = effectLayer._mainTexture;
  27622. if (renderTarget._shouldRender()) {
  27623. this._renderId++;
  27624. renderTarget.render(false, false);
  27625. needsRestoreFrameBuffer = true;
  27626. }
  27627. }
  27628. }
  27629. this._intermediateRendering = false;
  27630. this._renderId++;
  27631. }
  27632. if (needsRestoreFrameBuffer) {
  27633. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27634. }
  27635. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27636. // Prepare Frame
  27637. this.postProcessManager._prepareFrame();
  27638. // Backgrounds
  27639. var layerIndex;
  27640. var layer;
  27641. if (this.layers.length) {
  27642. engine.setDepthBuffer(false);
  27643. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27644. layer = this.layers[layerIndex];
  27645. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27646. layer.render();
  27647. }
  27648. }
  27649. engine.setDepthBuffer(true);
  27650. }
  27651. // Activate effect Layer stencil
  27652. if (needStencil) {
  27653. this._engine.setStencilBuffer(true);
  27654. }
  27655. // Render
  27656. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27657. this._renderingManager.render(null, null, true, true);
  27658. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27659. // Restore effect Layer stencil
  27660. if (needStencil) {
  27661. this._engine.setStencilBuffer(stencilState);
  27662. }
  27663. // Bounding boxes
  27664. if (this._boundingBoxRenderer) {
  27665. this._boundingBoxRenderer.render();
  27666. }
  27667. // Lens flares
  27668. if (this.lensFlaresEnabled) {
  27669. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27670. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27671. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27672. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27673. lensFlareSystem.render();
  27674. }
  27675. }
  27676. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27677. }
  27678. // Effect Layer
  27679. if (renderEffects) {
  27680. engine.setDepthBuffer(false);
  27681. for (var i = 0; i < this.effectLayers.length; i++) {
  27682. if (this.effectLayers[i].shouldRender()) {
  27683. this.effectLayers[i].render();
  27684. }
  27685. }
  27686. engine.setDepthBuffer(true);
  27687. }
  27688. // Foregrounds
  27689. if (this.layers.length) {
  27690. engine.setDepthBuffer(false);
  27691. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27692. layer = this.layers[layerIndex];
  27693. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27694. layer.render();
  27695. }
  27696. }
  27697. engine.setDepthBuffer(true);
  27698. }
  27699. // Finalize frame
  27700. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27701. // Reset some special arrays
  27702. this._renderTargets.reset();
  27703. this._alternateRendering = false;
  27704. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27705. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27706. };
  27707. Scene.prototype._processSubCameras = function (camera) {
  27708. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27709. this._renderForCamera(camera);
  27710. return;
  27711. }
  27712. // rig cameras
  27713. for (var index = 0; index < camera._rigCameras.length; index++) {
  27714. this._renderForCamera(camera._rigCameras[index], camera);
  27715. }
  27716. this.activeCamera = camera;
  27717. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27718. };
  27719. Scene.prototype._checkIntersections = function () {
  27720. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27721. var sourceMesh = this._meshesForIntersections.data[index];
  27722. if (!sourceMesh.actionManager) {
  27723. continue;
  27724. }
  27725. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27726. var action = sourceMesh.actionManager.actions[actionIndex];
  27727. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27728. var parameters = action.getTriggerParameter();
  27729. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27730. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27731. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27732. if (areIntersecting && currentIntersectionInProgress === -1) {
  27733. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27734. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27735. sourceMesh._intersectionsInProgress.push(otherMesh);
  27736. }
  27737. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27738. sourceMesh._intersectionsInProgress.push(otherMesh);
  27739. }
  27740. }
  27741. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27742. //They intersected, and now they don't.
  27743. //is this trigger an exit trigger? execute an event.
  27744. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27745. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27746. }
  27747. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27748. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27749. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27750. return otherMesh === parameterMesh;
  27751. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27752. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27753. }
  27754. }
  27755. }
  27756. }
  27757. }
  27758. };
  27759. /**
  27760. * Render the scene
  27761. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27762. */
  27763. Scene.prototype.render = function (updateCameras) {
  27764. if (updateCameras === void 0) { updateCameras = true; }
  27765. if (this.isDisposed) {
  27766. return;
  27767. }
  27768. this._activeParticles.fetchNewFrame();
  27769. this._totalVertices.fetchNewFrame();
  27770. this._activeIndices.fetchNewFrame();
  27771. this._activeBones.fetchNewFrame();
  27772. this._meshesForIntersections.reset();
  27773. this.resetCachedMaterial();
  27774. this.onBeforeAnimationsObservable.notifyObservers(this);
  27775. // Actions
  27776. if (this.actionManager) {
  27777. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27778. }
  27779. //Simplification Queue
  27780. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27781. this.simplificationQueue.executeNext();
  27782. }
  27783. if (this._engine.isDeterministicLockStep()) {
  27784. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27785. var defaultFPS = (60.0 / 1000.0);
  27786. var defaultFrameTime = 1000 / 60; // frame time in MS
  27787. if (this._physicsEngine) {
  27788. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27789. }
  27790. var stepsTaken = 0;
  27791. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27792. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27793. internalSteps = Math.min(internalSteps, maxSubSteps);
  27794. do {
  27795. this.onBeforeStepObservable.notifyObservers(this);
  27796. // Animations
  27797. this._animationRatio = defaultFrameTime * defaultFPS;
  27798. this._animate();
  27799. this.onAfterAnimationsObservable.notifyObservers(this);
  27800. // Physics
  27801. if (this._physicsEngine) {
  27802. this.onBeforePhysicsObservable.notifyObservers(this);
  27803. this._physicsEngine._step(defaultFrameTime / 1000);
  27804. this.onAfterPhysicsObservable.notifyObservers(this);
  27805. }
  27806. this.onAfterStepObservable.notifyObservers(this);
  27807. this._currentStepId++;
  27808. stepsTaken++;
  27809. deltaTime -= defaultFrameTime;
  27810. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27811. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27812. }
  27813. else {
  27814. // Animations
  27815. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27816. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27817. this._animate();
  27818. this.onAfterAnimationsObservable.notifyObservers(this);
  27819. // Physics
  27820. if (this._physicsEngine) {
  27821. this.onBeforePhysicsObservable.notifyObservers(this);
  27822. this._physicsEngine._step(deltaTime / 1000.0);
  27823. this.onAfterPhysicsObservable.notifyObservers(this);
  27824. }
  27825. }
  27826. // update gamepad manager
  27827. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27828. this._gamepadManager._checkGamepadsStatus();
  27829. }
  27830. // Update Cameras
  27831. if (updateCameras) {
  27832. if (this.activeCameras.length > 0) {
  27833. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27834. var camera = this.activeCameras[cameraIndex];
  27835. camera.update();
  27836. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27837. // rig cameras
  27838. for (var index = 0; index < camera._rigCameras.length; index++) {
  27839. camera._rigCameras[index].update();
  27840. }
  27841. }
  27842. }
  27843. }
  27844. else if (this.activeCamera) {
  27845. this.activeCamera.update();
  27846. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27847. // rig cameras
  27848. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27849. this.activeCamera._rigCameras[index].update();
  27850. }
  27851. }
  27852. }
  27853. }
  27854. // Before render
  27855. this.onBeforeRenderObservable.notifyObservers(this);
  27856. // Customs render targets
  27857. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27858. var engine = this.getEngine();
  27859. var currentActiveCamera = this.activeCamera;
  27860. if (this.renderTargetsEnabled) {
  27861. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27862. this._intermediateRendering = true;
  27863. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27864. var renderTarget = this.customRenderTargets[customIndex];
  27865. if (renderTarget._shouldRender()) {
  27866. this._renderId++;
  27867. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27868. if (!this.activeCamera)
  27869. throw new Error("Active camera not set");
  27870. // Viewport
  27871. engine.setViewport(this.activeCamera.viewport);
  27872. // Camera
  27873. this.updateTransformMatrix();
  27874. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27875. }
  27876. }
  27877. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27878. this._intermediateRendering = false;
  27879. this._renderId++;
  27880. }
  27881. // Restore back buffer
  27882. if (this.customRenderTargets.length > 0) {
  27883. engine.restoreDefaultFramebuffer();
  27884. }
  27885. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27886. this.activeCamera = currentActiveCamera;
  27887. // Procedural textures
  27888. if (this.proceduralTexturesEnabled) {
  27889. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27890. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27891. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27892. if (proceduralTexture._shouldRender()) {
  27893. proceduralTexture.render();
  27894. }
  27895. }
  27896. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27897. }
  27898. // Clear
  27899. if (this.autoClearDepthAndStencil || this.autoClear) {
  27900. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27901. }
  27902. // Shadows
  27903. if (this.shadowsEnabled) {
  27904. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27905. var light = this.lights[lightIndex];
  27906. var shadowGenerator = light.getShadowGenerator();
  27907. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27908. var shadowMap = (shadowGenerator.getShadowMap());
  27909. if (this.textures.indexOf(shadowMap) !== -1) {
  27910. this._renderTargets.push(shadowMap);
  27911. }
  27912. }
  27913. }
  27914. }
  27915. // Depth renderer
  27916. for (var key in this._depthRenderer) {
  27917. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27918. }
  27919. // Geometry renderer
  27920. if (this._geometryBufferRenderer) {
  27921. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27922. }
  27923. // RenderPipeline
  27924. if (this._postProcessRenderPipelineManager) {
  27925. this._postProcessRenderPipelineManager.update();
  27926. }
  27927. // Multi-cameras?
  27928. if (this.activeCameras.length > 0) {
  27929. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27930. if (cameraIndex > 0) {
  27931. this._engine.clear(null, false, true, true);
  27932. }
  27933. this._processSubCameras(this.activeCameras[cameraIndex]);
  27934. }
  27935. }
  27936. else {
  27937. if (!this.activeCamera) {
  27938. throw new Error("No camera defined");
  27939. }
  27940. this._processSubCameras(this.activeCamera);
  27941. }
  27942. // Intersection checks
  27943. this._checkIntersections();
  27944. // Update the audio listener attached to the camera
  27945. if (BABYLON.AudioEngine) {
  27946. this._updateAudioParameters();
  27947. }
  27948. // After render
  27949. if (this.afterRender) {
  27950. this.afterRender();
  27951. }
  27952. this.onAfterRenderObservable.notifyObservers(this);
  27953. // Cleaning
  27954. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27955. var data = this._toBeDisposed.data[index];
  27956. if (data) {
  27957. data.dispose();
  27958. }
  27959. this._toBeDisposed[index] = null;
  27960. }
  27961. this._toBeDisposed.reset();
  27962. if (this.dumpNextRenderTargets) {
  27963. this.dumpNextRenderTargets = false;
  27964. }
  27965. this._activeBones.addCount(0, true);
  27966. this._activeIndices.addCount(0, true);
  27967. this._activeParticles.addCount(0, true);
  27968. };
  27969. Scene.prototype._updateAudioParameters = function () {
  27970. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27971. return;
  27972. }
  27973. var listeningCamera;
  27974. var audioEngine = BABYLON.Engine.audioEngine;
  27975. if (this.activeCameras.length > 0) {
  27976. listeningCamera = this.activeCameras[0];
  27977. }
  27978. else {
  27979. listeningCamera = this.activeCamera;
  27980. }
  27981. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27982. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27983. // for VR cameras
  27984. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27985. listeningCamera = listeningCamera.rigCameras[0];
  27986. }
  27987. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27988. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27989. cameraDirection.normalize();
  27990. // To avoid some errors on GearVR
  27991. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27992. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27993. }
  27994. var i;
  27995. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27996. var sound = this.mainSoundTrack.soundCollection[i];
  27997. if (sound.useCustomAttenuation) {
  27998. sound.updateDistanceFromListener();
  27999. }
  28000. }
  28001. for (i = 0; i < this.soundTracks.length; i++) {
  28002. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28003. sound = this.soundTracks[i].soundCollection[j];
  28004. if (sound.useCustomAttenuation) {
  28005. sound.updateDistanceFromListener();
  28006. }
  28007. }
  28008. }
  28009. }
  28010. };
  28011. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28012. // Audio
  28013. /**
  28014. * Gets or sets if audio support is enabled
  28015. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28016. */
  28017. get: function () {
  28018. return this._audioEnabled;
  28019. },
  28020. set: function (value) {
  28021. this._audioEnabled = value;
  28022. if (BABYLON.AudioEngine) {
  28023. if (this._audioEnabled) {
  28024. this._enableAudio();
  28025. }
  28026. else {
  28027. this._disableAudio();
  28028. }
  28029. }
  28030. },
  28031. enumerable: true,
  28032. configurable: true
  28033. });
  28034. Scene.prototype._disableAudio = function () {
  28035. var i;
  28036. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28037. this.mainSoundTrack.soundCollection[i].pause();
  28038. }
  28039. for (i = 0; i < this.soundTracks.length; i++) {
  28040. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28041. this.soundTracks[i].soundCollection[j].pause();
  28042. }
  28043. }
  28044. };
  28045. Scene.prototype._enableAudio = function () {
  28046. var i;
  28047. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28048. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28049. this.mainSoundTrack.soundCollection[i].play();
  28050. }
  28051. }
  28052. for (i = 0; i < this.soundTracks.length; i++) {
  28053. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28054. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28055. this.soundTracks[i].soundCollection[j].play();
  28056. }
  28057. }
  28058. }
  28059. };
  28060. Object.defineProperty(Scene.prototype, "headphone", {
  28061. /**
  28062. * Gets or sets if audio will be output to headphones
  28063. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28064. */
  28065. get: function () {
  28066. return this._headphone;
  28067. },
  28068. set: function (value) {
  28069. this._headphone = value;
  28070. if (BABYLON.AudioEngine) {
  28071. if (this._headphone) {
  28072. this._switchAudioModeForHeadphones();
  28073. }
  28074. else {
  28075. this._switchAudioModeForNormalSpeakers();
  28076. }
  28077. }
  28078. },
  28079. enumerable: true,
  28080. configurable: true
  28081. });
  28082. Scene.prototype._switchAudioModeForHeadphones = function () {
  28083. this.mainSoundTrack.switchPanningModelToHRTF();
  28084. for (var i = 0; i < this.soundTracks.length; i++) {
  28085. this.soundTracks[i].switchPanningModelToHRTF();
  28086. }
  28087. };
  28088. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28089. this.mainSoundTrack.switchPanningModelToEqualPower();
  28090. for (var i = 0; i < this.soundTracks.length; i++) {
  28091. this.soundTracks[i].switchPanningModelToEqualPower();
  28092. }
  28093. };
  28094. /**
  28095. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28096. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28097. * @returns the created depth renderer
  28098. */
  28099. Scene.prototype.enableDepthRenderer = function (camera) {
  28100. camera = camera || this.activeCamera;
  28101. if (!camera) {
  28102. throw "No camera available to enable depth renderer";
  28103. }
  28104. if (!this._depthRenderer[camera.id]) {
  28105. var textureType = 0;
  28106. if (this._engine.getCaps().textureHalfFloatRender) {
  28107. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28108. }
  28109. else if (this._engine.getCaps().textureFloatRender) {
  28110. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28111. }
  28112. else {
  28113. throw "Depth renderer does not support int texture type";
  28114. }
  28115. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28116. }
  28117. return this._depthRenderer[camera.id];
  28118. };
  28119. /**
  28120. * Disables a depth renderer for a given camera
  28121. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28122. */
  28123. Scene.prototype.disableDepthRenderer = function (camera) {
  28124. camera = camera || this.activeCamera;
  28125. if (!camera || !this._depthRenderer[camera.id]) {
  28126. return;
  28127. }
  28128. this._depthRenderer[camera.id].dispose();
  28129. delete this._depthRenderer[camera.id];
  28130. };
  28131. /**
  28132. * Enables a GeometryBufferRender and associates it with the scene
  28133. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28134. * @returns the GeometryBufferRenderer
  28135. */
  28136. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28137. if (ratio === void 0) { ratio = 1; }
  28138. if (this._geometryBufferRenderer) {
  28139. return this._geometryBufferRenderer;
  28140. }
  28141. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28142. if (!this._geometryBufferRenderer.isSupported) {
  28143. this._geometryBufferRenderer = null;
  28144. }
  28145. return this._geometryBufferRenderer;
  28146. };
  28147. /**
  28148. * Disables the GeometryBufferRender associated with the scene
  28149. */
  28150. Scene.prototype.disableGeometryBufferRenderer = function () {
  28151. if (!this._geometryBufferRenderer) {
  28152. return;
  28153. }
  28154. this._geometryBufferRenderer.dispose();
  28155. this._geometryBufferRenderer = null;
  28156. };
  28157. /**
  28158. * Freeze all materials
  28159. * A frozen material will not be updatable but should be faster to render
  28160. */
  28161. Scene.prototype.freezeMaterials = function () {
  28162. for (var i = 0; i < this.materials.length; i++) {
  28163. this.materials[i].freeze();
  28164. }
  28165. };
  28166. /**
  28167. * Unfreeze all materials
  28168. * A frozen material will not be updatable but should be faster to render
  28169. */
  28170. Scene.prototype.unfreezeMaterials = function () {
  28171. for (var i = 0; i < this.materials.length; i++) {
  28172. this.materials[i].unfreeze();
  28173. }
  28174. };
  28175. /**
  28176. * Releases all held ressources
  28177. */
  28178. Scene.prototype.dispose = function () {
  28179. this.beforeRender = null;
  28180. this.afterRender = null;
  28181. this.skeletons = [];
  28182. this.morphTargetManagers = [];
  28183. this.importedMeshesFiles = new Array();
  28184. this.stopAllAnimations();
  28185. this.resetCachedMaterial();
  28186. for (var key in this._depthRenderer) {
  28187. this._depthRenderer[key].dispose();
  28188. }
  28189. if (this._gamepadManager) {
  28190. this._gamepadManager.dispose();
  28191. this._gamepadManager = null;
  28192. }
  28193. // Smart arrays
  28194. if (this.activeCamera) {
  28195. this.activeCamera._activeMeshes.dispose();
  28196. this.activeCamera = null;
  28197. }
  28198. this._activeMeshes.dispose();
  28199. this._renderingManager.dispose();
  28200. this._processedMaterials.dispose();
  28201. this._activeParticleSystems.dispose();
  28202. this._activeSkeletons.dispose();
  28203. this._softwareSkinnedMeshes.dispose();
  28204. this._renderTargets.dispose();
  28205. this._registeredForLateAnimationBindings.dispose();
  28206. if (this._boundingBoxRenderer) {
  28207. this._boundingBoxRenderer.dispose();
  28208. }
  28209. this._meshesForIntersections.dispose();
  28210. this._toBeDisposed.dispose();
  28211. // Abort active requests
  28212. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28213. var request = _a[_i];
  28214. request.abort();
  28215. }
  28216. // Debug layer
  28217. if (this._debugLayer) {
  28218. this._debugLayer.hide();
  28219. }
  28220. // Events
  28221. this.onDisposeObservable.notifyObservers(this);
  28222. this.onDisposeObservable.clear();
  28223. this.onBeforeRenderObservable.clear();
  28224. this.onAfterRenderObservable.clear();
  28225. this.onBeforeRenderTargetsRenderObservable.clear();
  28226. this.onAfterRenderTargetsRenderObservable.clear();
  28227. this.onAfterStepObservable.clear();
  28228. this.onBeforeStepObservable.clear();
  28229. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28230. this.onAfterActiveMeshesEvaluationObservable.clear();
  28231. this.onBeforeParticlesRenderingObservable.clear();
  28232. this.onAfterParticlesRenderingObservable.clear();
  28233. this.onBeforeSpritesRenderingObservable.clear();
  28234. this.onAfterSpritesRenderingObservable.clear();
  28235. this.onBeforeDrawPhaseObservable.clear();
  28236. this.onAfterDrawPhaseObservable.clear();
  28237. this.onBeforePhysicsObservable.clear();
  28238. this.onAfterPhysicsObservable.clear();
  28239. this.onBeforeAnimationsObservable.clear();
  28240. this.onAfterAnimationsObservable.clear();
  28241. this.onDataLoadedObservable.clear();
  28242. this.detachControl();
  28243. // Release sounds & sounds tracks
  28244. if (BABYLON.AudioEngine) {
  28245. this.disposeSounds();
  28246. }
  28247. // VR Helper
  28248. if (this.VRHelper) {
  28249. this.VRHelper.dispose();
  28250. }
  28251. // Detach cameras
  28252. var canvas = this._engine.getRenderingCanvas();
  28253. if (canvas) {
  28254. var index;
  28255. for (index = 0; index < this.cameras.length; index++) {
  28256. this.cameras[index].detachControl(canvas);
  28257. }
  28258. }
  28259. // Release animation groups
  28260. while (this.animationGroups.length) {
  28261. this.animationGroups[0].dispose();
  28262. }
  28263. // Release lights
  28264. while (this.lights.length) {
  28265. this.lights[0].dispose();
  28266. }
  28267. // Release meshes
  28268. while (this.meshes.length) {
  28269. this.meshes[0].dispose(true);
  28270. }
  28271. while (this.transformNodes.length) {
  28272. this.removeTransformNode(this.transformNodes[0]);
  28273. }
  28274. // Release cameras
  28275. while (this.cameras.length) {
  28276. this.cameras[0].dispose();
  28277. }
  28278. // Release materials
  28279. if (this.defaultMaterial) {
  28280. this.defaultMaterial.dispose();
  28281. }
  28282. while (this.multiMaterials.length) {
  28283. this.multiMaterials[0].dispose();
  28284. }
  28285. while (this.materials.length) {
  28286. this.materials[0].dispose();
  28287. }
  28288. // Release particles
  28289. while (this.particleSystems.length) {
  28290. this.particleSystems[0].dispose();
  28291. }
  28292. // Release sprites
  28293. while (this.spriteManagers.length) {
  28294. this.spriteManagers[0].dispose();
  28295. }
  28296. // Release postProcesses
  28297. while (this.postProcesses.length) {
  28298. this.postProcesses[0].dispose();
  28299. }
  28300. // Release layers
  28301. while (this.layers.length) {
  28302. this.layers[0].dispose();
  28303. }
  28304. while (this.effectLayers.length) {
  28305. this.effectLayers[0].dispose();
  28306. }
  28307. // Release textures
  28308. while (this.textures.length) {
  28309. this.textures[0].dispose();
  28310. }
  28311. // Release UBO
  28312. this._sceneUbo.dispose();
  28313. if (this._alternateSceneUbo) {
  28314. this._alternateSceneUbo.dispose();
  28315. }
  28316. // Post-processes
  28317. this.postProcessManager.dispose();
  28318. if (this._postProcessRenderPipelineManager) {
  28319. this._postProcessRenderPipelineManager.dispose();
  28320. }
  28321. // Physics
  28322. if (this._physicsEngine) {
  28323. this.disablePhysicsEngine();
  28324. }
  28325. // Remove from engine
  28326. index = this._engine.scenes.indexOf(this);
  28327. if (index > -1) {
  28328. this._engine.scenes.splice(index, 1);
  28329. }
  28330. this._engine.wipeCaches(true);
  28331. this._isDisposed = true;
  28332. };
  28333. Object.defineProperty(Scene.prototype, "isDisposed", {
  28334. /**
  28335. * Gets if the scene is already disposed
  28336. */
  28337. get: function () {
  28338. return this._isDisposed;
  28339. },
  28340. enumerable: true,
  28341. configurable: true
  28342. });
  28343. /**
  28344. * Releases sounds & soundtracks
  28345. */
  28346. Scene.prototype.disposeSounds = function () {
  28347. if (!this._mainSoundTrack) {
  28348. return;
  28349. }
  28350. this.mainSoundTrack.dispose();
  28351. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28352. this.soundTracks[scIndex].dispose();
  28353. }
  28354. };
  28355. /**
  28356. * Call this function to reduce memory footprint of the scene.
  28357. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28358. */
  28359. Scene.prototype.clearCachedVertexData = function () {
  28360. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28361. var mesh = this.meshes[meshIndex];
  28362. var geometry = mesh.geometry;
  28363. if (geometry) {
  28364. geometry._indices = [];
  28365. for (var vbName in geometry._vertexBuffers) {
  28366. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28367. continue;
  28368. }
  28369. geometry._vertexBuffers[vbName]._buffer._data = null;
  28370. }
  28371. }
  28372. }
  28373. };
  28374. /**
  28375. * This function will remove the local cached buffer data from texture.
  28376. * It will save memory but will prevent the texture from being rebuilt
  28377. */
  28378. Scene.prototype.cleanCachedTextureBuffer = function () {
  28379. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28380. var baseTexture = _a[_i];
  28381. var buffer = baseTexture._buffer;
  28382. if (buffer) {
  28383. baseTexture._buffer = null;
  28384. }
  28385. }
  28386. };
  28387. // Octrees
  28388. /**
  28389. * Get the world extend vectors with an optional filter
  28390. *
  28391. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28392. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28393. */
  28394. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28395. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28396. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28397. filterPredicate = filterPredicate || (function () { return true; });
  28398. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28399. mesh.computeWorldMatrix(true);
  28400. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28401. return;
  28402. }
  28403. var boundingInfo = mesh.getBoundingInfo();
  28404. var minBox = boundingInfo.boundingBox.minimumWorld;
  28405. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28406. BABYLON.Tools.CheckExtends(minBox, min, max);
  28407. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28408. });
  28409. return {
  28410. min: min,
  28411. max: max
  28412. };
  28413. };
  28414. /**
  28415. * Creates or updates the octree used to boost selection (picking)
  28416. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28417. * @param maxCapacity defines the maximum capacity per leaf
  28418. * @param maxDepth defines the maximum depth of the octree
  28419. * @returns an octree of AbstractMesh
  28420. */
  28421. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28422. if (maxCapacity === void 0) { maxCapacity = 64; }
  28423. if (maxDepth === void 0) { maxDepth = 2; }
  28424. if (!this._selectionOctree) {
  28425. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28426. }
  28427. var worldExtends = this.getWorldExtends();
  28428. // Update octree
  28429. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28430. return this._selectionOctree;
  28431. };
  28432. // Picking
  28433. /**
  28434. * Creates a ray that can be used to pick in the scene
  28435. * @param x defines the x coordinate of the origin (on-screen)
  28436. * @param y defines the y coordinate of the origin (on-screen)
  28437. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28438. * @param camera defines the camera to use for the picking
  28439. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28440. * @returns a Ray
  28441. */
  28442. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28443. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28444. var result = BABYLON.Ray.Zero();
  28445. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28446. return result;
  28447. };
  28448. /**
  28449. * Creates a ray that can be used to pick in the scene
  28450. * @param x defines the x coordinate of the origin (on-screen)
  28451. * @param y defines the y coordinate of the origin (on-screen)
  28452. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28453. * @param result defines the ray where to store the picking ray
  28454. * @param camera defines the camera to use for the picking
  28455. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28456. * @returns the current scene
  28457. */
  28458. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28459. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28460. var engine = this._engine;
  28461. if (!camera) {
  28462. if (!this.activeCamera)
  28463. throw new Error("Active camera not set");
  28464. camera = this.activeCamera;
  28465. }
  28466. var cameraViewport = camera.viewport;
  28467. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28468. // Moving coordinates to local viewport world
  28469. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28470. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28471. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28472. return this;
  28473. };
  28474. /**
  28475. * Creates a ray that can be used to pick in the scene
  28476. * @param x defines the x coordinate of the origin (on-screen)
  28477. * @param y defines the y coordinate of the origin (on-screen)
  28478. * @param camera defines the camera to use for the picking
  28479. * @returns a Ray
  28480. */
  28481. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28482. var result = BABYLON.Ray.Zero();
  28483. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28484. return result;
  28485. };
  28486. /**
  28487. * Creates a ray that can be used to pick in the scene
  28488. * @param x defines the x coordinate of the origin (on-screen)
  28489. * @param y defines the y coordinate of the origin (on-screen)
  28490. * @param result defines the ray where to store the picking ray
  28491. * @param camera defines the camera to use for the picking
  28492. * @returns the current scene
  28493. */
  28494. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28495. if (!BABYLON.PickingInfo) {
  28496. return this;
  28497. }
  28498. var engine = this._engine;
  28499. if (!camera) {
  28500. if (!this.activeCamera)
  28501. throw new Error("Active camera not set");
  28502. camera = this.activeCamera;
  28503. }
  28504. var cameraViewport = camera.viewport;
  28505. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28506. var identity = BABYLON.Matrix.Identity();
  28507. // Moving coordinates to local viewport world
  28508. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28509. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28510. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28511. return this;
  28512. };
  28513. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28514. if (!BABYLON.PickingInfo) {
  28515. return null;
  28516. }
  28517. var pickingInfo = null;
  28518. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28519. var mesh = this.meshes[meshIndex];
  28520. if (predicate) {
  28521. if (!predicate(mesh)) {
  28522. continue;
  28523. }
  28524. }
  28525. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28526. continue;
  28527. }
  28528. var world = mesh.getWorldMatrix();
  28529. var ray = rayFunction(world);
  28530. var result = mesh.intersects(ray, fastCheck);
  28531. if (!result || !result.hit)
  28532. continue;
  28533. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28534. continue;
  28535. pickingInfo = result;
  28536. if (fastCheck) {
  28537. break;
  28538. }
  28539. }
  28540. return pickingInfo || new BABYLON.PickingInfo();
  28541. };
  28542. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28543. if (!BABYLON.PickingInfo) {
  28544. return null;
  28545. }
  28546. var pickingInfos = new Array();
  28547. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28548. var mesh = this.meshes[meshIndex];
  28549. if (predicate) {
  28550. if (!predicate(mesh)) {
  28551. continue;
  28552. }
  28553. }
  28554. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28555. continue;
  28556. }
  28557. var world = mesh.getWorldMatrix();
  28558. var ray = rayFunction(world);
  28559. var result = mesh.intersects(ray, false);
  28560. if (!result || !result.hit)
  28561. continue;
  28562. pickingInfos.push(result);
  28563. }
  28564. return pickingInfos;
  28565. };
  28566. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28567. if (!BABYLON.PickingInfo) {
  28568. return null;
  28569. }
  28570. var pickingInfo = null;
  28571. if (!camera) {
  28572. if (!this.activeCamera) {
  28573. return null;
  28574. }
  28575. camera = this.activeCamera;
  28576. }
  28577. if (this.spriteManagers.length > 0) {
  28578. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28579. var spriteManager = this.spriteManagers[spriteIndex];
  28580. if (!spriteManager.isPickable) {
  28581. continue;
  28582. }
  28583. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28584. if (!result || !result.hit)
  28585. continue;
  28586. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28587. continue;
  28588. pickingInfo = result;
  28589. if (fastCheck) {
  28590. break;
  28591. }
  28592. }
  28593. }
  28594. return pickingInfo || new BABYLON.PickingInfo();
  28595. };
  28596. /** Launch a ray to try to pick a mesh in the scene
  28597. * @param x position on screen
  28598. * @param y position on screen
  28599. * @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
  28600. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28601. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28602. * @returns a PickingInfo
  28603. */
  28604. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28605. var _this = this;
  28606. if (!BABYLON.PickingInfo) {
  28607. return null;
  28608. }
  28609. var result = this._internalPick(function (world) {
  28610. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28611. return _this._tempPickingRay;
  28612. }, predicate, fastCheck);
  28613. if (result) {
  28614. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28615. }
  28616. return result;
  28617. };
  28618. /** Launch a ray to try to pick a sprite in the scene
  28619. * @param x position on screen
  28620. * @param y position on screen
  28621. * @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
  28622. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28623. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28624. * @returns a PickingInfo
  28625. */
  28626. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28627. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28628. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28629. };
  28630. /** Use the given ray to pick a mesh in the scene
  28631. * @param ray The ray to use to pick meshes
  28632. * @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
  28633. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28634. * @returns a PickingInfo
  28635. */
  28636. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28637. var _this = this;
  28638. var result = this._internalPick(function (world) {
  28639. if (!_this._pickWithRayInverseMatrix) {
  28640. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28641. }
  28642. world.invertToRef(_this._pickWithRayInverseMatrix);
  28643. if (!_this._cachedRayForTransform) {
  28644. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28645. }
  28646. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28647. return _this._cachedRayForTransform;
  28648. }, predicate, fastCheck);
  28649. if (result) {
  28650. result.ray = ray;
  28651. }
  28652. return result;
  28653. };
  28654. /**
  28655. * Launch a ray to try to pick a mesh in the scene
  28656. * @param x X position on screen
  28657. * @param y Y position on screen
  28658. * @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
  28659. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28660. * @returns an array of PickingInfo
  28661. */
  28662. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28663. var _this = this;
  28664. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28665. };
  28666. /**
  28667. * Launch a ray to try to pick a mesh in the scene
  28668. * @param ray Ray to use
  28669. * @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
  28670. * @returns an array of PickingInfo
  28671. */
  28672. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28673. var _this = this;
  28674. return this._internalMultiPick(function (world) {
  28675. if (!_this._pickWithRayInverseMatrix) {
  28676. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28677. }
  28678. world.invertToRef(_this._pickWithRayInverseMatrix);
  28679. if (!_this._cachedRayForTransform) {
  28680. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28681. }
  28682. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28683. return _this._cachedRayForTransform;
  28684. }, predicate);
  28685. };
  28686. /**
  28687. * Force the value of meshUnderPointer
  28688. * @param mesh defines the mesh to use
  28689. */
  28690. Scene.prototype.setPointerOverMesh = function (mesh) {
  28691. if (this._pointerOverMesh === mesh) {
  28692. return;
  28693. }
  28694. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28695. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28696. }
  28697. this._pointerOverMesh = mesh;
  28698. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28699. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28700. }
  28701. };
  28702. /**
  28703. * Gets the mesh under the pointer
  28704. * @returns a Mesh or null if no mesh is under the pointer
  28705. */
  28706. Scene.prototype.getPointerOverMesh = function () {
  28707. return this._pointerOverMesh;
  28708. };
  28709. /**
  28710. * Force the sprite under the pointer
  28711. * @param sprite defines the sprite to use
  28712. */
  28713. Scene.prototype.setPointerOverSprite = function (sprite) {
  28714. if (this._pointerOverSprite === sprite) {
  28715. return;
  28716. }
  28717. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28718. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28719. }
  28720. this._pointerOverSprite = sprite;
  28721. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28722. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28723. }
  28724. };
  28725. /**
  28726. * Gets the sprite under the pointer
  28727. * @returns a Sprite or null if no sprite is under the pointer
  28728. */
  28729. Scene.prototype.getPointerOverSprite = function () {
  28730. return this._pointerOverSprite;
  28731. };
  28732. // Physics
  28733. /**
  28734. * Gets the current physics engine
  28735. * @returns a PhysicsEngine or null if none attached
  28736. */
  28737. Scene.prototype.getPhysicsEngine = function () {
  28738. return this._physicsEngine;
  28739. };
  28740. /**
  28741. * Enables physics to the current scene
  28742. * @param gravity defines the scene's gravity for the physics engine
  28743. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28744. * @return a boolean indicating if the physics engine was initialized
  28745. */
  28746. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28747. if (gravity === void 0) { gravity = null; }
  28748. if (this._physicsEngine) {
  28749. return true;
  28750. }
  28751. try {
  28752. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28753. return true;
  28754. }
  28755. catch (e) {
  28756. BABYLON.Tools.Error(e.message);
  28757. return false;
  28758. }
  28759. };
  28760. /**
  28761. * Disables and disposes the physics engine associated with the scene
  28762. */
  28763. Scene.prototype.disablePhysicsEngine = function () {
  28764. if (!this._physicsEngine) {
  28765. return;
  28766. }
  28767. this._physicsEngine.dispose();
  28768. this._physicsEngine = null;
  28769. };
  28770. /**
  28771. * Gets a boolean indicating if there is an active physics engine
  28772. * @returns a boolean indicating if there is an active physics engine
  28773. */
  28774. Scene.prototype.isPhysicsEnabled = function () {
  28775. return this._physicsEngine !== undefined;
  28776. };
  28777. /**
  28778. * Deletes a physics compound impostor
  28779. * @param compound defines the compound to delete
  28780. */
  28781. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28782. var mesh = compound.parts[0].mesh;
  28783. if (mesh.physicsImpostor) {
  28784. mesh.physicsImpostor.dispose( /*true*/);
  28785. mesh.physicsImpostor = null;
  28786. }
  28787. };
  28788. // Misc.
  28789. /** @hidden */
  28790. Scene.prototype._rebuildGeometries = function () {
  28791. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28792. var geometry = _a[_i];
  28793. geometry._rebuild();
  28794. }
  28795. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28796. var mesh = _c[_b];
  28797. mesh._rebuild();
  28798. }
  28799. if (this.postProcessManager) {
  28800. this.postProcessManager._rebuild();
  28801. }
  28802. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28803. var layer = _e[_d];
  28804. layer._rebuild();
  28805. }
  28806. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28807. var effectLayer = _g[_f];
  28808. effectLayer._rebuild();
  28809. }
  28810. if (this._boundingBoxRenderer) {
  28811. this._boundingBoxRenderer._rebuild();
  28812. }
  28813. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28814. var system = _j[_h];
  28815. system.rebuild();
  28816. }
  28817. if (this._postProcessRenderPipelineManager) {
  28818. this._postProcessRenderPipelineManager._rebuild();
  28819. }
  28820. };
  28821. /** @hidden */
  28822. Scene.prototype._rebuildTextures = function () {
  28823. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28824. var texture = _a[_i];
  28825. texture._rebuild();
  28826. }
  28827. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28828. };
  28829. /**
  28830. * Creates a default light for the scene.
  28831. * @param replace Whether to replace the existing lights in the scene.
  28832. */
  28833. Scene.prototype.createDefaultLight = function (replace) {
  28834. if (replace === void 0) { replace = false; }
  28835. // Dispose existing light in replace mode.
  28836. if (replace) {
  28837. if (this.lights) {
  28838. for (var i = 0; i < this.lights.length; i++) {
  28839. this.lights[i].dispose();
  28840. }
  28841. }
  28842. }
  28843. // Light
  28844. if (this.lights.length === 0) {
  28845. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28846. }
  28847. };
  28848. /**
  28849. * Creates a default camera for the scene.
  28850. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28851. * @param replace Whether to replace the existing active camera in the scene.
  28852. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28853. */
  28854. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28855. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28856. if (replace === void 0) { replace = false; }
  28857. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28858. // Dispose existing camera in replace mode.
  28859. if (replace) {
  28860. if (this.activeCamera) {
  28861. this.activeCamera.dispose();
  28862. this.activeCamera = null;
  28863. }
  28864. }
  28865. // Camera
  28866. if (!this.activeCamera) {
  28867. var worldExtends = this.getWorldExtends();
  28868. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28869. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28870. var camera;
  28871. var radius = worldSize.length() * 1.5;
  28872. // empty scene scenario!
  28873. if (!isFinite(radius)) {
  28874. radius = 1;
  28875. worldCenter.copyFromFloats(0, 0, 0);
  28876. }
  28877. if (createArcRotateCamera) {
  28878. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28879. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28880. arcRotateCamera.wheelPrecision = 100 / radius;
  28881. camera = arcRotateCamera;
  28882. }
  28883. else {
  28884. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28885. freeCamera.setTarget(worldCenter);
  28886. camera = freeCamera;
  28887. }
  28888. camera.minZ = radius * 0.01;
  28889. camera.maxZ = radius * 1000;
  28890. camera.speed = radius * 0.2;
  28891. this.activeCamera = camera;
  28892. var canvas = this.getEngine().getRenderingCanvas();
  28893. if (attachCameraControls && canvas) {
  28894. camera.attachControl(canvas);
  28895. }
  28896. }
  28897. };
  28898. /**
  28899. * Creates a default camera and a default light
  28900. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28901. * @param replace defines if the camera and/or light will replace the existing ones
  28902. * @param attachCameraControls defines if attachControl will be called on the new camera
  28903. */
  28904. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28905. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28906. if (replace === void 0) { replace = false; }
  28907. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28908. this.createDefaultLight(replace);
  28909. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28910. };
  28911. /**
  28912. * Creates a new sky box
  28913. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28914. * @param environmentTexture defines the texture to use as environment texture
  28915. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28916. * @param scale defines the overall scale of the skybox
  28917. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28918. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28919. * @returns a new mesh holding the sky box
  28920. */
  28921. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28922. if (pbr === void 0) { pbr = false; }
  28923. if (scale === void 0) { scale = 1000; }
  28924. if (blur === void 0) { blur = 0; }
  28925. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28926. if (!environmentTexture) {
  28927. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28928. return null;
  28929. }
  28930. if (setGlobalEnvTexture) {
  28931. if (environmentTexture) {
  28932. this.environmentTexture = environmentTexture;
  28933. }
  28934. }
  28935. // Skybox
  28936. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28937. if (pbr) {
  28938. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28939. hdrSkyboxMaterial.backFaceCulling = false;
  28940. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28941. if (hdrSkyboxMaterial.reflectionTexture) {
  28942. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28943. }
  28944. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28945. hdrSkyboxMaterial.disableLighting = true;
  28946. hdrSkyboxMaterial.twoSidedLighting = true;
  28947. hdrSkybox.infiniteDistance = true;
  28948. hdrSkybox.material = hdrSkyboxMaterial;
  28949. }
  28950. else {
  28951. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28952. skyboxMaterial.backFaceCulling = false;
  28953. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28954. if (skyboxMaterial.reflectionTexture) {
  28955. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28956. }
  28957. skyboxMaterial.disableLighting = true;
  28958. hdrSkybox.infiniteDistance = true;
  28959. hdrSkybox.material = skyboxMaterial;
  28960. }
  28961. return hdrSkybox;
  28962. };
  28963. /**
  28964. * Creates a new environment
  28965. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28966. * @param options defines the options you can use to configure the environment
  28967. * @returns the new EnvironmentHelper
  28968. */
  28969. Scene.prototype.createDefaultEnvironment = function (options) {
  28970. if (BABYLON.EnvironmentHelper) {
  28971. return new BABYLON.EnvironmentHelper(options, this);
  28972. }
  28973. return null;
  28974. };
  28975. /**
  28976. * Creates a new VREXperienceHelper
  28977. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28978. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28979. * @returns a new VREXperienceHelper
  28980. */
  28981. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28982. if (webVROptions === void 0) { webVROptions = {}; }
  28983. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28984. };
  28985. // Tags
  28986. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28987. if (tagsQuery === undefined) {
  28988. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28989. return list;
  28990. }
  28991. var listByTags = [];
  28992. forEach = forEach || (function (item) { return; });
  28993. for (var i in list) {
  28994. var item = list[i];
  28995. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28996. listByTags.push(item);
  28997. forEach(item);
  28998. }
  28999. }
  29000. return listByTags;
  29001. };
  29002. /**
  29003. * Get a list of meshes by tags
  29004. * @param tagsQuery defines the tags query to use
  29005. * @param forEach defines a predicate used to filter results
  29006. * @returns an array of Mesh
  29007. */
  29008. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29009. return this._getByTags(this.meshes, tagsQuery, forEach);
  29010. };
  29011. /**
  29012. * Get a list of cameras by tags
  29013. * @param tagsQuery defines the tags query to use
  29014. * @param forEach defines a predicate used to filter results
  29015. * @returns an array of Camera
  29016. */
  29017. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29018. return this._getByTags(this.cameras, tagsQuery, forEach);
  29019. };
  29020. /**
  29021. * Get a list of lights by tags
  29022. * @param tagsQuery defines the tags query to use
  29023. * @param forEach defines a predicate used to filter results
  29024. * @returns an array of Light
  29025. */
  29026. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29027. return this._getByTags(this.lights, tagsQuery, forEach);
  29028. };
  29029. /**
  29030. * Get a list of materials by tags
  29031. * @param tagsQuery defines the tags query to use
  29032. * @param forEach defines a predicate used to filter results
  29033. * @returns an array of Material
  29034. */
  29035. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29036. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29037. };
  29038. /**
  29039. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29040. * This allowed control for front to back rendering or reversly depending of the special needs.
  29041. *
  29042. * @param renderingGroupId The rendering group id corresponding to its index
  29043. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29044. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29045. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29046. */
  29047. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29048. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29049. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29050. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29051. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29052. };
  29053. /**
  29054. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29055. *
  29056. * @param renderingGroupId The rendering group id corresponding to its index
  29057. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29058. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29059. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29060. */
  29061. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29062. if (depth === void 0) { depth = true; }
  29063. if (stencil === void 0) { stencil = true; }
  29064. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29065. };
  29066. /**
  29067. * Will flag all materials as dirty to trigger new shader compilation
  29068. * @param flag defines the flag used to specify which material part must be marked as dirty
  29069. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29070. */
  29071. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29072. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29073. var material = _a[_i];
  29074. if (predicate && !predicate(material)) {
  29075. continue;
  29076. }
  29077. material.markAsDirty(flag);
  29078. }
  29079. };
  29080. /** @hidden */
  29081. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29082. var _this = this;
  29083. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29084. this._activeRequests.push(request);
  29085. request.onCompleteObservable.add(function (request) {
  29086. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29087. });
  29088. return request;
  29089. };
  29090. /** @hidden */
  29091. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29092. var _this = this;
  29093. return new Promise(function (resolve, reject) {
  29094. _this._loadFile(url, function (data) {
  29095. resolve(data);
  29096. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29097. reject(exception);
  29098. });
  29099. });
  29100. };
  29101. // Statics
  29102. Scene._FOGMODE_NONE = 0;
  29103. Scene._FOGMODE_EXP = 1;
  29104. Scene._FOGMODE_EXP2 = 2;
  29105. Scene._FOGMODE_LINEAR = 3;
  29106. Scene._uniqueIdCounter = 0;
  29107. /**
  29108. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29109. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29110. */
  29111. Scene.MinDeltaTime = 1.0;
  29112. /**
  29113. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29114. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29115. */
  29116. Scene.MaxDeltaTime = 1000.0;
  29117. /** The distance in pixel that you have to move to prevent some events */
  29118. Scene.DragMovementThreshold = 10; // in pixels
  29119. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29120. Scene.LongPressDelay = 500; // in milliseconds
  29121. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29122. Scene.DoubleClickDelay = 300; // in milliseconds
  29123. /** If you need to check double click without raising a single click at first click, enable this flag */
  29124. Scene.ExclusiveDoubleClickMode = false;
  29125. return Scene;
  29126. }());
  29127. BABYLON.Scene = Scene;
  29128. })(BABYLON || (BABYLON = {}));
  29129. //# sourceMappingURL=babylon.scene.js.map
  29130. var BABYLON;
  29131. (function (BABYLON) {
  29132. /**
  29133. * Set of assets to keep when moving a scene into an asset container.
  29134. */
  29135. var KeepAssets = /** @class */ (function () {
  29136. function KeepAssets() {
  29137. /**
  29138. * Cameras to keep.
  29139. */
  29140. this.cameras = new Array();
  29141. /**
  29142. * Lights to keep.
  29143. */
  29144. this.lights = new Array();
  29145. /**
  29146. * Meshes to keep.
  29147. */
  29148. this.meshes = new Array();
  29149. /**
  29150. * Skeletons to keep.
  29151. */
  29152. this.skeletons = new Array();
  29153. /**
  29154. * ParticleSystems to keep.
  29155. */
  29156. this.particleSystems = new Array();
  29157. /**
  29158. * Animations to keep.
  29159. */
  29160. this.animations = new Array();
  29161. /**
  29162. * AnimationGroups to keep.
  29163. */
  29164. this.animationGroups = new Array();
  29165. /**
  29166. * MultiMaterials to keep.
  29167. */
  29168. this.multiMaterials = new Array();
  29169. /**
  29170. * Materials to keep.
  29171. */
  29172. this.materials = new Array();
  29173. /**
  29174. * MorphTargetManagers to keep.
  29175. */
  29176. this.morphTargetManagers = new Array();
  29177. /**
  29178. * Geometries to keep.
  29179. */
  29180. this.geometries = new Array();
  29181. /**
  29182. * TransformNodes to keep.
  29183. */
  29184. this.transformNodes = new Array();
  29185. /**
  29186. * LensFlareSystems to keep.
  29187. */
  29188. this.lensFlareSystems = new Array();
  29189. /**
  29190. * ShadowGenerators to keep.
  29191. */
  29192. this.shadowGenerators = new Array();
  29193. /**
  29194. * ActionManagers to keep.
  29195. */
  29196. this.actionManagers = new Array();
  29197. /**
  29198. * Sounds to keep.
  29199. */
  29200. this.sounds = new Array();
  29201. /**
  29202. * Textures to keep.
  29203. */
  29204. this.textures = new Array();
  29205. /**
  29206. * Effect layers to keep.
  29207. */
  29208. this.effectLayers = new Array();
  29209. }
  29210. return KeepAssets;
  29211. }());
  29212. BABYLON.KeepAssets = KeepAssets;
  29213. /**
  29214. * Container with a set of assets that can be added or removed from a scene.
  29215. */
  29216. var AssetContainer = /** @class */ (function () {
  29217. /**
  29218. * Instantiates an AssetContainer.
  29219. * @param scene The scene the AssetContainer belongs to.
  29220. */
  29221. function AssetContainer(scene) {
  29222. // Objects
  29223. /**
  29224. * Cameras populated in the container.
  29225. */
  29226. this.cameras = new Array();
  29227. /**
  29228. * Lights populated in the container.
  29229. */
  29230. this.lights = new Array();
  29231. /**
  29232. * Meshes populated in the container.
  29233. */
  29234. this.meshes = new Array();
  29235. /**
  29236. * Skeletons populated in the container.
  29237. */
  29238. this.skeletons = new Array();
  29239. /**
  29240. * ParticleSystems populated in the container.
  29241. */
  29242. this.particleSystems = new Array();
  29243. /**
  29244. * Animations populated in the container.
  29245. */
  29246. this.animations = new Array();
  29247. /**
  29248. * AnimationGroups populated in the container.
  29249. */
  29250. this.animationGroups = new Array();
  29251. /**
  29252. * MultiMaterials populated in the container.
  29253. */
  29254. this.multiMaterials = new Array();
  29255. /**
  29256. * Materials populated in the container.
  29257. */
  29258. this.materials = new Array();
  29259. /**
  29260. * MorphTargetManagers populated in the container.
  29261. */
  29262. this.morphTargetManagers = new Array();
  29263. /**
  29264. * Geometries populated in the container.
  29265. */
  29266. this.geometries = new Array();
  29267. /**
  29268. * TransformNodes populated in the container.
  29269. */
  29270. this.transformNodes = new Array();
  29271. /**
  29272. * LensFlareSystems populated in the container.
  29273. */
  29274. this.lensFlareSystems = new Array();
  29275. /**
  29276. * ShadowGenerators populated in the container.
  29277. */
  29278. this.shadowGenerators = new Array();
  29279. /**
  29280. * ActionManagers populated in the container.
  29281. */
  29282. this.actionManagers = new Array();
  29283. /**
  29284. * Sounds populated in the container.
  29285. */
  29286. this.sounds = new Array();
  29287. /**
  29288. * Textures populated in the container.
  29289. */
  29290. this.textures = new Array();
  29291. /**
  29292. * Effect layers populated in the container.
  29293. */
  29294. this.effectLayers = new Array();
  29295. this.scene = scene;
  29296. }
  29297. /**
  29298. * Adds all the assets from the container to the scene.
  29299. */
  29300. AssetContainer.prototype.addAllToScene = function () {
  29301. var _this = this;
  29302. this.cameras.forEach(function (o) {
  29303. _this.scene.addCamera(o);
  29304. });
  29305. this.lights.forEach(function (o) {
  29306. _this.scene.addLight(o);
  29307. });
  29308. this.meshes.forEach(function (o) {
  29309. _this.scene.addMesh(o);
  29310. });
  29311. this.skeletons.forEach(function (o) {
  29312. _this.scene.addSkeleton(o);
  29313. });
  29314. this.particleSystems.forEach(function (o) {
  29315. _this.scene.addParticleSystem(o);
  29316. });
  29317. this.animations.forEach(function (o) {
  29318. _this.scene.addAnimation(o);
  29319. });
  29320. this.animationGroups.forEach(function (o) {
  29321. _this.scene.addAnimationGroup(o);
  29322. });
  29323. this.multiMaterials.forEach(function (o) {
  29324. _this.scene.addMultiMaterial(o);
  29325. });
  29326. this.materials.forEach(function (o) {
  29327. _this.scene.addMaterial(o);
  29328. });
  29329. this.morphTargetManagers.forEach(function (o) {
  29330. _this.scene.addMorphTargetManager(o);
  29331. });
  29332. this.geometries.forEach(function (o) {
  29333. _this.scene.addGeometry(o);
  29334. });
  29335. this.transformNodes.forEach(function (o) {
  29336. _this.scene.addTransformNode(o);
  29337. });
  29338. this.lensFlareSystems.forEach(function (o) {
  29339. _this.scene.addLensFlareSystem(o);
  29340. });
  29341. this.actionManagers.forEach(function (o) {
  29342. _this.scene.addActionManager(o);
  29343. });
  29344. this.sounds.forEach(function (o) {
  29345. o.play();
  29346. o.autoplay = true;
  29347. _this.scene.mainSoundTrack.AddSound(o);
  29348. });
  29349. this.textures.forEach(function (o) {
  29350. _this.scene.addTexture(o);
  29351. });
  29352. this.effectLayers.forEach(function (o) {
  29353. _this.scene.addEffectLayer(o);
  29354. });
  29355. };
  29356. /**
  29357. * Removes all the assets in the container from the scene
  29358. */
  29359. AssetContainer.prototype.removeAllFromScene = function () {
  29360. var _this = this;
  29361. this.cameras.forEach(function (o) {
  29362. _this.scene.removeCamera(o);
  29363. });
  29364. this.lights.forEach(function (o) {
  29365. _this.scene.removeLight(o);
  29366. });
  29367. this.meshes.forEach(function (o) {
  29368. _this.scene.removeMesh(o);
  29369. });
  29370. this.skeletons.forEach(function (o) {
  29371. _this.scene.removeSkeleton(o);
  29372. });
  29373. this.particleSystems.forEach(function (o) {
  29374. _this.scene.removeParticleSystem(o);
  29375. });
  29376. this.animations.forEach(function (o) {
  29377. _this.scene.removeAnimation(o);
  29378. });
  29379. this.animationGroups.forEach(function (o) {
  29380. _this.scene.removeAnimationGroup(o);
  29381. });
  29382. this.multiMaterials.forEach(function (o) {
  29383. _this.scene.removeMultiMaterial(o);
  29384. });
  29385. this.materials.forEach(function (o) {
  29386. _this.scene.removeMaterial(o);
  29387. });
  29388. this.morphTargetManagers.forEach(function (o) {
  29389. _this.scene.removeMorphTargetManager(o);
  29390. });
  29391. this.geometries.forEach(function (o) {
  29392. _this.scene.removeGeometry(o);
  29393. });
  29394. this.transformNodes.forEach(function (o) {
  29395. _this.scene.removeTransformNode(o);
  29396. });
  29397. this.lensFlareSystems.forEach(function (o) {
  29398. _this.scene.removeLensFlareSystem(o);
  29399. });
  29400. this.actionManagers.forEach(function (o) {
  29401. _this.scene.removeActionManager(o);
  29402. });
  29403. this.sounds.forEach(function (o) {
  29404. o.stop();
  29405. o.autoplay = false;
  29406. _this.scene.mainSoundTrack.RemoveSound(o);
  29407. });
  29408. this.textures.forEach(function (o) {
  29409. _this.scene.removeTexture(o);
  29410. });
  29411. this.effectLayers.forEach(function (o) {
  29412. _this.scene.removeEffectLayer(o);
  29413. });
  29414. };
  29415. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29416. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29417. var asset = sourceAssets_1[_i];
  29418. var move = true;
  29419. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29420. var keepAsset = keepAssets_1[_a];
  29421. if (asset === keepAsset) {
  29422. move = false;
  29423. break;
  29424. }
  29425. }
  29426. if (move) {
  29427. targetAssets.push(asset);
  29428. }
  29429. }
  29430. };
  29431. /**
  29432. * Removes all the assets contained in the scene and adds them to the container.
  29433. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29434. */
  29435. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29436. if (keepAssets === undefined) {
  29437. keepAssets = new KeepAssets();
  29438. }
  29439. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29440. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29441. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29442. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29443. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29444. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29445. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29446. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29447. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29448. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29449. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29450. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29451. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29452. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29453. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29454. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29455. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29456. this.removeAllFromScene();
  29457. };
  29458. /**
  29459. * 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.
  29460. * @returns the root mesh
  29461. */
  29462. AssetContainer.prototype.createRootMesh = function () {
  29463. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29464. this.meshes.forEach(function (m) {
  29465. if (!m.parent) {
  29466. rootMesh.addChild(m);
  29467. }
  29468. });
  29469. this.meshes.unshift(rootMesh);
  29470. return rootMesh;
  29471. };
  29472. return AssetContainer;
  29473. }());
  29474. BABYLON.AssetContainer = AssetContainer;
  29475. })(BABYLON || (BABYLON = {}));
  29476. //# sourceMappingURL=babylon.assetContainer.js.map
  29477. var BABYLON;
  29478. (function (BABYLON) {
  29479. var Buffer = /** @class */ (function () {
  29480. /**
  29481. * Constructor
  29482. * @param engine the engine
  29483. * @param data the data to use for this buffer
  29484. * @param updatable whether the data is updatable
  29485. * @param stride the stride (optional)
  29486. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29487. * @param instanced whether the buffer is instanced (optional)
  29488. * @param useBytes set to true if the stride in in bytes (optional)
  29489. */
  29490. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29491. if (stride === void 0) { stride = 0; }
  29492. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29493. if (instanced === void 0) { instanced = false; }
  29494. if (useBytes === void 0) { useBytes = false; }
  29495. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29496. this._engine = engine.getScene().getEngine();
  29497. }
  29498. else {
  29499. this._engine = engine;
  29500. }
  29501. this._updatable = updatable;
  29502. this._instanced = instanced;
  29503. this._data = data;
  29504. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29505. if (!postponeInternalCreation) { // by default
  29506. this.create();
  29507. }
  29508. }
  29509. /**
  29510. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29511. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29512. * @param offset defines offset in the buffer (0 by default)
  29513. * @param size defines the size in floats of attributes (position is 3 for instance)
  29514. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29515. * @param instanced defines if the vertex buffer contains indexed data
  29516. * @param useBytes defines if the offset and stride are in bytes
  29517. * @returns the new vertex buffer
  29518. */
  29519. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29520. if (useBytes === void 0) { useBytes = false; }
  29521. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29522. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29523. // a lot of these parameters are ignored as they are overriden by the buffer
  29524. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29525. };
  29526. // Properties
  29527. Buffer.prototype.isUpdatable = function () {
  29528. return this._updatable;
  29529. };
  29530. Buffer.prototype.getData = function () {
  29531. return this._data;
  29532. };
  29533. Buffer.prototype.getBuffer = function () {
  29534. return this._buffer;
  29535. };
  29536. /**
  29537. * Gets the stride in float32 units (i.e. byte stride / 4).
  29538. * May not be an integer if the byte stride is not divisible by 4.
  29539. * DEPRECATED. Use byteStride instead.
  29540. * @returns the stride in float32 units
  29541. */
  29542. Buffer.prototype.getStrideSize = function () {
  29543. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29544. };
  29545. // Methods
  29546. Buffer.prototype.create = function (data) {
  29547. if (data === void 0) { data = null; }
  29548. if (!data && this._buffer) {
  29549. return; // nothing to do
  29550. }
  29551. data = data || this._data;
  29552. if (!data) {
  29553. return;
  29554. }
  29555. if (!this._buffer) { // create buffer
  29556. if (this._updatable) {
  29557. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29558. this._data = data;
  29559. }
  29560. else {
  29561. this._buffer = this._engine.createVertexBuffer(data);
  29562. }
  29563. }
  29564. else if (this._updatable) { // update buffer
  29565. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29566. this._data = data;
  29567. }
  29568. };
  29569. Buffer.prototype._rebuild = function () {
  29570. this._buffer = null;
  29571. this.create(this._data);
  29572. };
  29573. Buffer.prototype.update = function (data) {
  29574. this.create(data);
  29575. };
  29576. /**
  29577. * Updates the data directly.
  29578. * @param data the new data
  29579. * @param offset the new offset
  29580. * @param vertexCount the vertex count (optional)
  29581. * @param useBytes set to true if the offset is in bytes
  29582. */
  29583. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29584. if (useBytes === void 0) { useBytes = false; }
  29585. if (!this._buffer) {
  29586. return;
  29587. }
  29588. if (this._updatable) { // update buffer
  29589. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29590. this._data = null;
  29591. }
  29592. };
  29593. Buffer.prototype.dispose = function () {
  29594. if (!this._buffer) {
  29595. return;
  29596. }
  29597. if (this._engine._releaseBuffer(this._buffer)) {
  29598. this._buffer = null;
  29599. }
  29600. };
  29601. return Buffer;
  29602. }());
  29603. BABYLON.Buffer = Buffer;
  29604. })(BABYLON || (BABYLON = {}));
  29605. //# sourceMappingURL=babylon.buffer.js.map
  29606. var BABYLON;
  29607. (function (BABYLON) {
  29608. var VertexBuffer = /** @class */ (function () {
  29609. /**
  29610. * Constructor
  29611. * @param engine the engine
  29612. * @param data the data to use for this vertex buffer
  29613. * @param kind the vertex buffer kind
  29614. * @param updatable whether the data is updatable
  29615. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29616. * @param stride the stride (optional)
  29617. * @param instanced whether the buffer is instanced (optional)
  29618. * @param offset the offset of the data (optional)
  29619. * @param size the number of components (optional)
  29620. * @param type the type of the component (optional)
  29621. * @param normalized whether the data contains normalized data (optional)
  29622. * @param useBytes set to true if stride and offset are in bytes (optional)
  29623. */
  29624. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29625. if (normalized === void 0) { normalized = false; }
  29626. if (useBytes === void 0) { useBytes = false; }
  29627. if (data instanceof BABYLON.Buffer) {
  29628. this._buffer = data;
  29629. this._ownsBuffer = false;
  29630. }
  29631. else {
  29632. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29633. this._ownsBuffer = true;
  29634. }
  29635. this._kind = kind;
  29636. if (type == undefined) {
  29637. var data_1 = this.getData();
  29638. this.type = VertexBuffer.FLOAT;
  29639. if (data_1 instanceof Int8Array)
  29640. this.type = VertexBuffer.BYTE;
  29641. else if (data_1 instanceof Uint8Array)
  29642. this.type = VertexBuffer.UNSIGNED_BYTE;
  29643. else if (data_1 instanceof Int16Array)
  29644. this.type = VertexBuffer.SHORT;
  29645. else if (data_1 instanceof Uint16Array)
  29646. this.type = VertexBuffer.UNSIGNED_SHORT;
  29647. else if (data_1 instanceof Int32Array)
  29648. this.type = VertexBuffer.INT;
  29649. else if (data_1 instanceof Uint32Array)
  29650. this.type = VertexBuffer.UNSIGNED_INT;
  29651. }
  29652. else {
  29653. this.type = type;
  29654. }
  29655. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29656. if (useBytes) {
  29657. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29658. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29659. this.byteOffset = offset || 0;
  29660. }
  29661. else {
  29662. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29663. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29664. this.byteOffset = (offset || 0) * typeByteLength;
  29665. }
  29666. this.normalized = normalized;
  29667. this._instanced = instanced !== undefined ? instanced : false;
  29668. this._instanceDivisor = instanced ? 1 : 0;
  29669. }
  29670. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29671. /**
  29672. * Gets or sets the instance divisor when in instanced mode
  29673. */
  29674. get: function () {
  29675. return this._instanceDivisor;
  29676. },
  29677. set: function (value) {
  29678. this._instanceDivisor = value;
  29679. if (value == 0) {
  29680. this._instanced = false;
  29681. }
  29682. else {
  29683. this._instanced = true;
  29684. }
  29685. },
  29686. enumerable: true,
  29687. configurable: true
  29688. });
  29689. VertexBuffer.prototype._rebuild = function () {
  29690. if (!this._buffer) {
  29691. return;
  29692. }
  29693. this._buffer._rebuild();
  29694. };
  29695. /**
  29696. * Returns the kind of the VertexBuffer (string).
  29697. */
  29698. VertexBuffer.prototype.getKind = function () {
  29699. return this._kind;
  29700. };
  29701. // Properties
  29702. /**
  29703. * Boolean : is the VertexBuffer updatable ?
  29704. */
  29705. VertexBuffer.prototype.isUpdatable = function () {
  29706. return this._buffer.isUpdatable();
  29707. };
  29708. /**
  29709. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29710. */
  29711. VertexBuffer.prototype.getData = function () {
  29712. return this._buffer.getData();
  29713. };
  29714. /**
  29715. * Returns the WebGLBuffer associated to the VertexBuffer.
  29716. */
  29717. VertexBuffer.prototype.getBuffer = function () {
  29718. return this._buffer.getBuffer();
  29719. };
  29720. /**
  29721. * Returns the stride as a multiple of the type byte length.
  29722. * DEPRECATED. Use byteStride instead.
  29723. */
  29724. VertexBuffer.prototype.getStrideSize = function () {
  29725. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29726. };
  29727. /**
  29728. * Returns the offset as a multiple of the type byte length.
  29729. * DEPRECATED. Use byteOffset instead.
  29730. */
  29731. VertexBuffer.prototype.getOffset = function () {
  29732. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29733. };
  29734. /**
  29735. * Returns the number of components per vertex attribute (integer).
  29736. */
  29737. VertexBuffer.prototype.getSize = function () {
  29738. return this._size;
  29739. };
  29740. /**
  29741. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29742. */
  29743. VertexBuffer.prototype.getIsInstanced = function () {
  29744. return this._instanced;
  29745. };
  29746. /**
  29747. * Returns the instancing divisor, zero for non-instanced (integer).
  29748. */
  29749. VertexBuffer.prototype.getInstanceDivisor = function () {
  29750. return this._instanceDivisor;
  29751. };
  29752. // Methods
  29753. /**
  29754. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29755. * Returns the created WebGLBuffer.
  29756. */
  29757. VertexBuffer.prototype.create = function (data) {
  29758. return this._buffer.create(data);
  29759. };
  29760. /**
  29761. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29762. * This function will create a new buffer if the current one is not updatable
  29763. * Returns the updated WebGLBuffer.
  29764. */
  29765. VertexBuffer.prototype.update = function (data) {
  29766. return this._buffer.update(data);
  29767. };
  29768. /**
  29769. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29770. * Returns the directly updated WebGLBuffer.
  29771. * @param data the new data
  29772. * @param offset the new offset
  29773. * @param useBytes set to true if the offset is in bytes
  29774. */
  29775. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29776. if (useBytes === void 0) { useBytes = false; }
  29777. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29778. };
  29779. /**
  29780. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29781. */
  29782. VertexBuffer.prototype.dispose = function () {
  29783. if (this._ownsBuffer) {
  29784. this._buffer.dispose();
  29785. }
  29786. };
  29787. /**
  29788. * Enumerates each value of this vertex buffer as numbers.
  29789. * @param count the number of values to enumerate
  29790. * @param callback the callback function called for each value
  29791. */
  29792. VertexBuffer.prototype.forEach = function (count, callback) {
  29793. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29794. };
  29795. Object.defineProperty(VertexBuffer, "PositionKind", {
  29796. get: function () {
  29797. return VertexBuffer._PositionKind;
  29798. },
  29799. enumerable: true,
  29800. configurable: true
  29801. });
  29802. Object.defineProperty(VertexBuffer, "NormalKind", {
  29803. get: function () {
  29804. return VertexBuffer._NormalKind;
  29805. },
  29806. enumerable: true,
  29807. configurable: true
  29808. });
  29809. Object.defineProperty(VertexBuffer, "TangentKind", {
  29810. get: function () {
  29811. return VertexBuffer._TangentKind;
  29812. },
  29813. enumerable: true,
  29814. configurable: true
  29815. });
  29816. Object.defineProperty(VertexBuffer, "UVKind", {
  29817. get: function () {
  29818. return VertexBuffer._UVKind;
  29819. },
  29820. enumerable: true,
  29821. configurable: true
  29822. });
  29823. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29824. get: function () {
  29825. return VertexBuffer._UV2Kind;
  29826. },
  29827. enumerable: true,
  29828. configurable: true
  29829. });
  29830. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29831. get: function () {
  29832. return VertexBuffer._UV3Kind;
  29833. },
  29834. enumerable: true,
  29835. configurable: true
  29836. });
  29837. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29838. get: function () {
  29839. return VertexBuffer._UV4Kind;
  29840. },
  29841. enumerable: true,
  29842. configurable: true
  29843. });
  29844. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29845. get: function () {
  29846. return VertexBuffer._UV5Kind;
  29847. },
  29848. enumerable: true,
  29849. configurable: true
  29850. });
  29851. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29852. get: function () {
  29853. return VertexBuffer._UV6Kind;
  29854. },
  29855. enumerable: true,
  29856. configurable: true
  29857. });
  29858. Object.defineProperty(VertexBuffer, "ColorKind", {
  29859. get: function () {
  29860. return VertexBuffer._ColorKind;
  29861. },
  29862. enumerable: true,
  29863. configurable: true
  29864. });
  29865. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29866. get: function () {
  29867. return VertexBuffer._MatricesIndicesKind;
  29868. },
  29869. enumerable: true,
  29870. configurable: true
  29871. });
  29872. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29873. get: function () {
  29874. return VertexBuffer._MatricesWeightsKind;
  29875. },
  29876. enumerable: true,
  29877. configurable: true
  29878. });
  29879. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29880. get: function () {
  29881. return VertexBuffer._MatricesIndicesExtraKind;
  29882. },
  29883. enumerable: true,
  29884. configurable: true
  29885. });
  29886. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29887. get: function () {
  29888. return VertexBuffer._MatricesWeightsExtraKind;
  29889. },
  29890. enumerable: true,
  29891. configurable: true
  29892. });
  29893. /**
  29894. * Deduces the stride given a kind.
  29895. * @param kind The kind string to deduce
  29896. * @returns The deduced stride
  29897. */
  29898. VertexBuffer.DeduceStride = function (kind) {
  29899. switch (kind) {
  29900. case VertexBuffer.UVKind:
  29901. case VertexBuffer.UV2Kind:
  29902. case VertexBuffer.UV3Kind:
  29903. case VertexBuffer.UV4Kind:
  29904. case VertexBuffer.UV5Kind:
  29905. case VertexBuffer.UV6Kind:
  29906. return 2;
  29907. case VertexBuffer.NormalKind:
  29908. case VertexBuffer.PositionKind:
  29909. return 3;
  29910. case VertexBuffer.ColorKind:
  29911. case VertexBuffer.MatricesIndicesKind:
  29912. case VertexBuffer.MatricesIndicesExtraKind:
  29913. case VertexBuffer.MatricesWeightsKind:
  29914. case VertexBuffer.MatricesWeightsExtraKind:
  29915. case VertexBuffer.TangentKind:
  29916. return 4;
  29917. default:
  29918. throw new Error("Invalid kind '" + kind + "'");
  29919. }
  29920. };
  29921. /**
  29922. * Gets the byte length of the given type.
  29923. * @param type the type
  29924. * @returns the number of bytes
  29925. */
  29926. VertexBuffer.GetTypeByteLength = function (type) {
  29927. switch (type) {
  29928. case VertexBuffer.BYTE:
  29929. case VertexBuffer.UNSIGNED_BYTE:
  29930. return 1;
  29931. case VertexBuffer.SHORT:
  29932. case VertexBuffer.UNSIGNED_SHORT:
  29933. return 2;
  29934. case VertexBuffer.INT:
  29935. case VertexBuffer.FLOAT:
  29936. return 4;
  29937. default:
  29938. throw new Error("Invalid type '" + type + "'");
  29939. }
  29940. };
  29941. /**
  29942. * Enumerates each value of the given parameters as numbers.
  29943. * @param data the data to enumerate
  29944. * @param byteOffset the byte offset of the data
  29945. * @param byteStride the byte stride of the data
  29946. * @param componentCount the number of components per element
  29947. * @param componentType the type of the component
  29948. * @param count the total number of components
  29949. * @param normalized whether the data is normalized
  29950. * @param callback the callback function called for each value
  29951. */
  29952. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29953. if (data instanceof Array) {
  29954. var offset = byteOffset / 4;
  29955. var stride = byteStride / 4;
  29956. for (var index = 0; index < count; index += componentCount) {
  29957. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29958. callback(data[offset + componentIndex], index + componentIndex);
  29959. }
  29960. offset += stride;
  29961. }
  29962. }
  29963. else {
  29964. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29965. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29966. for (var index = 0; index < count; index += componentCount) {
  29967. var componentByteOffset = byteOffset;
  29968. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29969. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29970. callback(value, index + componentIndex);
  29971. componentByteOffset += componentByteLength;
  29972. }
  29973. byteOffset += byteStride;
  29974. }
  29975. }
  29976. };
  29977. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29978. switch (type) {
  29979. case VertexBuffer.BYTE: {
  29980. var value = dataView.getInt8(byteOffset);
  29981. if (normalized) {
  29982. value = Math.max(value / 127, -1);
  29983. }
  29984. return value;
  29985. }
  29986. case VertexBuffer.UNSIGNED_BYTE: {
  29987. var value = dataView.getUint8(byteOffset);
  29988. if (normalized) {
  29989. value = value / 255;
  29990. }
  29991. return value;
  29992. }
  29993. case VertexBuffer.SHORT: {
  29994. var value = dataView.getInt16(byteOffset, true);
  29995. if (normalized) {
  29996. value = Math.max(value / 16383, -1);
  29997. }
  29998. return value;
  29999. }
  30000. case VertexBuffer.UNSIGNED_SHORT: {
  30001. var value = dataView.getUint16(byteOffset, true);
  30002. if (normalized) {
  30003. value = value / 65535;
  30004. }
  30005. return value;
  30006. }
  30007. case VertexBuffer.FLOAT: {
  30008. return dataView.getFloat32(byteOffset, true);
  30009. }
  30010. default: {
  30011. throw new Error("Invalid component type " + type);
  30012. }
  30013. }
  30014. };
  30015. /**
  30016. * The byte type.
  30017. */
  30018. VertexBuffer.BYTE = 5120;
  30019. /**
  30020. * The unsigned byte type.
  30021. */
  30022. VertexBuffer.UNSIGNED_BYTE = 5121;
  30023. /**
  30024. * The short type.
  30025. */
  30026. VertexBuffer.SHORT = 5122;
  30027. /**
  30028. * The unsigned short type.
  30029. */
  30030. VertexBuffer.UNSIGNED_SHORT = 5123;
  30031. /**
  30032. * The integer type.
  30033. */
  30034. VertexBuffer.INT = 5124;
  30035. /**
  30036. * The unsigned integer type.
  30037. */
  30038. VertexBuffer.UNSIGNED_INT = 5125;
  30039. /**
  30040. * The float type.
  30041. */
  30042. VertexBuffer.FLOAT = 5126;
  30043. // Enums
  30044. VertexBuffer._PositionKind = "position";
  30045. VertexBuffer._NormalKind = "normal";
  30046. VertexBuffer._TangentKind = "tangent";
  30047. VertexBuffer._UVKind = "uv";
  30048. VertexBuffer._UV2Kind = "uv2";
  30049. VertexBuffer._UV3Kind = "uv3";
  30050. VertexBuffer._UV4Kind = "uv4";
  30051. VertexBuffer._UV5Kind = "uv5";
  30052. VertexBuffer._UV6Kind = "uv6";
  30053. VertexBuffer._ColorKind = "color";
  30054. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30055. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30056. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30057. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30058. return VertexBuffer;
  30059. }());
  30060. BABYLON.VertexBuffer = VertexBuffer;
  30061. })(BABYLON || (BABYLON = {}));
  30062. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30063. var BABYLON;
  30064. (function (BABYLON) {
  30065. /**
  30066. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30067. */
  30068. var DummyInternalTextureTracker = /** @class */ (function () {
  30069. function DummyInternalTextureTracker() {
  30070. /**
  30071. * Gets or set the previous tracker in the list
  30072. */
  30073. this.previous = null;
  30074. /**
  30075. * Gets or set the next tracker in the list
  30076. */
  30077. this.next = null;
  30078. }
  30079. return DummyInternalTextureTracker;
  30080. }());
  30081. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30082. })(BABYLON || (BABYLON = {}));
  30083. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30084. var BABYLON;
  30085. (function (BABYLON) {
  30086. /**
  30087. * Class used to store data associated with WebGL texture data for the engine
  30088. * This class should not be used directly
  30089. */
  30090. var InternalTexture = /** @class */ (function () {
  30091. /**
  30092. * Creates a new InternalTexture
  30093. * @param engine defines the engine to use
  30094. * @param dataSource defines the type of data that will be used
  30095. */
  30096. function InternalTexture(engine, dataSource) {
  30097. /**
  30098. * Observable called when the texture is loaded
  30099. */
  30100. this.onLoadedObservable = new BABYLON.Observable();
  30101. /**
  30102. * Gets or set the previous tracker in the list
  30103. */
  30104. this.previous = null;
  30105. /**
  30106. * Gets or set the next tracker in the list
  30107. */
  30108. this.next = null;
  30109. // Private
  30110. /** @hidden */
  30111. this._initialSlot = -1;
  30112. /** @hidden */
  30113. this._designatedSlot = -1;
  30114. /** @hidden */
  30115. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30116. /** @hidden */
  30117. this._comparisonFunction = 0;
  30118. /** @hidden */
  30119. this._references = 1;
  30120. this._engine = engine;
  30121. this._dataSource = dataSource;
  30122. this._webGLTexture = engine._createTexture();
  30123. }
  30124. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30125. /**
  30126. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30127. */
  30128. get: function () {
  30129. return this._dataSource;
  30130. },
  30131. enumerable: true,
  30132. configurable: true
  30133. });
  30134. /**
  30135. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30136. */
  30137. InternalTexture.prototype.incrementReferences = function () {
  30138. this._references++;
  30139. };
  30140. /**
  30141. * Change the size of the texture (not the size of the content)
  30142. * @param width defines the new width
  30143. * @param height defines the new height
  30144. * @param depth defines the new depth (1 by default)
  30145. */
  30146. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30147. if (depth === void 0) { depth = 1; }
  30148. this.width = width;
  30149. this.height = height;
  30150. this.depth = depth;
  30151. this.baseWidth = width;
  30152. this.baseHeight = height;
  30153. this.baseDepth = depth;
  30154. this._size = width * height * depth;
  30155. };
  30156. /** @hidden */
  30157. InternalTexture.prototype._rebuild = function () {
  30158. var _this = this;
  30159. var proxy;
  30160. this.isReady = false;
  30161. this._cachedCoordinatesMode = null;
  30162. this._cachedWrapU = null;
  30163. this._cachedWrapV = null;
  30164. this._cachedAnisotropicFilteringLevel = null;
  30165. switch (this._dataSource) {
  30166. case InternalTexture.DATASOURCE_TEMP:
  30167. return;
  30168. case InternalTexture.DATASOURCE_URL:
  30169. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30170. _this.isReady = true;
  30171. }, null, this._buffer, undefined, this.format);
  30172. proxy._swapAndDie(this);
  30173. return;
  30174. case InternalTexture.DATASOURCE_RAW:
  30175. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30176. proxy._swapAndDie(this);
  30177. this.isReady = true;
  30178. return;
  30179. case InternalTexture.DATASOURCE_RAW3D:
  30180. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30181. proxy._swapAndDie(this);
  30182. this.isReady = true;
  30183. return;
  30184. case InternalTexture.DATASOURCE_DYNAMIC:
  30185. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30186. proxy._swapAndDie(this);
  30187. // The engine will make sure to update content so no need to flag it as isReady = true
  30188. return;
  30189. case InternalTexture.DATASOURCE_RENDERTARGET:
  30190. var options = new BABYLON.RenderTargetCreationOptions();
  30191. options.generateDepthBuffer = this._generateDepthBuffer;
  30192. options.generateMipMaps = this.generateMipMaps;
  30193. options.generateStencilBuffer = this._generateStencilBuffer;
  30194. options.samplingMode = this.samplingMode;
  30195. options.type = this.type;
  30196. if (this.isCube) {
  30197. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30198. }
  30199. else {
  30200. var size = {
  30201. width: this.width,
  30202. height: this.height
  30203. };
  30204. proxy = this._engine.createRenderTargetTexture(size, options);
  30205. }
  30206. proxy._swapAndDie(this);
  30207. this.isReady = true;
  30208. return;
  30209. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30210. var depthTextureOptions = {
  30211. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30212. comparisonFunction: this._comparisonFunction,
  30213. generateStencil: this._generateStencilBuffer,
  30214. isCube: this.isCube
  30215. };
  30216. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30217. proxy._swapAndDie(this);
  30218. this.isReady = true;
  30219. return;
  30220. case InternalTexture.DATASOURCE_CUBE:
  30221. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30222. _this.isReady = true;
  30223. }, null, this.format, this._extension);
  30224. proxy._swapAndDie(this);
  30225. return;
  30226. case InternalTexture.DATASOURCE_CUBERAW:
  30227. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30228. proxy._swapAndDie(this);
  30229. this.isReady = true;
  30230. return;
  30231. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30232. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30233. if (proxy) {
  30234. proxy._swapAndDie(_this);
  30235. }
  30236. _this.isReady = true;
  30237. }, null, this.format, this._extension);
  30238. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30239. return;
  30240. }
  30241. };
  30242. InternalTexture.prototype._swapAndDie = function (target) {
  30243. target._webGLTexture = this._webGLTexture;
  30244. if (this._framebuffer) {
  30245. target._framebuffer = this._framebuffer;
  30246. }
  30247. if (this._depthStencilBuffer) {
  30248. target._depthStencilBuffer = this._depthStencilBuffer;
  30249. }
  30250. if (this._lodTextureHigh) {
  30251. if (target._lodTextureHigh) {
  30252. target._lodTextureHigh.dispose();
  30253. }
  30254. target._lodTextureHigh = this._lodTextureHigh;
  30255. }
  30256. if (this._lodTextureMid) {
  30257. if (target._lodTextureMid) {
  30258. target._lodTextureMid.dispose();
  30259. }
  30260. target._lodTextureMid = this._lodTextureMid;
  30261. }
  30262. if (this._lodTextureLow) {
  30263. if (target._lodTextureLow) {
  30264. target._lodTextureLow.dispose();
  30265. }
  30266. target._lodTextureLow = this._lodTextureLow;
  30267. }
  30268. var cache = this._engine.getLoadedTexturesCache();
  30269. var index = cache.indexOf(this);
  30270. if (index !== -1) {
  30271. cache.splice(index, 1);
  30272. }
  30273. };
  30274. /**
  30275. * Dispose the current allocated resources
  30276. */
  30277. InternalTexture.prototype.dispose = function () {
  30278. if (!this._webGLTexture) {
  30279. return;
  30280. }
  30281. this._references--;
  30282. if (this._references === 0) {
  30283. this._engine._releaseTexture(this);
  30284. this._webGLTexture = null;
  30285. this.previous = null;
  30286. this.next = null;
  30287. }
  30288. };
  30289. /**
  30290. * The source of the texture data is unknown
  30291. */
  30292. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30293. /**
  30294. * Texture data comes from an URL
  30295. */
  30296. InternalTexture.DATASOURCE_URL = 1;
  30297. /**
  30298. * Texture data is only used for temporary storage
  30299. */
  30300. InternalTexture.DATASOURCE_TEMP = 2;
  30301. /**
  30302. * Texture data comes from raw data (ArrayBuffer)
  30303. */
  30304. InternalTexture.DATASOURCE_RAW = 3;
  30305. /**
  30306. * Texture content is dynamic (video or dynamic texture)
  30307. */
  30308. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30309. /**
  30310. * Texture content is generated by rendering to it
  30311. */
  30312. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30313. /**
  30314. * Texture content is part of a multi render target process
  30315. */
  30316. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30317. /**
  30318. * Texture data comes from a cube data file
  30319. */
  30320. InternalTexture.DATASOURCE_CUBE = 7;
  30321. /**
  30322. * Texture data comes from a raw cube data
  30323. */
  30324. InternalTexture.DATASOURCE_CUBERAW = 8;
  30325. /**
  30326. * Texture data come from a prefiltered cube data file
  30327. */
  30328. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30329. /**
  30330. * Texture content is raw 3D data
  30331. */
  30332. InternalTexture.DATASOURCE_RAW3D = 10;
  30333. /**
  30334. * Texture content is a depth texture
  30335. */
  30336. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30337. return InternalTexture;
  30338. }());
  30339. BABYLON.InternalTexture = InternalTexture;
  30340. })(BABYLON || (BABYLON = {}));
  30341. //# sourceMappingURL=babylon.internalTexture.js.map
  30342. var BABYLON;
  30343. (function (BABYLON) {
  30344. var BaseTexture = /** @class */ (function () {
  30345. function BaseTexture(scene) {
  30346. this._hasAlpha = false;
  30347. this.getAlphaFromRGB = false;
  30348. this.level = 1;
  30349. this.coordinatesIndex = 0;
  30350. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30351. /**
  30352. * | Value | Type | Description |
  30353. * | ----- | ------------------ | ----------- |
  30354. * | 0 | CLAMP_ADDRESSMODE | |
  30355. * | 1 | WRAP_ADDRESSMODE | |
  30356. * | 2 | MIRROR_ADDRESSMODE | |
  30357. */
  30358. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30359. /**
  30360. * | Value | Type | Description |
  30361. * | ----- | ------------------ | ----------- |
  30362. * | 0 | CLAMP_ADDRESSMODE | |
  30363. * | 1 | WRAP_ADDRESSMODE | |
  30364. * | 2 | MIRROR_ADDRESSMODE | |
  30365. */
  30366. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30367. /**
  30368. * | Value | Type | Description |
  30369. * | ----- | ------------------ | ----------- |
  30370. * | 0 | CLAMP_ADDRESSMODE | |
  30371. * | 1 | WRAP_ADDRESSMODE | |
  30372. * | 2 | MIRROR_ADDRESSMODE | |
  30373. */
  30374. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30375. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30376. this.isCube = false;
  30377. this.is3D = false;
  30378. this.gammaSpace = true;
  30379. this.invertZ = false;
  30380. this.lodLevelInAlpha = false;
  30381. this.lodGenerationOffset = 0.0;
  30382. this.lodGenerationScale = 0.8;
  30383. this.isRenderTarget = false;
  30384. this.animations = new Array();
  30385. /**
  30386. * An event triggered when the texture is disposed.
  30387. */
  30388. this.onDisposeObservable = new BABYLON.Observable();
  30389. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30390. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30391. if (this._scene) {
  30392. this._scene.textures.push(this);
  30393. }
  30394. this._uid = null;
  30395. }
  30396. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30397. get: function () {
  30398. return this._hasAlpha;
  30399. },
  30400. set: function (value) {
  30401. if (this._hasAlpha === value) {
  30402. return;
  30403. }
  30404. this._hasAlpha = value;
  30405. if (this._scene) {
  30406. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30407. }
  30408. },
  30409. enumerable: true,
  30410. configurable: true
  30411. });
  30412. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30413. get: function () {
  30414. return this._coordinatesMode;
  30415. },
  30416. /**
  30417. * How a texture is mapped.
  30418. *
  30419. * | Value | Type | Description |
  30420. * | ----- | ----------------------------------- | ----------- |
  30421. * | 0 | EXPLICIT_MODE | |
  30422. * | 1 | SPHERICAL_MODE | |
  30423. * | 2 | PLANAR_MODE | |
  30424. * | 3 | CUBIC_MODE | |
  30425. * | 4 | PROJECTION_MODE | |
  30426. * | 5 | SKYBOX_MODE | |
  30427. * | 6 | INVCUBIC_MODE | |
  30428. * | 7 | EQUIRECTANGULAR_MODE | |
  30429. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30430. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30431. */
  30432. set: function (value) {
  30433. if (this._coordinatesMode === value) {
  30434. return;
  30435. }
  30436. this._coordinatesMode = value;
  30437. if (this._scene) {
  30438. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30439. }
  30440. },
  30441. enumerable: true,
  30442. configurable: true
  30443. });
  30444. Object.defineProperty(BaseTexture.prototype, "uid", {
  30445. get: function () {
  30446. if (!this._uid) {
  30447. this._uid = BABYLON.Tools.RandomId();
  30448. }
  30449. return this._uid;
  30450. },
  30451. enumerable: true,
  30452. configurable: true
  30453. });
  30454. BaseTexture.prototype.toString = function () {
  30455. return this.name;
  30456. };
  30457. BaseTexture.prototype.getClassName = function () {
  30458. return "BaseTexture";
  30459. };
  30460. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30461. set: function (callback) {
  30462. if (this._onDisposeObserver) {
  30463. this.onDisposeObservable.remove(this._onDisposeObserver);
  30464. }
  30465. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30466. },
  30467. enumerable: true,
  30468. configurable: true
  30469. });
  30470. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30471. get: function () {
  30472. return true;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. BaseTexture.prototype.getScene = function () {
  30478. return this._scene;
  30479. };
  30480. BaseTexture.prototype.getTextureMatrix = function () {
  30481. return BABYLON.Matrix.IdentityReadOnly;
  30482. };
  30483. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30484. return BABYLON.Matrix.IdentityReadOnly;
  30485. };
  30486. BaseTexture.prototype.getInternalTexture = function () {
  30487. return this._texture;
  30488. };
  30489. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30490. return !this.isBlocking || this.isReady();
  30491. };
  30492. BaseTexture.prototype.isReady = function () {
  30493. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30494. this.delayLoad();
  30495. return false;
  30496. }
  30497. if (this._texture) {
  30498. return this._texture.isReady;
  30499. }
  30500. return false;
  30501. };
  30502. BaseTexture.prototype.getSize = function () {
  30503. if (this._texture && this._texture.width) {
  30504. return new BABYLON.Size(this._texture.width, this._texture.height);
  30505. }
  30506. if (this._texture && this._texture._size) {
  30507. return new BABYLON.Size(this._texture._size, this._texture._size);
  30508. }
  30509. return BABYLON.Size.Zero();
  30510. };
  30511. BaseTexture.prototype.getBaseSize = function () {
  30512. if (!this.isReady() || !this._texture)
  30513. return BABYLON.Size.Zero();
  30514. if (this._texture._size) {
  30515. return new BABYLON.Size(this._texture._size, this._texture._size);
  30516. }
  30517. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30518. };
  30519. BaseTexture.prototype.scale = function (ratio) {
  30520. };
  30521. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30522. get: function () {
  30523. return false;
  30524. },
  30525. enumerable: true,
  30526. configurable: true
  30527. });
  30528. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30529. if (!this._scene) {
  30530. return null;
  30531. }
  30532. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30533. for (var index = 0; index < texturesCache.length; index++) {
  30534. var texturesCacheEntry = texturesCache[index];
  30535. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30536. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30537. texturesCacheEntry.incrementReferences();
  30538. return texturesCacheEntry;
  30539. }
  30540. }
  30541. }
  30542. return null;
  30543. };
  30544. BaseTexture.prototype._rebuild = function () {
  30545. };
  30546. BaseTexture.prototype.delayLoad = function () {
  30547. };
  30548. BaseTexture.prototype.clone = function () {
  30549. return null;
  30550. };
  30551. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30552. get: function () {
  30553. if (!this._texture) {
  30554. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30555. }
  30556. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30557. },
  30558. enumerable: true,
  30559. configurable: true
  30560. });
  30561. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30562. get: function () {
  30563. if (!this._texture) {
  30564. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30565. }
  30566. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30567. },
  30568. enumerable: true,
  30569. configurable: true
  30570. });
  30571. BaseTexture.prototype.readPixels = function (faceIndex) {
  30572. if (faceIndex === void 0) { faceIndex = 0; }
  30573. if (!this._texture) {
  30574. return null;
  30575. }
  30576. var size = this.getSize();
  30577. var scene = this.getScene();
  30578. if (!scene) {
  30579. return null;
  30580. }
  30581. var engine = scene.getEngine();
  30582. if (this._texture.isCube) {
  30583. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30584. }
  30585. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30586. };
  30587. BaseTexture.prototype.releaseInternalTexture = function () {
  30588. if (this._texture) {
  30589. this._texture.dispose();
  30590. this._texture = null;
  30591. }
  30592. };
  30593. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30594. get: function () {
  30595. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30596. return null;
  30597. }
  30598. if (!this._texture._sphericalPolynomial) {
  30599. this._texture._sphericalPolynomial =
  30600. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30601. }
  30602. return this._texture._sphericalPolynomial;
  30603. },
  30604. set: function (value) {
  30605. if (this._texture) {
  30606. this._texture._sphericalPolynomial = value;
  30607. }
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30613. get: function () {
  30614. if (this._texture) {
  30615. return this._texture._lodTextureHigh;
  30616. }
  30617. return null;
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30623. get: function () {
  30624. if (this._texture) {
  30625. return this._texture._lodTextureMid;
  30626. }
  30627. return null;
  30628. },
  30629. enumerable: true,
  30630. configurable: true
  30631. });
  30632. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30633. get: function () {
  30634. if (this._texture) {
  30635. return this._texture._lodTextureLow;
  30636. }
  30637. return null;
  30638. },
  30639. enumerable: true,
  30640. configurable: true
  30641. });
  30642. BaseTexture.prototype.dispose = function () {
  30643. if (!this._scene) {
  30644. return;
  30645. }
  30646. // Animations
  30647. this._scene.stopAnimation(this);
  30648. // Remove from scene
  30649. this._scene._removePendingData(this);
  30650. var index = this._scene.textures.indexOf(this);
  30651. if (index >= 0) {
  30652. this._scene.textures.splice(index, 1);
  30653. }
  30654. if (this._texture === undefined) {
  30655. return;
  30656. }
  30657. // Release
  30658. this.releaseInternalTexture();
  30659. // Callback
  30660. this.onDisposeObservable.notifyObservers(this);
  30661. this.onDisposeObservable.clear();
  30662. };
  30663. BaseTexture.prototype.serialize = function () {
  30664. if (!this.name) {
  30665. return null;
  30666. }
  30667. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30668. // Animations
  30669. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30670. return serializationObject;
  30671. };
  30672. BaseTexture.WhenAllReady = function (textures, callback) {
  30673. var numRemaining = textures.length;
  30674. if (numRemaining === 0) {
  30675. callback();
  30676. return;
  30677. }
  30678. var _loop_1 = function () {
  30679. texture = textures[i];
  30680. if (texture.isReady()) {
  30681. if (--numRemaining === 0) {
  30682. callback();
  30683. }
  30684. }
  30685. else {
  30686. onLoadObservable = texture.onLoadObservable;
  30687. var onLoadCallback_1 = function () {
  30688. onLoadObservable.removeCallback(onLoadCallback_1);
  30689. if (--numRemaining === 0) {
  30690. callback();
  30691. }
  30692. };
  30693. onLoadObservable.add(onLoadCallback_1);
  30694. }
  30695. };
  30696. var texture, onLoadObservable;
  30697. for (var i = 0; i < textures.length; i++) {
  30698. _loop_1();
  30699. }
  30700. };
  30701. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30702. __decorate([
  30703. BABYLON.serialize()
  30704. ], BaseTexture.prototype, "name", void 0);
  30705. __decorate([
  30706. BABYLON.serialize("hasAlpha")
  30707. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30708. __decorate([
  30709. BABYLON.serialize()
  30710. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30711. __decorate([
  30712. BABYLON.serialize()
  30713. ], BaseTexture.prototype, "level", void 0);
  30714. __decorate([
  30715. BABYLON.serialize()
  30716. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30717. __decorate([
  30718. BABYLON.serialize("coordinatesMode")
  30719. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30720. __decorate([
  30721. BABYLON.serialize()
  30722. ], BaseTexture.prototype, "wrapU", void 0);
  30723. __decorate([
  30724. BABYLON.serialize()
  30725. ], BaseTexture.prototype, "wrapV", void 0);
  30726. __decorate([
  30727. BABYLON.serialize()
  30728. ], BaseTexture.prototype, "wrapR", void 0);
  30729. __decorate([
  30730. BABYLON.serialize()
  30731. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30732. __decorate([
  30733. BABYLON.serialize()
  30734. ], BaseTexture.prototype, "isCube", void 0);
  30735. __decorate([
  30736. BABYLON.serialize()
  30737. ], BaseTexture.prototype, "is3D", void 0);
  30738. __decorate([
  30739. BABYLON.serialize()
  30740. ], BaseTexture.prototype, "gammaSpace", void 0);
  30741. __decorate([
  30742. BABYLON.serialize()
  30743. ], BaseTexture.prototype, "invertZ", void 0);
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30753. __decorate([
  30754. BABYLON.serialize()
  30755. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30756. return BaseTexture;
  30757. }());
  30758. BABYLON.BaseTexture = BaseTexture;
  30759. })(BABYLON || (BABYLON = {}));
  30760. //# sourceMappingURL=babylon.baseTexture.js.map
  30761. var BABYLON;
  30762. (function (BABYLON) {
  30763. var Texture = /** @class */ (function (_super) {
  30764. __extends(Texture, _super);
  30765. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30766. if (noMipmap === void 0) { noMipmap = false; }
  30767. if (invertY === void 0) { invertY = true; }
  30768. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30769. if (onLoad === void 0) { onLoad = null; }
  30770. if (onError === void 0) { onError = null; }
  30771. if (buffer === void 0) { buffer = null; }
  30772. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30773. var _this = _super.call(this, scene) || this;
  30774. _this.uOffset = 0;
  30775. _this.vOffset = 0;
  30776. _this.uScale = 1.0;
  30777. _this.vScale = 1.0;
  30778. _this.uAng = 0;
  30779. _this.vAng = 0;
  30780. _this.wAng = 0;
  30781. /**
  30782. * Defines the center of rotation (U)
  30783. */
  30784. _this.uRotationCenter = 0.5;
  30785. /**
  30786. * Defines the center of rotation (V)
  30787. */
  30788. _this.vRotationCenter = 0.5;
  30789. /**
  30790. * Defines the center of rotation (W)
  30791. */
  30792. _this.wRotationCenter = 0.5;
  30793. _this._isBlocking = true;
  30794. _this.name = url || "";
  30795. _this.url = url;
  30796. _this._noMipmap = noMipmap;
  30797. _this._invertY = invertY;
  30798. _this._samplingMode = samplingMode;
  30799. _this._buffer = buffer;
  30800. _this._deleteBuffer = deleteBuffer;
  30801. if (format) {
  30802. _this._format = format;
  30803. }
  30804. scene = _this.getScene();
  30805. if (!scene) {
  30806. return _this;
  30807. }
  30808. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30809. var load = function () {
  30810. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30811. _this.onLoadObservable.notifyObservers(_this);
  30812. }
  30813. if (onLoad) {
  30814. onLoad();
  30815. }
  30816. if (!_this.isBlocking && scene) {
  30817. scene.resetCachedMaterial();
  30818. }
  30819. };
  30820. if (!_this.url) {
  30821. _this._delayedOnLoad = load;
  30822. _this._delayedOnError = onError;
  30823. return _this;
  30824. }
  30825. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30826. if (!_this._texture) {
  30827. if (!scene.useDelayedTextureLoading) {
  30828. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30829. if (deleteBuffer) {
  30830. delete _this._buffer;
  30831. }
  30832. }
  30833. else {
  30834. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30835. _this._delayedOnLoad = load;
  30836. _this._delayedOnError = onError;
  30837. }
  30838. }
  30839. else {
  30840. if (_this._texture.isReady) {
  30841. BABYLON.Tools.SetImmediate(function () { return load(); });
  30842. }
  30843. else {
  30844. _this._texture.onLoadedObservable.add(load);
  30845. }
  30846. }
  30847. return _this;
  30848. }
  30849. Object.defineProperty(Texture.prototype, "noMipmap", {
  30850. get: function () {
  30851. return this._noMipmap;
  30852. },
  30853. enumerable: true,
  30854. configurable: true
  30855. });
  30856. Object.defineProperty(Texture.prototype, "isBlocking", {
  30857. get: function () {
  30858. return this._isBlocking;
  30859. },
  30860. set: function (value) {
  30861. this._isBlocking = value;
  30862. },
  30863. enumerable: true,
  30864. configurable: true
  30865. });
  30866. Object.defineProperty(Texture.prototype, "samplingMode", {
  30867. get: function () {
  30868. return this._samplingMode;
  30869. },
  30870. enumerable: true,
  30871. configurable: true
  30872. });
  30873. /**
  30874. * Update the url (and optional buffer) of this texture if url was null during construction.
  30875. * @param url the url of the texture
  30876. * @param buffer the buffer of the texture (defaults to null)
  30877. */
  30878. Texture.prototype.updateURL = function (url, buffer) {
  30879. if (buffer === void 0) { buffer = null; }
  30880. if (this.url) {
  30881. throw new Error("URL is already set");
  30882. }
  30883. this.url = url;
  30884. this._buffer = buffer;
  30885. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30886. this.delayLoad();
  30887. };
  30888. Texture.prototype.delayLoad = function () {
  30889. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30890. return;
  30891. }
  30892. var scene = this.getScene();
  30893. if (!scene) {
  30894. return;
  30895. }
  30896. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30897. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30898. if (!this._texture) {
  30899. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30900. if (this._deleteBuffer) {
  30901. delete this._buffer;
  30902. }
  30903. }
  30904. else {
  30905. if (this._delayedOnLoad) {
  30906. if (this._texture.isReady) {
  30907. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30908. }
  30909. else {
  30910. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30911. }
  30912. }
  30913. }
  30914. this._delayedOnLoad = null;
  30915. this._delayedOnError = null;
  30916. };
  30917. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30918. if (!this._texture) {
  30919. return;
  30920. }
  30921. var scene = this.getScene();
  30922. if (!scene) {
  30923. return;
  30924. }
  30925. this._samplingMode = samplingMode;
  30926. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30927. };
  30928. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30929. x *= this.uScale;
  30930. y *= this.vScale;
  30931. x -= this.uRotationCenter * this.uScale;
  30932. y -= this.vRotationCenter * this.vScale;
  30933. z -= this.wRotationCenter;
  30934. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30935. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30936. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30937. t.z += this.wRotationCenter;
  30938. };
  30939. Texture.prototype.getTextureMatrix = function () {
  30940. var _this = this;
  30941. if (this.uOffset === this._cachedUOffset &&
  30942. this.vOffset === this._cachedVOffset &&
  30943. this.uScale === this._cachedUScale &&
  30944. this.vScale === this._cachedVScale &&
  30945. this.uAng === this._cachedUAng &&
  30946. this.vAng === this._cachedVAng &&
  30947. this.wAng === this._cachedWAng) {
  30948. return this._cachedTextureMatrix;
  30949. }
  30950. this._cachedUOffset = this.uOffset;
  30951. this._cachedVOffset = this.vOffset;
  30952. this._cachedUScale = this.uScale;
  30953. this._cachedVScale = this.vScale;
  30954. this._cachedUAng = this.uAng;
  30955. this._cachedVAng = this.vAng;
  30956. this._cachedWAng = this.wAng;
  30957. if (!this._cachedTextureMatrix) {
  30958. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30959. this._rowGenerationMatrix = new BABYLON.Matrix();
  30960. this._t0 = BABYLON.Vector3.Zero();
  30961. this._t1 = BABYLON.Vector3.Zero();
  30962. this._t2 = BABYLON.Vector3.Zero();
  30963. }
  30964. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30965. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30966. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30967. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30968. this._t1.subtractInPlace(this._t0);
  30969. this._t2.subtractInPlace(this._t0);
  30970. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30971. this._cachedTextureMatrix.m[0] = this._t1.x;
  30972. this._cachedTextureMatrix.m[1] = this._t1.y;
  30973. this._cachedTextureMatrix.m[2] = this._t1.z;
  30974. this._cachedTextureMatrix.m[4] = this._t2.x;
  30975. this._cachedTextureMatrix.m[5] = this._t2.y;
  30976. this._cachedTextureMatrix.m[6] = this._t2.z;
  30977. this._cachedTextureMatrix.m[8] = this._t0.x;
  30978. this._cachedTextureMatrix.m[9] = this._t0.y;
  30979. this._cachedTextureMatrix.m[10] = this._t0.z;
  30980. var scene = this.getScene();
  30981. if (!scene) {
  30982. return this._cachedTextureMatrix;
  30983. }
  30984. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30985. return mat.hasTexture(_this);
  30986. });
  30987. return this._cachedTextureMatrix;
  30988. };
  30989. Texture.prototype.getReflectionTextureMatrix = function () {
  30990. var _this = this;
  30991. var scene = this.getScene();
  30992. if (!scene) {
  30993. return this._cachedTextureMatrix;
  30994. }
  30995. if (this.uOffset === this._cachedUOffset &&
  30996. this.vOffset === this._cachedVOffset &&
  30997. this.uScale === this._cachedUScale &&
  30998. this.vScale === this._cachedVScale &&
  30999. this.coordinatesMode === this._cachedCoordinatesMode) {
  31000. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31001. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31002. return this._cachedTextureMatrix;
  31003. }
  31004. }
  31005. else {
  31006. return this._cachedTextureMatrix;
  31007. }
  31008. }
  31009. if (!this._cachedTextureMatrix) {
  31010. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31011. }
  31012. if (!this._projectionModeMatrix) {
  31013. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31014. }
  31015. this._cachedUOffset = this.uOffset;
  31016. this._cachedVOffset = this.vOffset;
  31017. this._cachedUScale = this.uScale;
  31018. this._cachedVScale = this.vScale;
  31019. this._cachedCoordinatesMode = this.coordinatesMode;
  31020. switch (this.coordinatesMode) {
  31021. case Texture.PLANAR_MODE:
  31022. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31023. this._cachedTextureMatrix[0] = this.uScale;
  31024. this._cachedTextureMatrix[5] = this.vScale;
  31025. this._cachedTextureMatrix[12] = this.uOffset;
  31026. this._cachedTextureMatrix[13] = this.vOffset;
  31027. break;
  31028. case Texture.PROJECTION_MODE:
  31029. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31030. this._projectionModeMatrix.m[0] = 0.5;
  31031. this._projectionModeMatrix.m[5] = -0.5;
  31032. this._projectionModeMatrix.m[10] = 0.0;
  31033. this._projectionModeMatrix.m[12] = 0.5;
  31034. this._projectionModeMatrix.m[13] = 0.5;
  31035. this._projectionModeMatrix.m[14] = 1.0;
  31036. this._projectionModeMatrix.m[15] = 1.0;
  31037. var projectionMatrix = scene.getProjectionMatrix();
  31038. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31039. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31040. break;
  31041. default:
  31042. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31043. break;
  31044. }
  31045. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31046. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31047. });
  31048. return this._cachedTextureMatrix;
  31049. };
  31050. Texture.prototype.clone = function () {
  31051. var _this = this;
  31052. return BABYLON.SerializationHelper.Clone(function () {
  31053. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31054. }, this);
  31055. };
  31056. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31057. get: function () {
  31058. if (!this._onLoadObservable) {
  31059. this._onLoadObservable = new BABYLON.Observable();
  31060. }
  31061. return this._onLoadObservable;
  31062. },
  31063. enumerable: true,
  31064. configurable: true
  31065. });
  31066. Texture.prototype.serialize = function () {
  31067. var serializationObject = _super.prototype.serialize.call(this);
  31068. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31069. serializationObject.base64String = this._buffer;
  31070. serializationObject.name = serializationObject.name.replace("data:", "");
  31071. }
  31072. serializationObject.invertY = this._invertY;
  31073. serializationObject.samplingMode = this.samplingMode;
  31074. return serializationObject;
  31075. };
  31076. Texture.prototype.getClassName = function () {
  31077. return "Texture";
  31078. };
  31079. Texture.prototype.dispose = function () {
  31080. _super.prototype.dispose.call(this);
  31081. if (this.onLoadObservable) {
  31082. this.onLoadObservable.clear();
  31083. this._onLoadObservable = null;
  31084. }
  31085. this._delayedOnLoad = null;
  31086. this._delayedOnError = null;
  31087. };
  31088. // Statics
  31089. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31090. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31091. if (onLoad === void 0) { onLoad = null; }
  31092. if (onError === void 0) { onError = null; }
  31093. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31094. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31095. };
  31096. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31097. if (parsedTexture.customType) {
  31098. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31099. // Update Sampling Mode
  31100. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31101. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31102. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31103. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31104. }
  31105. }
  31106. return parsedCustomTexture;
  31107. }
  31108. if (parsedTexture.isCube) {
  31109. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31110. }
  31111. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31112. return null;
  31113. }
  31114. var texture = BABYLON.SerializationHelper.Parse(function () {
  31115. var generateMipMaps = true;
  31116. if (parsedTexture.noMipmap) {
  31117. generateMipMaps = false;
  31118. }
  31119. if (parsedTexture.mirrorPlane) {
  31120. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31121. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31122. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31123. return mirrorTexture;
  31124. }
  31125. else if (parsedTexture.isRenderTarget) {
  31126. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31127. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31128. return renderTargetTexture;
  31129. }
  31130. else {
  31131. var texture;
  31132. if (parsedTexture.base64String) {
  31133. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31134. }
  31135. else {
  31136. var url = rootUrl + parsedTexture.name;
  31137. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31138. url = parsedTexture.url;
  31139. }
  31140. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31141. }
  31142. return texture;
  31143. }
  31144. }, parsedTexture, scene);
  31145. // Update Sampling Mode
  31146. if (parsedTexture.samplingMode) {
  31147. var sampling = parsedTexture.samplingMode;
  31148. if (texture._samplingMode !== sampling) {
  31149. texture.updateSamplingMode(sampling);
  31150. }
  31151. }
  31152. // Animations
  31153. if (parsedTexture.animations) {
  31154. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31155. var parsedAnimation = parsedTexture.animations[animationIndex];
  31156. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31157. }
  31158. }
  31159. return texture;
  31160. };
  31161. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31162. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31163. if (noMipmap === void 0) { noMipmap = false; }
  31164. if (invertY === void 0) { invertY = true; }
  31165. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31166. if (onLoad === void 0) { onLoad = null; }
  31167. if (onError === void 0) { onError = null; }
  31168. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31169. if (name.substr(0, 5) !== "data:") {
  31170. name = "data:" + name;
  31171. }
  31172. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31173. };
  31174. // Constants
  31175. Texture.NEAREST_SAMPLINGMODE = 1;
  31176. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31177. Texture.BILINEAR_SAMPLINGMODE = 2;
  31178. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31179. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31180. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31181. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31182. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31183. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31184. Texture.NEAREST_LINEAR = 7;
  31185. Texture.NEAREST_NEAREST = 8;
  31186. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31187. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31188. Texture.LINEAR_LINEAR = 11;
  31189. Texture.LINEAR_NEAREST = 12;
  31190. Texture.EXPLICIT_MODE = 0;
  31191. Texture.SPHERICAL_MODE = 1;
  31192. Texture.PLANAR_MODE = 2;
  31193. Texture.CUBIC_MODE = 3;
  31194. Texture.PROJECTION_MODE = 4;
  31195. Texture.SKYBOX_MODE = 5;
  31196. Texture.INVCUBIC_MODE = 6;
  31197. Texture.EQUIRECTANGULAR_MODE = 7;
  31198. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31199. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31200. Texture.CLAMP_ADDRESSMODE = 0;
  31201. Texture.WRAP_ADDRESSMODE = 1;
  31202. Texture.MIRROR_ADDRESSMODE = 2;
  31203. /**
  31204. * 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
  31205. */
  31206. Texture.UseSerializedUrlIfAny = false;
  31207. __decorate([
  31208. BABYLON.serialize()
  31209. ], Texture.prototype, "url", void 0);
  31210. __decorate([
  31211. BABYLON.serialize()
  31212. ], Texture.prototype, "uOffset", void 0);
  31213. __decorate([
  31214. BABYLON.serialize()
  31215. ], Texture.prototype, "vOffset", void 0);
  31216. __decorate([
  31217. BABYLON.serialize()
  31218. ], Texture.prototype, "uScale", void 0);
  31219. __decorate([
  31220. BABYLON.serialize()
  31221. ], Texture.prototype, "vScale", void 0);
  31222. __decorate([
  31223. BABYLON.serialize()
  31224. ], Texture.prototype, "uAng", void 0);
  31225. __decorate([
  31226. BABYLON.serialize()
  31227. ], Texture.prototype, "vAng", void 0);
  31228. __decorate([
  31229. BABYLON.serialize()
  31230. ], Texture.prototype, "wAng", void 0);
  31231. __decorate([
  31232. BABYLON.serialize()
  31233. ], Texture.prototype, "uRotationCenter", void 0);
  31234. __decorate([
  31235. BABYLON.serialize()
  31236. ], Texture.prototype, "vRotationCenter", void 0);
  31237. __decorate([
  31238. BABYLON.serialize()
  31239. ], Texture.prototype, "wRotationCenter", void 0);
  31240. __decorate([
  31241. BABYLON.serialize()
  31242. ], Texture.prototype, "isBlocking", null);
  31243. return Texture;
  31244. }(BABYLON.BaseTexture));
  31245. BABYLON.Texture = Texture;
  31246. })(BABYLON || (BABYLON = {}));
  31247. //# sourceMappingURL=babylon.texture.js.map
  31248. var BABYLON;
  31249. (function (BABYLON) {
  31250. /**
  31251. * @hidden
  31252. **/
  31253. var _InstancesBatch = /** @class */ (function () {
  31254. function _InstancesBatch() {
  31255. this.mustReturn = false;
  31256. this.visibleInstances = new Array();
  31257. this.renderSelf = new Array();
  31258. }
  31259. return _InstancesBatch;
  31260. }());
  31261. BABYLON._InstancesBatch = _InstancesBatch;
  31262. var Mesh = /** @class */ (function (_super) {
  31263. __extends(Mesh, _super);
  31264. /**
  31265. * @constructor
  31266. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31267. * @param {Scene} scene The scene to add this mesh to.
  31268. * @param {Node} parent The parent of this mesh, if it has one
  31269. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31270. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31271. * When false, achieved by calling a clone(), also passing False.
  31272. * This will make creation of children, recursive.
  31273. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31274. */
  31275. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31276. if (scene === void 0) { scene = null; }
  31277. if (parent === void 0) { parent = null; }
  31278. if (source === void 0) { source = null; }
  31279. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31280. var _this = _super.call(this, name, scene) || this;
  31281. // Events
  31282. /**
  31283. * An event triggered before rendering the mesh
  31284. */
  31285. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31286. /**
  31287. * An event triggered after rendering the mesh
  31288. */
  31289. _this.onAfterRenderObservable = new BABYLON.Observable();
  31290. /**
  31291. * An event triggered before drawing the mesh
  31292. */
  31293. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31294. // Members
  31295. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31296. _this.instances = new Array();
  31297. _this._LODLevels = new Array();
  31298. _this._visibleInstances = {};
  31299. _this._renderIdForInstances = new Array();
  31300. _this._batchCache = new _InstancesBatch();
  31301. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31302. // Use by builder only to know what orientation were the mesh build in.
  31303. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31304. _this.overrideMaterialSideOrientation = null;
  31305. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31306. // Will be used to save a source mesh reference, If any
  31307. _this._source = null;
  31308. scene = _this.getScene();
  31309. if (source) {
  31310. // Geometry
  31311. if (source._geometry) {
  31312. source._geometry.applyToMesh(_this);
  31313. }
  31314. // Deep copy
  31315. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31316. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31317. // Source mesh
  31318. _this._source = source;
  31319. // Metadata
  31320. if (source.metadata && source.metadata.clone) {
  31321. _this.metadata = source.metadata.clone();
  31322. }
  31323. else {
  31324. _this.metadata = source.metadata;
  31325. }
  31326. // Tags
  31327. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31328. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31329. }
  31330. // Parent
  31331. _this.parent = source.parent;
  31332. // Pivot
  31333. _this.setPivotMatrix(source.getPivotMatrix());
  31334. _this.id = name + "." + source.id;
  31335. // Material
  31336. _this.material = source.material;
  31337. var index;
  31338. if (!doNotCloneChildren) {
  31339. // Children
  31340. var directDescendants = source.getDescendants(true);
  31341. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31342. var child = directDescendants[index_1];
  31343. if (child.clone) {
  31344. child.clone(name + "." + child.name, _this);
  31345. }
  31346. }
  31347. }
  31348. // Physics clone
  31349. var physicsEngine = _this.getScene().getPhysicsEngine();
  31350. if (clonePhysicsImpostor && physicsEngine) {
  31351. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31352. if (impostor) {
  31353. _this.physicsImpostor = impostor.clone(_this);
  31354. }
  31355. }
  31356. // Particles
  31357. for (index = 0; index < scene.particleSystems.length; index++) {
  31358. var system = scene.particleSystems[index];
  31359. if (system.emitter === source) {
  31360. system.clone(system.name, _this);
  31361. }
  31362. }
  31363. _this.computeWorldMatrix(true);
  31364. }
  31365. // Parent
  31366. if (parent !== null) {
  31367. _this.parent = parent;
  31368. }
  31369. return _this;
  31370. }
  31371. Object.defineProperty(Mesh, "FRONTSIDE", {
  31372. /**
  31373. * Mesh side orientation : usually the external or front surface
  31374. */
  31375. get: function () {
  31376. return Mesh._FRONTSIDE;
  31377. },
  31378. enumerable: true,
  31379. configurable: true
  31380. });
  31381. Object.defineProperty(Mesh, "BACKSIDE", {
  31382. /**
  31383. * Mesh side orientation : usually the internal or back surface
  31384. */
  31385. get: function () {
  31386. return Mesh._BACKSIDE;
  31387. },
  31388. enumerable: true,
  31389. configurable: true
  31390. });
  31391. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31392. /**
  31393. * Mesh side orientation : both internal and external or front and back surfaces
  31394. */
  31395. get: function () {
  31396. return Mesh._DOUBLESIDE;
  31397. },
  31398. enumerable: true,
  31399. configurable: true
  31400. });
  31401. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31402. /**
  31403. * Mesh side orientation : by default, `FRONTSIDE`
  31404. */
  31405. get: function () {
  31406. return Mesh._DEFAULTSIDE;
  31407. },
  31408. enumerable: true,
  31409. configurable: true
  31410. });
  31411. Object.defineProperty(Mesh, "NO_CAP", {
  31412. /**
  31413. * Mesh cap setting : no cap
  31414. */
  31415. get: function () {
  31416. return Mesh._NO_CAP;
  31417. },
  31418. enumerable: true,
  31419. configurable: true
  31420. });
  31421. Object.defineProperty(Mesh, "CAP_START", {
  31422. /**
  31423. * Mesh cap setting : one cap at the beginning of the mesh
  31424. */
  31425. get: function () {
  31426. return Mesh._CAP_START;
  31427. },
  31428. enumerable: true,
  31429. configurable: true
  31430. });
  31431. Object.defineProperty(Mesh, "CAP_END", {
  31432. /**
  31433. * Mesh cap setting : one cap at the end of the mesh
  31434. */
  31435. get: function () {
  31436. return Mesh._CAP_END;
  31437. },
  31438. enumerable: true,
  31439. configurable: true
  31440. });
  31441. Object.defineProperty(Mesh, "CAP_ALL", {
  31442. /**
  31443. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31444. */
  31445. get: function () {
  31446. return Mesh._CAP_ALL;
  31447. },
  31448. enumerable: true,
  31449. configurable: true
  31450. });
  31451. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31452. set: function (callback) {
  31453. if (this._onBeforeDrawObserver) {
  31454. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31455. }
  31456. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31457. },
  31458. enumerable: true,
  31459. configurable: true
  31460. });
  31461. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31462. get: function () {
  31463. return this._morphTargetManager;
  31464. },
  31465. set: function (value) {
  31466. if (this._morphTargetManager === value) {
  31467. return;
  31468. }
  31469. this._morphTargetManager = value;
  31470. this._syncGeometryWithMorphTargetManager();
  31471. },
  31472. enumerable: true,
  31473. configurable: true
  31474. });
  31475. Object.defineProperty(Mesh.prototype, "source", {
  31476. get: function () {
  31477. return this._source;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31483. get: function () {
  31484. return this._unIndexed;
  31485. },
  31486. set: function (value) {
  31487. if (this._unIndexed !== value) {
  31488. this._unIndexed = value;
  31489. this._markSubMeshesAsAttributesDirty();
  31490. }
  31491. },
  31492. enumerable: true,
  31493. configurable: true
  31494. });
  31495. // Methods
  31496. /**
  31497. * Returns the string "Mesh".
  31498. */
  31499. Mesh.prototype.getClassName = function () {
  31500. return "Mesh";
  31501. };
  31502. /**
  31503. * Returns a string.
  31504. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31505. */
  31506. Mesh.prototype.toString = function (fullDetails) {
  31507. var ret = _super.prototype.toString.call(this, fullDetails);
  31508. ret += ", n vertices: " + this.getTotalVertices();
  31509. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31510. if (this.animations) {
  31511. for (var i = 0; i < this.animations.length; i++) {
  31512. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31513. }
  31514. }
  31515. if (fullDetails) {
  31516. if (this._geometry) {
  31517. var ib = this.getIndices();
  31518. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31519. if (vb && ib) {
  31520. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31521. }
  31522. }
  31523. else {
  31524. ret += ", flat shading: UNKNOWN";
  31525. }
  31526. }
  31527. return ret;
  31528. };
  31529. Mesh.prototype._unBindEffect = function () {
  31530. _super.prototype._unBindEffect.call(this);
  31531. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31532. var instance = _a[_i];
  31533. instance._unBindEffect();
  31534. }
  31535. };
  31536. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31537. /**
  31538. * True if the mesh has some Levels Of Details (LOD).
  31539. * Returns a boolean.
  31540. */
  31541. get: function () {
  31542. return this._LODLevels.length > 0;
  31543. },
  31544. enumerable: true,
  31545. configurable: true
  31546. });
  31547. /**
  31548. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31549. * @returns an array of {BABYLON.MeshLODLevel}
  31550. */
  31551. Mesh.prototype.getLODLevels = function () {
  31552. return this._LODLevels;
  31553. };
  31554. Mesh.prototype._sortLODLevels = function () {
  31555. this._LODLevels.sort(function (a, b) {
  31556. if (a.distance < b.distance) {
  31557. return 1;
  31558. }
  31559. if (a.distance > b.distance) {
  31560. return -1;
  31561. }
  31562. return 0;
  31563. });
  31564. };
  31565. /**
  31566. * Add a mesh as LOD level triggered at the given distance.
  31567. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31568. * @param {number} distance The distance from the center of the object to show this level
  31569. * @param {Mesh} mesh The mesh to be added as LOD level
  31570. * @return {Mesh} This mesh (for chaining)
  31571. */
  31572. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31573. if (mesh && mesh._masterMesh) {
  31574. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31575. return this;
  31576. }
  31577. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31578. this._LODLevels.push(level);
  31579. if (mesh) {
  31580. mesh._masterMesh = this;
  31581. }
  31582. this._sortLODLevels();
  31583. return this;
  31584. };
  31585. /**
  31586. * Returns the LOD level mesh at the passed distance or null if not found.
  31587. * It is related to the method `addLODLevel(distance, mesh)`.
  31588. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31589. * Returns an object Mesh or `null`.
  31590. */
  31591. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31592. for (var index = 0; index < this._LODLevels.length; index++) {
  31593. var level = this._LODLevels[index];
  31594. if (level.distance === distance) {
  31595. return level.mesh;
  31596. }
  31597. }
  31598. return null;
  31599. };
  31600. /**
  31601. * Remove a mesh from the LOD array
  31602. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31603. * @param {Mesh} mesh The mesh to be removed.
  31604. * @return {Mesh} This mesh (for chaining)
  31605. */
  31606. Mesh.prototype.removeLODLevel = function (mesh) {
  31607. for (var index = 0; index < this._LODLevels.length; index++) {
  31608. if (this._LODLevels[index].mesh === mesh) {
  31609. this._LODLevels.splice(index, 1);
  31610. if (mesh) {
  31611. mesh._masterMesh = null;
  31612. }
  31613. }
  31614. }
  31615. this._sortLODLevels();
  31616. return this;
  31617. };
  31618. /**
  31619. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31620. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31621. */
  31622. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31623. if (!this._LODLevels || this._LODLevels.length === 0) {
  31624. return this;
  31625. }
  31626. var bSphere;
  31627. if (boundingSphere) {
  31628. bSphere = boundingSphere;
  31629. }
  31630. else {
  31631. var boundingInfo = this.getBoundingInfo();
  31632. bSphere = boundingInfo.boundingSphere;
  31633. }
  31634. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31635. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31636. if (this.onLODLevelSelection) {
  31637. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31638. }
  31639. return this;
  31640. }
  31641. for (var index = 0; index < this._LODLevels.length; index++) {
  31642. var level = this._LODLevels[index];
  31643. if (level.distance < distanceToCamera) {
  31644. if (level.mesh) {
  31645. level.mesh._preActivate();
  31646. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31647. }
  31648. if (this.onLODLevelSelection) {
  31649. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31650. }
  31651. return level.mesh;
  31652. }
  31653. }
  31654. if (this.onLODLevelSelection) {
  31655. this.onLODLevelSelection(distanceToCamera, this, this);
  31656. }
  31657. return this;
  31658. };
  31659. Object.defineProperty(Mesh.prototype, "geometry", {
  31660. /**
  31661. * Returns the mesh internal Geometry object.
  31662. */
  31663. get: function () {
  31664. return this._geometry;
  31665. },
  31666. enumerable: true,
  31667. configurable: true
  31668. });
  31669. /**
  31670. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31671. */
  31672. Mesh.prototype.getTotalVertices = function () {
  31673. if (this._geometry === null || this._geometry === undefined) {
  31674. return 0;
  31675. }
  31676. return this._geometry.getTotalVertices();
  31677. };
  31678. /**
  31679. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31680. * 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.
  31681. * You can force the copy with forceCopy === true
  31682. * Returns null if the mesh has no geometry or no vertex buffer.
  31683. * Possible `kind` values :
  31684. * - BABYLON.VertexBuffer.PositionKind
  31685. * - BABYLON.VertexBuffer.UVKind
  31686. * - BABYLON.VertexBuffer.UV2Kind
  31687. * - BABYLON.VertexBuffer.UV3Kind
  31688. * - BABYLON.VertexBuffer.UV4Kind
  31689. * - BABYLON.VertexBuffer.UV5Kind
  31690. * - BABYLON.VertexBuffer.UV6Kind
  31691. * - BABYLON.VertexBuffer.ColorKind
  31692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31696. */
  31697. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31698. if (!this._geometry) {
  31699. return null;
  31700. }
  31701. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31702. };
  31703. /**
  31704. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31705. * Returns `null` if the mesh has no geometry.
  31706. * Possible `kind` values :
  31707. * - BABYLON.VertexBuffer.PositionKind
  31708. * - BABYLON.VertexBuffer.UVKind
  31709. * - BABYLON.VertexBuffer.UV2Kind
  31710. * - BABYLON.VertexBuffer.UV3Kind
  31711. * - BABYLON.VertexBuffer.UV4Kind
  31712. * - BABYLON.VertexBuffer.UV5Kind
  31713. * - BABYLON.VertexBuffer.UV6Kind
  31714. * - BABYLON.VertexBuffer.ColorKind
  31715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31719. */
  31720. Mesh.prototype.getVertexBuffer = function (kind) {
  31721. if (!this._geometry) {
  31722. return null;
  31723. }
  31724. return this._geometry.getVertexBuffer(kind);
  31725. };
  31726. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31727. if (!this._geometry) {
  31728. if (this._delayInfo) {
  31729. return this._delayInfo.indexOf(kind) !== -1;
  31730. }
  31731. return false;
  31732. }
  31733. return this._geometry.isVerticesDataPresent(kind);
  31734. };
  31735. /**
  31736. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31737. * Possible `kind` values :
  31738. * - BABYLON.VertexBuffer.PositionKind
  31739. * - BABYLON.VertexBuffer.UVKind
  31740. * - BABYLON.VertexBuffer.UV2Kind
  31741. * - BABYLON.VertexBuffer.UV3Kind
  31742. * - BABYLON.VertexBuffer.UV4Kind
  31743. * - BABYLON.VertexBuffer.UV5Kind
  31744. * - BABYLON.VertexBuffer.UV6Kind
  31745. * - BABYLON.VertexBuffer.ColorKind
  31746. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31747. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31748. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31749. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31750. */
  31751. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31752. if (!this._geometry) {
  31753. if (this._delayInfo) {
  31754. return this._delayInfo.indexOf(kind) !== -1;
  31755. }
  31756. return false;
  31757. }
  31758. return this._geometry.isVertexBufferUpdatable(kind);
  31759. };
  31760. /**
  31761. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31762. * Possible `kind` values :
  31763. * - BABYLON.VertexBuffer.PositionKind
  31764. * - BABYLON.VertexBuffer.UVKind
  31765. * - BABYLON.VertexBuffer.UV2Kind
  31766. * - BABYLON.VertexBuffer.UV3Kind
  31767. * - BABYLON.VertexBuffer.UV4Kind
  31768. * - BABYLON.VertexBuffer.UV5Kind
  31769. * - BABYLON.VertexBuffer.UV6Kind
  31770. * - BABYLON.VertexBuffer.ColorKind
  31771. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31772. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31773. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31774. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31775. */
  31776. Mesh.prototype.getVerticesDataKinds = function () {
  31777. if (!this._geometry) {
  31778. var result = new Array();
  31779. if (this._delayInfo) {
  31780. this._delayInfo.forEach(function (kind, index, array) {
  31781. result.push(kind);
  31782. });
  31783. }
  31784. return result;
  31785. }
  31786. return this._geometry.getVerticesDataKinds();
  31787. };
  31788. /**
  31789. * Returns a positive integer : the total number of indices in this mesh geometry.
  31790. * Returns zero if the mesh has no geometry.
  31791. */
  31792. Mesh.prototype.getTotalIndices = function () {
  31793. if (!this._geometry) {
  31794. return 0;
  31795. }
  31796. return this._geometry.getTotalIndices();
  31797. };
  31798. /**
  31799. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31800. * 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.
  31801. * Returns an empty array if the mesh has no geometry.
  31802. */
  31803. Mesh.prototype.getIndices = function (copyWhenShared) {
  31804. if (!this._geometry) {
  31805. return [];
  31806. }
  31807. return this._geometry.getIndices(copyWhenShared);
  31808. };
  31809. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31810. get: function () {
  31811. return this._masterMesh !== null && this._masterMesh !== undefined;
  31812. },
  31813. enumerable: true,
  31814. configurable: true
  31815. });
  31816. /**
  31817. * Determine if the current mesh is ready to be rendered
  31818. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31819. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31820. * @returns true if all associated assets are ready (material, textures, shaders)
  31821. */
  31822. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31823. if (completeCheck === void 0) { completeCheck = false; }
  31824. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31825. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31826. return false;
  31827. }
  31828. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31829. return false;
  31830. }
  31831. if (!this.subMeshes || this.subMeshes.length === 0) {
  31832. return true;
  31833. }
  31834. if (!completeCheck) {
  31835. return true;
  31836. }
  31837. var engine = this.getEngine();
  31838. var scene = this.getScene();
  31839. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31840. this.computeWorldMatrix();
  31841. var mat = this.material || scene.defaultMaterial;
  31842. if (mat) {
  31843. if (mat.storeEffectOnSubMeshes) {
  31844. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31845. var subMesh = _a[_i];
  31846. var effectiveMaterial = subMesh.getMaterial();
  31847. if (effectiveMaterial) {
  31848. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31849. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31850. return false;
  31851. }
  31852. }
  31853. else {
  31854. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31855. return false;
  31856. }
  31857. }
  31858. }
  31859. }
  31860. }
  31861. else {
  31862. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31863. return false;
  31864. }
  31865. }
  31866. }
  31867. // Shadows
  31868. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31869. var light = _c[_b];
  31870. var generator = light.getShadowGenerator();
  31871. if (generator) {
  31872. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31873. var subMesh = _e[_d];
  31874. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31875. return false;
  31876. }
  31877. }
  31878. }
  31879. }
  31880. // LOD
  31881. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31882. var lod = _g[_f];
  31883. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31884. return false;
  31885. }
  31886. }
  31887. return true;
  31888. };
  31889. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31890. /**
  31891. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31892. * This property is pertinent only for updatable parametric shapes.
  31893. */
  31894. get: function () {
  31895. return this._areNormalsFrozen;
  31896. },
  31897. enumerable: true,
  31898. configurable: true
  31899. });
  31900. /**
  31901. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31902. * It has no effect at all on other shapes.
  31903. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31904. * Returns the Mesh.
  31905. */
  31906. Mesh.prototype.freezeNormals = function () {
  31907. this._areNormalsFrozen = true;
  31908. return this;
  31909. };
  31910. /**
  31911. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31912. * It has no effect at all on other shapes.
  31913. * It reactivates the mesh normals computation if it was previously frozen.
  31914. * Returns the Mesh.
  31915. */
  31916. Mesh.prototype.unfreezeNormals = function () {
  31917. this._areNormalsFrozen = false;
  31918. return this;
  31919. };
  31920. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31921. /**
  31922. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31923. */
  31924. set: function (count) {
  31925. this._overridenInstanceCount = count;
  31926. },
  31927. enumerable: true,
  31928. configurable: true
  31929. });
  31930. // Methods
  31931. Mesh.prototype._preActivate = function () {
  31932. var sceneRenderId = this.getScene().getRenderId();
  31933. if (this._preActivateId === sceneRenderId) {
  31934. return this;
  31935. }
  31936. this._preActivateId = sceneRenderId;
  31937. this._visibleInstances = null;
  31938. return this;
  31939. };
  31940. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31941. if (this._visibleInstances) {
  31942. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31943. }
  31944. return this;
  31945. };
  31946. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31947. if (!this._visibleInstances) {
  31948. this._visibleInstances = {};
  31949. this._visibleInstances.defaultRenderId = renderId;
  31950. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31951. }
  31952. if (!this._visibleInstances[renderId]) {
  31953. this._visibleInstances[renderId] = new Array();
  31954. }
  31955. this._visibleInstances[renderId].push(instance);
  31956. return this;
  31957. };
  31958. /**
  31959. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31960. * This means the mesh underlying bounding box and sphere are recomputed.
  31961. * Returns the Mesh.
  31962. */
  31963. Mesh.prototype.refreshBoundingInfo = function () {
  31964. return this._refreshBoundingInfo(false);
  31965. };
  31966. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31967. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31968. return this;
  31969. }
  31970. var data = this._getPositionData(applySkeleton);
  31971. if (data) {
  31972. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31973. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31974. }
  31975. if (this.subMeshes) {
  31976. for (var index = 0; index < this.subMeshes.length; index++) {
  31977. this.subMeshes[index].refreshBoundingInfo();
  31978. }
  31979. }
  31980. this._updateBoundingInfo();
  31981. return this;
  31982. };
  31983. Mesh.prototype._getPositionData = function (applySkeleton) {
  31984. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31985. if (data && applySkeleton && this.skeleton) {
  31986. data = BABYLON.Tools.Slice(data);
  31987. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31988. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31989. if (matricesWeightsData && matricesIndicesData) {
  31990. var needExtras = this.numBoneInfluencers > 4;
  31991. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31992. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31993. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31994. var tempVector = BABYLON.Tmp.Vector3[0];
  31995. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31996. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31997. var matWeightIdx = 0;
  31998. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31999. finalMatrix.reset();
  32000. var inf;
  32001. var weight;
  32002. for (inf = 0; inf < 4; inf++) {
  32003. weight = matricesWeightsData[matWeightIdx + inf];
  32004. if (weight <= 0)
  32005. break;
  32006. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32007. finalMatrix.addToSelf(tempMatrix);
  32008. }
  32009. if (needExtras) {
  32010. for (inf = 0; inf < 4; inf++) {
  32011. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32012. if (weight <= 0)
  32013. break;
  32014. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32015. finalMatrix.addToSelf(tempMatrix);
  32016. }
  32017. }
  32018. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32019. tempVector.toArray(data, index);
  32020. }
  32021. }
  32022. }
  32023. return data;
  32024. };
  32025. Mesh.prototype._createGlobalSubMesh = function (force) {
  32026. var totalVertices = this.getTotalVertices();
  32027. if (!totalVertices || !this.getIndices()) {
  32028. return null;
  32029. }
  32030. // Check if we need to recreate the submeshes
  32031. if (this.subMeshes && this.subMeshes.length > 0) {
  32032. var ib = this.getIndices();
  32033. if (!ib) {
  32034. return null;
  32035. }
  32036. var totalIndices = ib.length;
  32037. var needToRecreate = false;
  32038. if (force) {
  32039. needToRecreate = true;
  32040. }
  32041. else {
  32042. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32043. var submesh = _a[_i];
  32044. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32045. needToRecreate = true;
  32046. break;
  32047. }
  32048. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32049. needToRecreate = true;
  32050. break;
  32051. }
  32052. }
  32053. }
  32054. if (!needToRecreate) {
  32055. return this.subMeshes[0];
  32056. }
  32057. }
  32058. this.releaseSubMeshes();
  32059. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32060. };
  32061. Mesh.prototype.subdivide = function (count) {
  32062. if (count < 1) {
  32063. return;
  32064. }
  32065. var totalIndices = this.getTotalIndices();
  32066. var subdivisionSize = (totalIndices / count) | 0;
  32067. var offset = 0;
  32068. // Ensure that subdivisionSize is a multiple of 3
  32069. while (subdivisionSize % 3 !== 0) {
  32070. subdivisionSize++;
  32071. }
  32072. this.releaseSubMeshes();
  32073. for (var index = 0; index < count; index++) {
  32074. if (offset >= totalIndices) {
  32075. break;
  32076. }
  32077. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32078. offset += subdivisionSize;
  32079. }
  32080. this.synchronizeInstances();
  32081. };
  32082. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32083. if (updatable === void 0) { updatable = false; }
  32084. if (!this._geometry) {
  32085. var vertexData = new BABYLON.VertexData();
  32086. vertexData.set(data, kind);
  32087. var scene = this.getScene();
  32088. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32089. }
  32090. else {
  32091. this._geometry.setVerticesData(kind, data, updatable, stride);
  32092. }
  32093. return this;
  32094. };
  32095. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32096. if (updatable === void 0) { updatable = true; }
  32097. var vb = this.getVertexBuffer(kind);
  32098. if (!vb || vb.isUpdatable() === updatable) {
  32099. return;
  32100. }
  32101. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32102. };
  32103. /**
  32104. * Sets the mesh VertexBuffer.
  32105. * Returns the Mesh.
  32106. */
  32107. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32108. if (!this._geometry) {
  32109. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32110. }
  32111. this._geometry.setVerticesBuffer(buffer);
  32112. return this;
  32113. };
  32114. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32115. if (!this._geometry) {
  32116. return this;
  32117. }
  32118. if (!makeItUnique) {
  32119. this._geometry.updateVerticesData(kind, data, updateExtends);
  32120. }
  32121. else {
  32122. this.makeGeometryUnique();
  32123. this.updateVerticesData(kind, data, updateExtends, false);
  32124. }
  32125. return this;
  32126. };
  32127. /**
  32128. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32129. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32130. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32131. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32132. * Returns the Mesh.
  32133. */
  32134. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32135. if (computeNormals === void 0) { computeNormals = true; }
  32136. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32137. if (!positions) {
  32138. return this;
  32139. }
  32140. positionFunction(positions);
  32141. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32142. if (computeNormals) {
  32143. var indices = this.getIndices();
  32144. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32145. if (!normals) {
  32146. return this;
  32147. }
  32148. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32149. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32150. }
  32151. return this;
  32152. };
  32153. /**
  32154. * Creates a un-shared specific occurence of the geometry for the mesh.
  32155. * Returns the Mesh.
  32156. */
  32157. Mesh.prototype.makeGeometryUnique = function () {
  32158. if (!this._geometry) {
  32159. return this;
  32160. }
  32161. var oldGeometry = this._geometry;
  32162. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32163. oldGeometry.releaseForMesh(this, true);
  32164. geometry.applyToMesh(this);
  32165. return this;
  32166. };
  32167. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32168. if (totalVertices === void 0) { totalVertices = null; }
  32169. if (updatable === void 0) { updatable = false; }
  32170. if (!this._geometry) {
  32171. var vertexData = new BABYLON.VertexData();
  32172. vertexData.indices = indices;
  32173. var scene = this.getScene();
  32174. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32175. }
  32176. else {
  32177. this._geometry.setIndices(indices, totalVertices, updatable);
  32178. }
  32179. return this;
  32180. };
  32181. /**
  32182. * Update the current index buffer
  32183. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32184. * Returns the Mesh.
  32185. */
  32186. Mesh.prototype.updateIndices = function (indices, offset) {
  32187. if (!this._geometry) {
  32188. return this;
  32189. }
  32190. this._geometry.updateIndices(indices, offset);
  32191. return this;
  32192. };
  32193. /**
  32194. * Invert the geometry to move from a right handed system to a left handed one.
  32195. * Returns the Mesh.
  32196. */
  32197. Mesh.prototype.toLeftHanded = function () {
  32198. if (!this._geometry) {
  32199. return this;
  32200. }
  32201. this._geometry.toLeftHanded();
  32202. return this;
  32203. };
  32204. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32205. if (!this._geometry) {
  32206. return this;
  32207. }
  32208. var engine = this.getScene().getEngine();
  32209. // Wireframe
  32210. var indexToBind;
  32211. if (this._unIndexed) {
  32212. indexToBind = null;
  32213. }
  32214. else {
  32215. switch (fillMode) {
  32216. case BABYLON.Material.PointFillMode:
  32217. indexToBind = null;
  32218. break;
  32219. case BABYLON.Material.WireFrameFillMode:
  32220. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32221. break;
  32222. default:
  32223. case BABYLON.Material.TriangleFillMode:
  32224. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32225. break;
  32226. }
  32227. }
  32228. // VBOs
  32229. this._geometry._bind(effect, indexToBind);
  32230. return this;
  32231. };
  32232. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32233. if (alternate === void 0) { alternate = false; }
  32234. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32235. return this;
  32236. }
  32237. this.onBeforeDrawObservable.notifyObservers(this);
  32238. var scene = this.getScene();
  32239. var engine = scene.getEngine();
  32240. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32241. // or triangles as points
  32242. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32243. }
  32244. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32245. // Triangles as wireframe
  32246. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32247. }
  32248. else {
  32249. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32250. }
  32251. if (scene._isAlternateRenderingEnabled && !alternate) {
  32252. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32253. if (!effect || !scene.activeCamera) {
  32254. return this;
  32255. }
  32256. scene._switchToAlternateCameraConfiguration(true);
  32257. this._effectiveMaterial.bindView(effect);
  32258. this._effectiveMaterial.bindViewProjection(effect);
  32259. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32260. this._draw(subMesh, fillMode, instancesCount, true);
  32261. engine.setViewport(scene.activeCamera.viewport);
  32262. scene._switchToAlternateCameraConfiguration(false);
  32263. this._effectiveMaterial.bindView(effect);
  32264. this._effectiveMaterial.bindViewProjection(effect);
  32265. }
  32266. return this;
  32267. };
  32268. /**
  32269. * Registers for this mesh a javascript function called just before the rendering process.
  32270. * This function is passed the current mesh.
  32271. * Return the Mesh.
  32272. */
  32273. Mesh.prototype.registerBeforeRender = function (func) {
  32274. this.onBeforeRenderObservable.add(func);
  32275. return this;
  32276. };
  32277. /**
  32278. * Disposes a previously registered javascript function called before the rendering.
  32279. * This function is passed the current mesh.
  32280. * Returns the Mesh.
  32281. */
  32282. Mesh.prototype.unregisterBeforeRender = function (func) {
  32283. this.onBeforeRenderObservable.removeCallback(func);
  32284. return this;
  32285. };
  32286. /**
  32287. * Registers for this mesh a javascript function called just after the rendering is complete.
  32288. * This function is passed the current mesh.
  32289. * Returns the Mesh.
  32290. */
  32291. Mesh.prototype.registerAfterRender = function (func) {
  32292. this.onAfterRenderObservable.add(func);
  32293. return this;
  32294. };
  32295. /**
  32296. * Disposes a previously registered javascript function called after the rendering.
  32297. * This function is passed the current mesh.
  32298. * Return the Mesh.
  32299. */
  32300. Mesh.prototype.unregisterAfterRender = function (func) {
  32301. this.onAfterRenderObservable.removeCallback(func);
  32302. return this;
  32303. };
  32304. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32305. var scene = this.getScene();
  32306. this._batchCache.mustReturn = false;
  32307. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32308. this._batchCache.visibleInstances[subMeshId] = null;
  32309. if (this._visibleInstances) {
  32310. var currentRenderId = scene.getRenderId();
  32311. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32312. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32313. var selfRenderId = this._renderId;
  32314. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32315. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32316. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32317. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32318. }
  32319. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32320. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32321. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32322. this._batchCache.mustReturn = true;
  32323. return this._batchCache;
  32324. }
  32325. if (currentRenderId !== selfRenderId) {
  32326. this._batchCache.renderSelf[subMeshId] = false;
  32327. }
  32328. }
  32329. this._renderIdForInstances[subMeshId] = currentRenderId;
  32330. }
  32331. return this._batchCache;
  32332. };
  32333. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32334. var visibleInstances = batch.visibleInstances[subMesh._id];
  32335. if (!visibleInstances) {
  32336. return this;
  32337. }
  32338. var matricesCount = visibleInstances.length + 1;
  32339. var bufferSize = matricesCount * 16 * 4;
  32340. var currentInstancesBufferSize = this._instancesBufferSize;
  32341. var instancesBuffer = this._instancesBuffer;
  32342. while (this._instancesBufferSize < bufferSize) {
  32343. this._instancesBufferSize *= 2;
  32344. }
  32345. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32346. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32347. }
  32348. var offset = 0;
  32349. var instancesCount = 0;
  32350. var world = this.getWorldMatrix();
  32351. if (batch.renderSelf[subMesh._id]) {
  32352. world.copyToArray(this._instancesData, offset);
  32353. offset += 16;
  32354. instancesCount++;
  32355. }
  32356. if (visibleInstances) {
  32357. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32358. var instance = visibleInstances[instanceIndex];
  32359. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32360. offset += 16;
  32361. instancesCount++;
  32362. }
  32363. }
  32364. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32365. if (instancesBuffer) {
  32366. instancesBuffer.dispose();
  32367. }
  32368. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32369. this._instancesBuffer = instancesBuffer;
  32370. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32371. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32372. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32373. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32374. }
  32375. else {
  32376. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32377. }
  32378. this._bind(subMesh, effect, fillMode);
  32379. this._draw(subMesh, fillMode, instancesCount);
  32380. engine.unbindInstanceAttributes();
  32381. return this;
  32382. };
  32383. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32384. var scene = this.getScene();
  32385. var engine = scene.getEngine();
  32386. if (hardwareInstancedRendering) {
  32387. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32388. }
  32389. else {
  32390. if (batch.renderSelf[subMesh._id]) {
  32391. // Draw
  32392. if (onBeforeDraw) {
  32393. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32394. }
  32395. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32396. }
  32397. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32398. if (visibleInstancesForSubMesh) {
  32399. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32400. var instance = visibleInstancesForSubMesh[instanceIndex];
  32401. // World
  32402. var world = instance.getWorldMatrix();
  32403. if (onBeforeDraw) {
  32404. onBeforeDraw(true, world, effectiveMaterial);
  32405. }
  32406. // Draw
  32407. this._draw(subMesh, fillMode);
  32408. }
  32409. }
  32410. }
  32411. return this;
  32412. };
  32413. /**
  32414. * Triggers the draw call for the mesh.
  32415. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32416. * Returns the Mesh.
  32417. */
  32418. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32419. this._checkOcclusionQuery();
  32420. if (this._isOccluded) {
  32421. return this;
  32422. }
  32423. var scene = this.getScene();
  32424. // Managing instances
  32425. var batch = this._getInstancesRenderList(subMesh._id);
  32426. if (batch.mustReturn) {
  32427. return this;
  32428. }
  32429. // Checking geometry state
  32430. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32431. return this;
  32432. }
  32433. this.onBeforeRenderObservable.notifyObservers(this);
  32434. var engine = scene.getEngine();
  32435. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32436. // Material
  32437. var material = subMesh.getMaterial();
  32438. if (!material) {
  32439. return this;
  32440. }
  32441. this._effectiveMaterial = material;
  32442. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32443. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32444. return this;
  32445. }
  32446. }
  32447. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32448. return this;
  32449. }
  32450. // Alpha mode
  32451. if (enableAlphaMode) {
  32452. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32453. }
  32454. // Outline - step 1
  32455. var savedDepthWrite = engine.getDepthWrite();
  32456. if (this.renderOutline) {
  32457. engine.setDepthWrite(false);
  32458. scene.getOutlineRenderer().render(subMesh, batch);
  32459. engine.setDepthWrite(savedDepthWrite);
  32460. }
  32461. var effect;
  32462. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32463. effect = subMesh.effect;
  32464. }
  32465. else {
  32466. effect = this._effectiveMaterial.getEffect();
  32467. }
  32468. if (!effect) {
  32469. return this;
  32470. }
  32471. var sideOrientation = this.overrideMaterialSideOrientation;
  32472. if (sideOrientation == null) {
  32473. sideOrientation = this._effectiveMaterial.sideOrientation;
  32474. if (this._getWorldMatrixDeterminant() < 0) {
  32475. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32476. }
  32477. }
  32478. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32479. if (this._effectiveMaterial.forceDepthWrite) {
  32480. engine.setDepthWrite(true);
  32481. }
  32482. // Bind
  32483. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32484. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32485. this._bind(subMesh, effect, fillMode);
  32486. }
  32487. var world = this.getWorldMatrix();
  32488. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32489. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32490. }
  32491. else {
  32492. this._effectiveMaterial.bind(world, this);
  32493. }
  32494. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32495. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32496. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32497. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32498. }
  32499. // Draw
  32500. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32501. // Unbind
  32502. this._effectiveMaterial.unbind();
  32503. // Outline - step 2
  32504. if (this.renderOutline && savedDepthWrite) {
  32505. engine.setDepthWrite(true);
  32506. engine.setColorWrite(false);
  32507. scene.getOutlineRenderer().render(subMesh, batch);
  32508. engine.setColorWrite(true);
  32509. }
  32510. // Overlay
  32511. if (this.renderOverlay) {
  32512. var currentMode = engine.getAlphaMode();
  32513. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32514. scene.getOutlineRenderer().render(subMesh, batch, true);
  32515. engine.setAlphaMode(currentMode);
  32516. }
  32517. this.onAfterRenderObservable.notifyObservers(this);
  32518. return this;
  32519. };
  32520. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32521. if (isInstance && effectiveMaterial) {
  32522. effectiveMaterial.bindOnlyWorldMatrix(world);
  32523. }
  32524. };
  32525. /**
  32526. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32527. */
  32528. Mesh.prototype.getEmittedParticleSystems = function () {
  32529. var results = new Array();
  32530. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32531. var particleSystem = this.getScene().particleSystems[index];
  32532. if (particleSystem.emitter === this) {
  32533. results.push(particleSystem);
  32534. }
  32535. }
  32536. return results;
  32537. };
  32538. /**
  32539. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32540. */
  32541. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32542. var results = new Array();
  32543. var descendants = this.getDescendants();
  32544. descendants.push(this);
  32545. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32546. var particleSystem = this.getScene().particleSystems[index];
  32547. var emitter = particleSystem.emitter;
  32548. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32549. results.push(particleSystem);
  32550. }
  32551. }
  32552. return results;
  32553. };
  32554. /**
  32555. * Normalize matrix weights so that all vertices have a total weight set to 1
  32556. */
  32557. Mesh.prototype.cleanMatrixWeights = function () {
  32558. var epsilon = 1e-3;
  32559. var noInfluenceBoneIndex = 0.0;
  32560. if (this.skeleton) {
  32561. noInfluenceBoneIndex = this.skeleton.bones.length;
  32562. }
  32563. else {
  32564. return;
  32565. }
  32566. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32567. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32568. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32569. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32570. var influencers = this.numBoneInfluencers;
  32571. var size = matricesWeights.length;
  32572. for (var i = 0; i < size; i += 4) {
  32573. var weight = 0.0;
  32574. var firstZeroWeight = -1;
  32575. for (var j = 0; j < 4; j++) {
  32576. var w = matricesWeights[i + j];
  32577. weight += w;
  32578. if (w < epsilon && firstZeroWeight < 0) {
  32579. firstZeroWeight = j;
  32580. }
  32581. }
  32582. if (matricesWeightsExtra) {
  32583. for (var j = 0; j < 4; j++) {
  32584. var w = matricesWeightsExtra[i + j];
  32585. weight += w;
  32586. if (w < epsilon && firstZeroWeight < 0) {
  32587. firstZeroWeight = j + 4;
  32588. }
  32589. }
  32590. }
  32591. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32592. firstZeroWeight = influencers - 1;
  32593. }
  32594. if (weight > epsilon) {
  32595. var mweight = 1.0 / weight;
  32596. for (var j = 0; j < 4; j++) {
  32597. matricesWeights[i + j] *= mweight;
  32598. }
  32599. if (matricesWeightsExtra) {
  32600. for (var j = 0; j < 4; j++) {
  32601. matricesWeightsExtra[i + j] *= mweight;
  32602. }
  32603. }
  32604. }
  32605. else {
  32606. if (firstZeroWeight >= 4) {
  32607. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32608. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32609. }
  32610. else {
  32611. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32612. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32613. }
  32614. }
  32615. }
  32616. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32617. if (matricesIndicesExtra) {
  32618. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32619. }
  32620. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32621. if (matricesWeightsExtra) {
  32622. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32623. }
  32624. };
  32625. Mesh.prototype._checkDelayState = function () {
  32626. var scene = this.getScene();
  32627. if (this._geometry) {
  32628. this._geometry.load(scene);
  32629. }
  32630. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32631. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32632. this._queueLoad(scene);
  32633. }
  32634. return this;
  32635. };
  32636. Mesh.prototype._queueLoad = function (scene) {
  32637. var _this = this;
  32638. scene._addPendingData(this);
  32639. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32640. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32641. if (data instanceof ArrayBuffer) {
  32642. _this._delayLoadingFunction(data, _this);
  32643. }
  32644. else {
  32645. _this._delayLoadingFunction(JSON.parse(data), _this);
  32646. }
  32647. _this.instances.forEach(function (instance) {
  32648. instance._syncSubMeshes();
  32649. });
  32650. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32651. scene._removePendingData(_this);
  32652. }, function () { }, scene.database, getBinaryData);
  32653. return this;
  32654. };
  32655. /**
  32656. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32657. */
  32658. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32659. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32660. return false;
  32661. }
  32662. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32663. return false;
  32664. }
  32665. this._checkDelayState();
  32666. return true;
  32667. };
  32668. /**
  32669. * Sets the mesh material by the material or multiMaterial `id` property.
  32670. * The material `id` is a string identifying the material or the multiMaterial.
  32671. * This method returns the Mesh.
  32672. */
  32673. Mesh.prototype.setMaterialByID = function (id) {
  32674. var materials = this.getScene().materials;
  32675. var index;
  32676. for (index = materials.length - 1; index > -1; index--) {
  32677. if (materials[index].id === id) {
  32678. this.material = materials[index];
  32679. return this;
  32680. }
  32681. }
  32682. // Multi
  32683. var multiMaterials = this.getScene().multiMaterials;
  32684. for (index = multiMaterials.length - 1; index > -1; index--) {
  32685. if (multiMaterials[index].id === id) {
  32686. this.material = multiMaterials[index];
  32687. return this;
  32688. }
  32689. }
  32690. return this;
  32691. };
  32692. /**
  32693. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32694. */
  32695. Mesh.prototype.getAnimatables = function () {
  32696. var results = new Array();
  32697. if (this.material) {
  32698. results.push(this.material);
  32699. }
  32700. if (this.skeleton) {
  32701. results.push(this.skeleton);
  32702. }
  32703. return results;
  32704. };
  32705. /**
  32706. * Modifies the mesh geometry according to the passed transformation matrix.
  32707. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32708. * The mesh normals are modified accordingly the same transformation.
  32709. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32710. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32711. * Returns the Mesh.
  32712. */
  32713. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32714. // Position
  32715. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32716. return this;
  32717. }
  32718. var submeshes = this.subMeshes.splice(0);
  32719. this._resetPointsArrayCache();
  32720. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32721. var temp = new Array();
  32722. var index;
  32723. for (index = 0; index < data.length; index += 3) {
  32724. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32725. }
  32726. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32727. // Normals
  32728. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32729. return this;
  32730. }
  32731. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32732. temp = [];
  32733. for (index = 0; index < data.length; index += 3) {
  32734. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32735. }
  32736. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32737. // flip faces?
  32738. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32739. this.flipFaces();
  32740. }
  32741. // Restore submeshes
  32742. this.releaseSubMeshes();
  32743. this.subMeshes = submeshes;
  32744. return this;
  32745. };
  32746. /**
  32747. * Modifies the mesh geometry according to its own current World Matrix.
  32748. * The mesh World Matrix is then reset.
  32749. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32750. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32751. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32752. * Returns the Mesh.
  32753. */
  32754. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32755. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32756. this.scaling.copyFromFloats(1, 1, 1);
  32757. this.position.copyFromFloats(0, 0, 0);
  32758. this.rotation.copyFromFloats(0, 0, 0);
  32759. //only if quaternion is already set
  32760. if (this.rotationQuaternion) {
  32761. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32762. }
  32763. this._worldMatrix = BABYLON.Matrix.Identity();
  32764. return this;
  32765. };
  32766. Object.defineProperty(Mesh.prototype, "_positions", {
  32767. // Cache
  32768. get: function () {
  32769. if (this._geometry) {
  32770. return this._geometry._positions;
  32771. }
  32772. return null;
  32773. },
  32774. enumerable: true,
  32775. configurable: true
  32776. });
  32777. Mesh.prototype._resetPointsArrayCache = function () {
  32778. if (this._geometry) {
  32779. this._geometry._resetPointsArrayCache();
  32780. }
  32781. return this;
  32782. };
  32783. Mesh.prototype._generatePointsArray = function () {
  32784. if (this._geometry) {
  32785. return this._geometry._generatePointsArray();
  32786. }
  32787. return false;
  32788. };
  32789. /**
  32790. * Returns a new Mesh object generated from the current mesh properties.
  32791. * This method must not get confused with createInstance().
  32792. * The parameter `name` is a string, the name given to the new mesh.
  32793. * The optional parameter `newParent` can be any Node object (default `null`).
  32794. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32795. * 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.
  32796. */
  32797. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32798. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32799. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32800. };
  32801. /**
  32802. * Releases resources associated with this mesh.
  32803. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32804. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32805. */
  32806. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32807. var _this = this;
  32808. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32809. this.morphTargetManager = null;
  32810. if (this._geometry) {
  32811. this._geometry.releaseForMesh(this, true);
  32812. }
  32813. // Sources
  32814. var meshes = this.getScene().meshes;
  32815. meshes.forEach(function (abstractMesh) {
  32816. var mesh = abstractMesh;
  32817. if (mesh._source && mesh._source === _this) {
  32818. mesh._source = null;
  32819. }
  32820. });
  32821. this._source = null;
  32822. // Instances
  32823. if (this._instancesBuffer) {
  32824. this._instancesBuffer.dispose();
  32825. this._instancesBuffer = null;
  32826. }
  32827. while (this.instances.length) {
  32828. this.instances[0].dispose();
  32829. }
  32830. // Effect layers.
  32831. var effectLayers = this.getScene().effectLayers;
  32832. for (var i = 0; i < effectLayers.length; i++) {
  32833. var effectLayer = effectLayers[i];
  32834. if (effectLayer) {
  32835. effectLayer._disposeMesh(this);
  32836. }
  32837. }
  32838. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32839. };
  32840. /**
  32841. * Modifies the mesh geometry according to a displacement map.
  32842. * 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.
  32843. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32844. * This method returns nothing.
  32845. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32846. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32847. * 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.
  32848. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32849. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32850. *
  32851. * Returns the Mesh.
  32852. */
  32853. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32854. var _this = this;
  32855. var scene = this.getScene();
  32856. var onload = function (img) {
  32857. // Getting height map data
  32858. var canvas = document.createElement("canvas");
  32859. var context = canvas.getContext("2d");
  32860. var heightMapWidth = img.width;
  32861. var heightMapHeight = img.height;
  32862. canvas.width = heightMapWidth;
  32863. canvas.height = heightMapHeight;
  32864. context.drawImage(img, 0, 0);
  32865. // Create VertexData from map data
  32866. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32867. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32868. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32869. //execute success callback, if set
  32870. if (onSuccess) {
  32871. onSuccess(_this);
  32872. }
  32873. };
  32874. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32875. return this;
  32876. };
  32877. /**
  32878. * Modifies the mesh geometry according to a displacementMap buffer.
  32879. * 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.
  32880. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32881. * This method returns nothing.
  32882. * 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.
  32883. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32884. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32885. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32886. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32887. *
  32888. * Returns the Mesh.
  32889. */
  32890. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32891. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32892. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32893. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32894. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32895. return this;
  32896. }
  32897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32898. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32899. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32900. var position = BABYLON.Vector3.Zero();
  32901. var normal = BABYLON.Vector3.Zero();
  32902. var uv = BABYLON.Vector2.Zero();
  32903. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32904. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32905. for (var index = 0; index < positions.length; index += 3) {
  32906. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32907. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32908. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32909. // Compute height
  32910. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32911. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32912. var pos = (u + v * heightMapWidth) * 4;
  32913. var r = buffer[pos] / 255.0;
  32914. var g = buffer[pos + 1] / 255.0;
  32915. var b = buffer[pos + 2] / 255.0;
  32916. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32917. normal.normalize();
  32918. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32919. position = position.add(normal);
  32920. position.toArray(positions, index);
  32921. }
  32922. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32923. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32924. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32925. return this;
  32926. };
  32927. /**
  32928. * Modify the mesh to get a flat shading rendering.
  32929. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32930. * This method returns the Mesh.
  32931. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32932. */
  32933. Mesh.prototype.convertToFlatShadedMesh = function () {
  32934. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32935. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32936. var kinds = this.getVerticesDataKinds();
  32937. var vbs = {};
  32938. var data = {};
  32939. var newdata = {};
  32940. var updatableNormals = false;
  32941. var kindIndex;
  32942. var kind;
  32943. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32944. kind = kinds[kindIndex];
  32945. var vertexBuffer = this.getVertexBuffer(kind);
  32946. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32947. updatableNormals = vertexBuffer.isUpdatable();
  32948. kinds.splice(kindIndex, 1);
  32949. kindIndex--;
  32950. continue;
  32951. }
  32952. vbs[kind] = vertexBuffer;
  32953. data[kind] = vbs[kind].getData();
  32954. newdata[kind] = [];
  32955. }
  32956. // Save previous submeshes
  32957. var previousSubmeshes = this.subMeshes.slice(0);
  32958. var indices = this.getIndices();
  32959. var totalIndices = this.getTotalIndices();
  32960. // Generating unique vertices per face
  32961. var index;
  32962. for (index = 0; index < totalIndices; index++) {
  32963. var vertexIndex = indices[index];
  32964. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32965. kind = kinds[kindIndex];
  32966. var stride = vbs[kind].getStrideSize();
  32967. for (var offset = 0; offset < stride; offset++) {
  32968. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32969. }
  32970. }
  32971. }
  32972. // Updating faces & normal
  32973. var normals = [];
  32974. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32975. for (index = 0; index < totalIndices; index += 3) {
  32976. indices[index] = index;
  32977. indices[index + 1] = index + 1;
  32978. indices[index + 2] = index + 2;
  32979. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32980. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32981. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32982. var p1p2 = p1.subtract(p2);
  32983. var p3p2 = p3.subtract(p2);
  32984. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32985. // Store same normals for every vertex
  32986. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32987. normals.push(normal.x);
  32988. normals.push(normal.y);
  32989. normals.push(normal.z);
  32990. }
  32991. }
  32992. this.setIndices(indices);
  32993. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32994. // Updating vertex buffers
  32995. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32996. kind = kinds[kindIndex];
  32997. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32998. }
  32999. // Updating submeshes
  33000. this.releaseSubMeshes();
  33001. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33002. var previousOne = previousSubmeshes[submeshIndex];
  33003. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33004. }
  33005. this.synchronizeInstances();
  33006. return this;
  33007. };
  33008. /**
  33009. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33010. * In other words, more vertices, no more indices and a single bigger VBO.
  33011. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33012. * Returns the Mesh.
  33013. */
  33014. Mesh.prototype.convertToUnIndexedMesh = function () {
  33015. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33016. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33017. var kinds = this.getVerticesDataKinds();
  33018. var vbs = {};
  33019. var data = {};
  33020. var newdata = {};
  33021. var kindIndex;
  33022. var kind;
  33023. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33024. kind = kinds[kindIndex];
  33025. var vertexBuffer = this.getVertexBuffer(kind);
  33026. vbs[kind] = vertexBuffer;
  33027. data[kind] = vbs[kind].getData();
  33028. newdata[kind] = [];
  33029. }
  33030. // Save previous submeshes
  33031. var previousSubmeshes = this.subMeshes.slice(0);
  33032. var indices = this.getIndices();
  33033. var totalIndices = this.getTotalIndices();
  33034. // Generating unique vertices per face
  33035. var index;
  33036. for (index = 0; index < totalIndices; index++) {
  33037. var vertexIndex = indices[index];
  33038. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33039. kind = kinds[kindIndex];
  33040. var stride = vbs[kind].getStrideSize();
  33041. for (var offset = 0; offset < stride; offset++) {
  33042. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33043. }
  33044. }
  33045. }
  33046. // Updating indices
  33047. for (index = 0; index < totalIndices; index += 3) {
  33048. indices[index] = index;
  33049. indices[index + 1] = index + 1;
  33050. indices[index + 2] = index + 2;
  33051. }
  33052. this.setIndices(indices);
  33053. // Updating vertex buffers
  33054. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33055. kind = kinds[kindIndex];
  33056. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33057. }
  33058. // Updating submeshes
  33059. this.releaseSubMeshes();
  33060. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33061. var previousOne = previousSubmeshes[submeshIndex];
  33062. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33063. }
  33064. this._unIndexed = true;
  33065. this.synchronizeInstances();
  33066. return this;
  33067. };
  33068. /**
  33069. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33070. * This method returns the Mesh.
  33071. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33072. */
  33073. Mesh.prototype.flipFaces = function (flipNormals) {
  33074. if (flipNormals === void 0) { flipNormals = false; }
  33075. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33076. var i;
  33077. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33078. for (i = 0; i < vertex_data.normals.length; i++) {
  33079. vertex_data.normals[i] *= -1;
  33080. }
  33081. }
  33082. if (vertex_data.indices) {
  33083. var temp;
  33084. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33085. // reassign indices
  33086. temp = vertex_data.indices[i + 1];
  33087. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33088. vertex_data.indices[i + 2] = temp;
  33089. }
  33090. }
  33091. vertex_data.applyToMesh(this);
  33092. return this;
  33093. };
  33094. // Instances
  33095. /**
  33096. * Creates a new InstancedMesh object from the mesh model.
  33097. * An instance shares the same properties and the same material than its model.
  33098. * Only these properties of each instance can then be set individually :
  33099. * - position
  33100. * - rotation
  33101. * - rotationQuaternion
  33102. * - setPivotMatrix
  33103. * - scaling
  33104. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33105. * Warning : this method is not supported for Line mesh and LineSystem
  33106. */
  33107. Mesh.prototype.createInstance = function (name) {
  33108. return new BABYLON.InstancedMesh(name, this);
  33109. };
  33110. /**
  33111. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33112. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33113. * This method returns the Mesh.
  33114. */
  33115. Mesh.prototype.synchronizeInstances = function () {
  33116. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33117. var instance = this.instances[instanceIndex];
  33118. instance._syncSubMeshes();
  33119. }
  33120. return this;
  33121. };
  33122. /**
  33123. * Simplify the mesh according to the given array of settings.
  33124. * Function will return immediately and will simplify async. It returns the Mesh.
  33125. * @param settings a collection of simplification settings.
  33126. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33127. * @param type the type of simplification to run.
  33128. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33129. */
  33130. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33131. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33132. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33133. this.getScene().simplificationQueue.addTask({
  33134. settings: settings,
  33135. parallelProcessing: parallelProcessing,
  33136. mesh: this,
  33137. simplificationType: simplificationType,
  33138. successCallback: successCallback
  33139. });
  33140. return this;
  33141. };
  33142. /**
  33143. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33144. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33145. * This should be used together with the simplification to avoid disappearing triangles.
  33146. * Returns the Mesh.
  33147. * @param successCallback an optional success callback to be called after the optimization finished.
  33148. */
  33149. Mesh.prototype.optimizeIndices = function (successCallback) {
  33150. var _this = this;
  33151. var indices = this.getIndices();
  33152. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33153. if (!positions || !indices) {
  33154. return this;
  33155. }
  33156. var vectorPositions = new Array();
  33157. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33158. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33159. }
  33160. var dupes = new Array();
  33161. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33162. var realPos = vectorPositions.length - 1 - iteration;
  33163. var testedPosition = vectorPositions[realPos];
  33164. for (var j = 0; j < realPos; ++j) {
  33165. var againstPosition = vectorPositions[j];
  33166. if (testedPosition.equals(againstPosition)) {
  33167. dupes[realPos] = j;
  33168. break;
  33169. }
  33170. }
  33171. }, function () {
  33172. for (var i = 0; i < indices.length; ++i) {
  33173. indices[i] = dupes[indices[i]] || indices[i];
  33174. }
  33175. //indices are now reordered
  33176. var originalSubMeshes = _this.subMeshes.slice(0);
  33177. _this.setIndices(indices);
  33178. _this.subMeshes = originalSubMeshes;
  33179. if (successCallback) {
  33180. successCallback(_this);
  33181. }
  33182. });
  33183. return this;
  33184. };
  33185. Mesh.prototype.serialize = function (serializationObject) {
  33186. serializationObject.name = this.name;
  33187. serializationObject.id = this.id;
  33188. serializationObject.type = this.getClassName();
  33189. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33190. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33191. }
  33192. serializationObject.position = this.position.asArray();
  33193. if (this.rotationQuaternion) {
  33194. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33195. }
  33196. else if (this.rotation) {
  33197. serializationObject.rotation = this.rotation.asArray();
  33198. }
  33199. serializationObject.scaling = this.scaling.asArray();
  33200. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33201. serializationObject.isEnabled = this.isEnabled(false);
  33202. serializationObject.isVisible = this.isVisible;
  33203. serializationObject.infiniteDistance = this.infiniteDistance;
  33204. serializationObject.pickable = this.isPickable;
  33205. serializationObject.receiveShadows = this.receiveShadows;
  33206. serializationObject.billboardMode = this.billboardMode;
  33207. serializationObject.visibility = this.visibility;
  33208. serializationObject.checkCollisions = this.checkCollisions;
  33209. serializationObject.isBlocker = this.isBlocker;
  33210. // Parent
  33211. if (this.parent) {
  33212. serializationObject.parentId = this.parent.id;
  33213. }
  33214. // Geometry
  33215. serializationObject.isUnIndexed = this.isUnIndexed;
  33216. var geometry = this._geometry;
  33217. if (geometry) {
  33218. var geometryId = geometry.id;
  33219. serializationObject.geometryId = geometryId;
  33220. // SubMeshes
  33221. serializationObject.subMeshes = [];
  33222. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33223. var subMesh = this.subMeshes[subIndex];
  33224. serializationObject.subMeshes.push({
  33225. materialIndex: subMesh.materialIndex,
  33226. verticesStart: subMesh.verticesStart,
  33227. verticesCount: subMesh.verticesCount,
  33228. indexStart: subMesh.indexStart,
  33229. indexCount: subMesh.indexCount
  33230. });
  33231. }
  33232. }
  33233. // Material
  33234. if (this.material) {
  33235. serializationObject.materialId = this.material.id;
  33236. }
  33237. else {
  33238. this.material = null;
  33239. }
  33240. // Morph targets
  33241. if (this.morphTargetManager) {
  33242. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33243. }
  33244. // Skeleton
  33245. if (this.skeleton) {
  33246. serializationObject.skeletonId = this.skeleton.id;
  33247. }
  33248. // Physics
  33249. //TODO implement correct serialization for physics impostors.
  33250. var impostor = this.getPhysicsImpostor();
  33251. if (impostor) {
  33252. serializationObject.physicsMass = impostor.getParam("mass");
  33253. serializationObject.physicsFriction = impostor.getParam("friction");
  33254. serializationObject.physicsRestitution = impostor.getParam("mass");
  33255. serializationObject.physicsImpostor = impostor.type;
  33256. }
  33257. // Metadata
  33258. if (this.metadata) {
  33259. serializationObject.metadata = this.metadata;
  33260. }
  33261. // Instances
  33262. serializationObject.instances = [];
  33263. for (var index = 0; index < this.instances.length; index++) {
  33264. var instance = this.instances[index];
  33265. var serializationInstance = {
  33266. name: instance.name,
  33267. id: instance.id,
  33268. position: instance.position.asArray(),
  33269. scaling: instance.scaling.asArray()
  33270. };
  33271. if (instance.rotationQuaternion) {
  33272. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33273. }
  33274. else if (instance.rotation) {
  33275. serializationInstance.rotation = instance.rotation.asArray();
  33276. }
  33277. serializationObject.instances.push(serializationInstance);
  33278. // Animations
  33279. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33280. serializationInstance.ranges = instance.serializeAnimationRanges();
  33281. }
  33282. //
  33283. // Animations
  33284. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33285. serializationObject.ranges = this.serializeAnimationRanges();
  33286. // Layer mask
  33287. serializationObject.layerMask = this.layerMask;
  33288. // Alpha
  33289. serializationObject.alphaIndex = this.alphaIndex;
  33290. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33291. // Overlay
  33292. serializationObject.overlayAlpha = this.overlayAlpha;
  33293. serializationObject.overlayColor = this.overlayColor.asArray();
  33294. serializationObject.renderOverlay = this.renderOverlay;
  33295. // Fog
  33296. serializationObject.applyFog = this.applyFog;
  33297. // Action Manager
  33298. if (this.actionManager) {
  33299. serializationObject.actions = this.actionManager.serialize(this.name);
  33300. }
  33301. };
  33302. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33303. if (!this.geometry) {
  33304. return;
  33305. }
  33306. this._markSubMeshesAsAttributesDirty();
  33307. var morphTargetManager = this._morphTargetManager;
  33308. if (morphTargetManager && morphTargetManager.vertexCount) {
  33309. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33310. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33311. this.morphTargetManager = null;
  33312. return;
  33313. }
  33314. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33315. var morphTarget = morphTargetManager.getActiveTarget(index);
  33316. var positions = morphTarget.getPositions();
  33317. if (!positions) {
  33318. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33319. return;
  33320. }
  33321. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33322. var normals = morphTarget.getNormals();
  33323. if (normals) {
  33324. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33325. }
  33326. var tangents = morphTarget.getTangents();
  33327. if (tangents) {
  33328. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33329. }
  33330. }
  33331. }
  33332. else {
  33333. var index = 0;
  33334. // Positions
  33335. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33336. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33337. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33338. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33339. }
  33340. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33341. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33342. }
  33343. index++;
  33344. }
  33345. }
  33346. };
  33347. // Statics
  33348. /**
  33349. * Returns a new Mesh object parsed from the source provided.
  33350. * The parameter `parsedMesh` is the source.
  33351. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33352. */
  33353. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33354. var mesh;
  33355. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33356. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33357. }
  33358. else {
  33359. mesh = new Mesh(parsedMesh.name, scene);
  33360. }
  33361. mesh.id = parsedMesh.id;
  33362. if (BABYLON.Tags) {
  33363. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33364. }
  33365. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33366. if (parsedMesh.metadata !== undefined) {
  33367. mesh.metadata = parsedMesh.metadata;
  33368. }
  33369. if (parsedMesh.rotationQuaternion) {
  33370. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33371. }
  33372. else if (parsedMesh.rotation) {
  33373. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33374. }
  33375. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33376. if (parsedMesh.localMatrix) {
  33377. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33378. }
  33379. else if (parsedMesh.pivotMatrix) {
  33380. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33381. }
  33382. mesh.setEnabled(parsedMesh.isEnabled);
  33383. mesh.isVisible = parsedMesh.isVisible;
  33384. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33385. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33386. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33387. if (parsedMesh.applyFog !== undefined) {
  33388. mesh.applyFog = parsedMesh.applyFog;
  33389. }
  33390. if (parsedMesh.pickable !== undefined) {
  33391. mesh.isPickable = parsedMesh.pickable;
  33392. }
  33393. if (parsedMesh.alphaIndex !== undefined) {
  33394. mesh.alphaIndex = parsedMesh.alphaIndex;
  33395. }
  33396. mesh.receiveShadows = parsedMesh.receiveShadows;
  33397. mesh.billboardMode = parsedMesh.billboardMode;
  33398. if (parsedMesh.visibility !== undefined) {
  33399. mesh.visibility = parsedMesh.visibility;
  33400. }
  33401. mesh.checkCollisions = parsedMesh.checkCollisions;
  33402. if (parsedMesh.isBlocker !== undefined) {
  33403. mesh.isBlocker = parsedMesh.isBlocker;
  33404. }
  33405. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33406. // freezeWorldMatrix
  33407. if (parsedMesh.freezeWorldMatrix) {
  33408. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33409. }
  33410. // Parent
  33411. if (parsedMesh.parentId) {
  33412. mesh._waitingParentId = parsedMesh.parentId;
  33413. }
  33414. // Actions
  33415. if (parsedMesh.actions !== undefined) {
  33416. mesh._waitingActions = parsedMesh.actions;
  33417. }
  33418. // Overlay
  33419. if (parsedMesh.overlayAlpha !== undefined) {
  33420. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33421. }
  33422. if (parsedMesh.overlayColor !== undefined) {
  33423. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33424. }
  33425. if (parsedMesh.renderOverlay !== undefined) {
  33426. mesh.renderOverlay = parsedMesh.renderOverlay;
  33427. }
  33428. // Geometry
  33429. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33430. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33431. if (parsedMesh.delayLoadingFile) {
  33432. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33433. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33434. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33435. if (parsedMesh._binaryInfo) {
  33436. mesh._binaryInfo = parsedMesh._binaryInfo;
  33437. }
  33438. mesh._delayInfo = [];
  33439. if (parsedMesh.hasUVs) {
  33440. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33441. }
  33442. if (parsedMesh.hasUVs2) {
  33443. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33444. }
  33445. if (parsedMesh.hasUVs3) {
  33446. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33447. }
  33448. if (parsedMesh.hasUVs4) {
  33449. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33450. }
  33451. if (parsedMesh.hasUVs5) {
  33452. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33453. }
  33454. if (parsedMesh.hasUVs6) {
  33455. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33456. }
  33457. if (parsedMesh.hasColors) {
  33458. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33459. }
  33460. if (parsedMesh.hasMatricesIndices) {
  33461. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33462. }
  33463. if (parsedMesh.hasMatricesWeights) {
  33464. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33465. }
  33466. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33467. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33468. mesh._checkDelayState();
  33469. }
  33470. }
  33471. else {
  33472. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33473. }
  33474. // Material
  33475. if (parsedMesh.materialId) {
  33476. mesh.setMaterialByID(parsedMesh.materialId);
  33477. }
  33478. else {
  33479. mesh.material = null;
  33480. }
  33481. // Morph targets
  33482. if (parsedMesh.morphTargetManagerId > -1) {
  33483. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33484. }
  33485. // Skeleton
  33486. if (parsedMesh.skeletonId > -1) {
  33487. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33488. if (parsedMesh.numBoneInfluencers) {
  33489. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33490. }
  33491. }
  33492. // Animations
  33493. if (parsedMesh.animations) {
  33494. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33495. var parsedAnimation = parsedMesh.animations[animationIndex];
  33496. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33497. }
  33498. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33499. }
  33500. if (parsedMesh.autoAnimate) {
  33501. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33502. }
  33503. // Layer Mask
  33504. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33505. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33506. }
  33507. else {
  33508. mesh.layerMask = 0x0FFFFFFF;
  33509. }
  33510. // Physics
  33511. if (parsedMesh.physicsImpostor) {
  33512. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33513. mass: parsedMesh.physicsMass,
  33514. friction: parsedMesh.physicsFriction,
  33515. restitution: parsedMesh.physicsRestitution
  33516. }, scene);
  33517. }
  33518. // Instances
  33519. if (parsedMesh.instances) {
  33520. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33521. var parsedInstance = parsedMesh.instances[index];
  33522. var instance = mesh.createInstance(parsedInstance.name);
  33523. if (parsedInstance.id) {
  33524. instance.id = parsedInstance.id;
  33525. }
  33526. if (BABYLON.Tags) {
  33527. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33528. }
  33529. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33530. if (parsedInstance.parentId) {
  33531. instance._waitingParentId = parsedInstance.parentId;
  33532. }
  33533. if (parsedInstance.rotationQuaternion) {
  33534. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33535. }
  33536. else if (parsedInstance.rotation) {
  33537. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33538. }
  33539. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33540. instance.checkCollisions = mesh.checkCollisions;
  33541. if (parsedMesh.animations) {
  33542. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33543. parsedAnimation = parsedMesh.animations[animationIndex];
  33544. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33545. }
  33546. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33547. }
  33548. }
  33549. }
  33550. return mesh;
  33551. };
  33552. /**
  33553. * Creates a ribbon mesh.
  33554. * Please consider using the same method from the MeshBuilder class instead.
  33555. * 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.
  33556. *
  33557. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33558. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33559. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33560. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33561. * 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.
  33562. * 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.
  33563. * 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
  33564. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33565. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33567. */
  33568. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33569. if (closeArray === void 0) { closeArray = false; }
  33570. if (updatable === void 0) { updatable = false; }
  33571. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33572. pathArray: pathArray,
  33573. closeArray: closeArray,
  33574. closePath: closePath,
  33575. offset: offset,
  33576. updatable: updatable,
  33577. sideOrientation: sideOrientation,
  33578. instance: instance
  33579. }, scene);
  33580. };
  33581. /**
  33582. * Creates a plane polygonal mesh. By default, this is a disc.
  33583. * Please consider using the same method from the MeshBuilder class instead.
  33584. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33585. * 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.
  33586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33587. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33589. */
  33590. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33591. if (scene === void 0) { scene = null; }
  33592. var options = {
  33593. radius: radius,
  33594. tessellation: tessellation,
  33595. sideOrientation: sideOrientation,
  33596. updatable: updatable
  33597. };
  33598. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33599. };
  33600. /**
  33601. * Creates a box mesh.
  33602. * Please consider using the same method from the MeshBuilder class instead.
  33603. * The parameter `size` sets the size (float) of each box side (default 1).
  33604. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33605. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33606. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33607. */
  33608. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33609. if (scene === void 0) { scene = null; }
  33610. var options = {
  33611. size: size,
  33612. sideOrientation: sideOrientation,
  33613. updatable: updatable
  33614. };
  33615. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33616. };
  33617. /**
  33618. * Creates a sphere mesh.
  33619. * Please consider using the same method from the MeshBuilder class instead.
  33620. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33621. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33623. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33625. */
  33626. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33627. var options = {
  33628. segments: segments,
  33629. diameterX: diameter,
  33630. diameterY: diameter,
  33631. diameterZ: diameter,
  33632. sideOrientation: sideOrientation,
  33633. updatable: updatable
  33634. };
  33635. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33636. };
  33637. /**
  33638. * Creates a cylinder or a cone mesh.
  33639. * Please consider using the same method from the MeshBuilder class instead.
  33640. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33641. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33642. * 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.
  33643. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33644. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33646. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33648. */
  33649. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33650. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33651. if (scene !== undefined) {
  33652. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33653. updatable = scene;
  33654. }
  33655. scene = subdivisions;
  33656. subdivisions = 1;
  33657. }
  33658. var options = {
  33659. height: height,
  33660. diameterTop: diameterTop,
  33661. diameterBottom: diameterBottom,
  33662. tessellation: tessellation,
  33663. subdivisions: subdivisions,
  33664. sideOrientation: sideOrientation,
  33665. updatable: updatable
  33666. };
  33667. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33668. };
  33669. // Torus (Code from SharpDX.org)
  33670. /**
  33671. * Creates a torus mesh.
  33672. * Please consider using the same method from the MeshBuilder class instead.
  33673. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33674. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33675. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33677. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33679. */
  33680. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33681. var options = {
  33682. diameter: diameter,
  33683. thickness: thickness,
  33684. tessellation: tessellation,
  33685. sideOrientation: sideOrientation,
  33686. updatable: updatable
  33687. };
  33688. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33689. };
  33690. /**
  33691. * Creates a torus knot mesh.
  33692. * Please consider using the same method from the MeshBuilder class instead.
  33693. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33694. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33695. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33696. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33697. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33698. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33699. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33700. */
  33701. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33702. var options = {
  33703. radius: radius,
  33704. tube: tube,
  33705. radialSegments: radialSegments,
  33706. tubularSegments: tubularSegments,
  33707. p: p,
  33708. q: q,
  33709. sideOrientation: sideOrientation,
  33710. updatable: updatable
  33711. };
  33712. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33713. };
  33714. /**
  33715. * Creates a line mesh.
  33716. * Please consider using the same method from the MeshBuilder class instead.
  33717. * 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.
  33718. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33719. * The parameter `points` is an array successive Vector3.
  33720. * 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
  33721. * When updating an instance, remember that only point positions can change, not the number of points.
  33722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33723. */
  33724. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33725. if (scene === void 0) { scene = null; }
  33726. if (updatable === void 0) { updatable = false; }
  33727. if (instance === void 0) { instance = null; }
  33728. var options = {
  33729. points: points,
  33730. updatable: updatable,
  33731. instance: instance
  33732. };
  33733. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33734. };
  33735. /**
  33736. * Creates a dashed line mesh.
  33737. * Please consider using the same method from the MeshBuilder class instead.
  33738. * 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.
  33739. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33740. * The parameter `points` is an array successive Vector3.
  33741. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33742. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33743. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33744. * 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
  33745. * When updating an instance, remember that only point positions can change, not the number of points.
  33746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33747. */
  33748. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33749. if (scene === void 0) { scene = null; }
  33750. var options = {
  33751. points: points,
  33752. dashSize: dashSize,
  33753. gapSize: gapSize,
  33754. dashNb: dashNb,
  33755. updatable: updatable,
  33756. instance: instance
  33757. };
  33758. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33759. };
  33760. /**
  33761. * Creates a polygon mesh.
  33762. * Please consider using the same method from the MeshBuilder class instead.
  33763. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33764. * 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.
  33765. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33766. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33767. * Remember you can only change the shape positions, not their number when updating a polygon.
  33768. */
  33769. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33770. var options = {
  33771. shape: shape,
  33772. holes: holes,
  33773. updatable: updatable,
  33774. sideOrientation: sideOrientation
  33775. };
  33776. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33777. };
  33778. /**
  33779. * Creates an extruded polygon mesh, with depth in the Y direction.
  33780. * Please consider using the same method from the MeshBuilder class instead.
  33781. */
  33782. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33783. var options = {
  33784. shape: shape,
  33785. holes: holes,
  33786. depth: depth,
  33787. updatable: updatable,
  33788. sideOrientation: sideOrientation
  33789. };
  33790. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33791. };
  33792. /**
  33793. * Creates an extruded shape mesh.
  33794. * 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.
  33795. * Please consider using the same method from the MeshBuilder class instead.
  33796. *
  33797. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33798. * 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
  33799. * extruded along the Z axis.
  33800. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33801. * 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.
  33802. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33803. * 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
  33804. * 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
  33805. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33806. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33807. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33809. */
  33810. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33811. if (scene === void 0) { scene = null; }
  33812. var options = {
  33813. shape: shape,
  33814. path: path,
  33815. scale: scale,
  33816. rotation: rotation,
  33817. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33818. sideOrientation: sideOrientation,
  33819. instance: instance,
  33820. updatable: updatable
  33821. };
  33822. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33823. };
  33824. /**
  33825. * Creates an custom extruded shape mesh.
  33826. * 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.
  33827. * Please consider using the same method from the MeshBuilder class instead.
  33828. *
  33829. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33830. * 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
  33831. * extruded along the Z axis.
  33832. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33833. * 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
  33834. * and the distance of this point from the begining of the path :
  33835. * ```javascript
  33836. * var rotationFunction = function(i, distance) {
  33837. * // do things
  33838. * return rotationValue; }
  33839. * ```
  33840. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33841. * 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
  33842. * and the distance of this point from the begining of the path :
  33843. * ```javascript
  33844. * var scaleFunction = function(i, distance) {
  33845. * // do things
  33846. * return scaleValue;}
  33847. * ```
  33848. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33849. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33850. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33851. * 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
  33852. * 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
  33853. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33855. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33857. */
  33858. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33859. var options = {
  33860. shape: shape,
  33861. path: path,
  33862. scaleFunction: scaleFunction,
  33863. rotationFunction: rotationFunction,
  33864. ribbonCloseArray: ribbonCloseArray,
  33865. ribbonClosePath: ribbonClosePath,
  33866. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33867. sideOrientation: sideOrientation,
  33868. instance: instance,
  33869. updatable: updatable
  33870. };
  33871. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33872. };
  33873. /**
  33874. * Creates lathe mesh.
  33875. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33876. * Please consider using the same method from the MeshBuilder class instead.
  33877. * 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
  33878. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33879. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33880. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33882. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33884. */
  33885. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33886. var options = {
  33887. shape: shape,
  33888. radius: radius,
  33889. tessellation: tessellation,
  33890. sideOrientation: sideOrientation,
  33891. updatable: updatable
  33892. };
  33893. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33894. };
  33895. /**
  33896. * Creates a plane mesh.
  33897. * Please consider using the same method from the MeshBuilder class instead.
  33898. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33900. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33902. */
  33903. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33904. var options = {
  33905. size: size,
  33906. width: size,
  33907. height: size,
  33908. sideOrientation: sideOrientation,
  33909. updatable: updatable
  33910. };
  33911. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33912. };
  33913. /**
  33914. * Creates a ground mesh.
  33915. * Please consider using the same method from the MeshBuilder class instead.
  33916. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33917. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33919. */
  33920. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33921. var options = {
  33922. width: width,
  33923. height: height,
  33924. subdivisions: subdivisions,
  33925. updatable: updatable
  33926. };
  33927. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33928. };
  33929. /**
  33930. * Creates a tiled ground mesh.
  33931. * Please consider using the same method from the MeshBuilder class instead.
  33932. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33933. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33934. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33935. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33936. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33937. * numbers of subdivisions on the ground width and height of each tile.
  33938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33939. */
  33940. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33941. var options = {
  33942. xmin: xmin,
  33943. zmin: zmin,
  33944. xmax: xmax,
  33945. zmax: zmax,
  33946. subdivisions: subdivisions,
  33947. precision: precision,
  33948. updatable: updatable
  33949. };
  33950. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33951. };
  33952. /**
  33953. * Creates a ground mesh from a height map.
  33954. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33955. * Please consider using the same method from the MeshBuilder class instead.
  33956. * The parameter `url` sets the URL of the height map image resource.
  33957. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33958. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33959. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33960. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33961. * 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).
  33962. * This function is passed the newly built mesh :
  33963. * ```javascript
  33964. * function(mesh) { // do things
  33965. * return; }
  33966. * ```
  33967. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33968. */
  33969. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33970. var options = {
  33971. width: width,
  33972. height: height,
  33973. subdivisions: subdivisions,
  33974. minHeight: minHeight,
  33975. maxHeight: maxHeight,
  33976. updatable: updatable,
  33977. onReady: onReady
  33978. };
  33979. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33980. };
  33981. /**
  33982. * Creates a tube mesh.
  33983. * 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.
  33984. * Please consider using the same method from the MeshBuilder class instead.
  33985. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33986. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33987. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33988. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33989. * 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.
  33990. * It must return a radius value (positive float) :
  33991. * ```javascript
  33992. * var radiusFunction = function(i, distance) {
  33993. * // do things
  33994. * return radius; }
  33995. * ```
  33996. * 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
  33997. * 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
  33998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33999. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34001. */
  34002. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34003. var options = {
  34004. path: path,
  34005. radius: radius,
  34006. tessellation: tessellation,
  34007. radiusFunction: radiusFunction,
  34008. arc: 1,
  34009. cap: cap,
  34010. updatable: updatable,
  34011. sideOrientation: sideOrientation,
  34012. instance: instance
  34013. };
  34014. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34015. };
  34016. /**
  34017. * Creates a polyhedron mesh.
  34018. * Please consider using the same method from the MeshBuilder class instead.
  34019. * 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
  34020. * to choose the wanted type.
  34021. * The parameter `size` (positive float, default 1) sets the polygon size.
  34022. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34023. * 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`.
  34024. * 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
  34025. * 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)`).
  34026. * 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
  34027. * 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.
  34028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34029. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34031. */
  34032. Mesh.CreatePolyhedron = function (name, options, scene) {
  34033. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34034. };
  34035. /**
  34036. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34037. * Please consider using the same method from the MeshBuilder class instead.
  34038. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34039. * 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`).
  34040. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34041. * 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.
  34042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34043. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34045. */
  34046. Mesh.CreateIcoSphere = function (name, options, scene) {
  34047. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34048. };
  34049. /**
  34050. * Creates a decal mesh.
  34051. * Please consider using the same method from the MeshBuilder class instead.
  34052. * 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.
  34053. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34054. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34055. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34056. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34057. */
  34058. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34059. var options = {
  34060. position: position,
  34061. normal: normal,
  34062. size: size,
  34063. angle: angle
  34064. };
  34065. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34066. };
  34067. // Skeletons
  34068. /**
  34069. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34070. */
  34071. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34072. if (!this._sourcePositions) {
  34073. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34074. if (!source) {
  34075. return this._sourcePositions;
  34076. }
  34077. this._sourcePositions = new Float32Array(source);
  34078. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34079. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34080. }
  34081. }
  34082. return this._sourcePositions;
  34083. };
  34084. /**
  34085. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34086. */
  34087. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34088. if (!this._sourceNormals) {
  34089. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34090. if (!source) {
  34091. return this._sourceNormals;
  34092. }
  34093. this._sourceNormals = new Float32Array(source);
  34094. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34095. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34096. }
  34097. }
  34098. return this._sourceNormals;
  34099. };
  34100. /**
  34101. * Updates the vertex buffer by applying transformation from the bones.
  34102. * Returns the Mesh.
  34103. *
  34104. * @param {skeleton} skeleton to apply
  34105. */
  34106. Mesh.prototype.applySkeleton = function (skeleton) {
  34107. if (!this.geometry) {
  34108. return this;
  34109. }
  34110. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34111. return this;
  34112. }
  34113. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34114. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34115. return this;
  34116. }
  34117. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34118. return this;
  34119. }
  34120. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34121. return this;
  34122. }
  34123. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34124. return this;
  34125. }
  34126. if (!this._sourcePositions) {
  34127. var submeshes = this.subMeshes.slice();
  34128. this.setPositionsForCPUSkinning();
  34129. this.subMeshes = submeshes;
  34130. }
  34131. if (!this._sourceNormals) {
  34132. this.setNormalsForCPUSkinning();
  34133. }
  34134. // positionsData checks for not being Float32Array will only pass at most once
  34135. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34136. if (!positionsData) {
  34137. return this;
  34138. }
  34139. if (!(positionsData instanceof Float32Array)) {
  34140. positionsData = new Float32Array(positionsData);
  34141. }
  34142. // normalsData checks for not being Float32Array will only pass at most once
  34143. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34144. if (!normalsData) {
  34145. return this;
  34146. }
  34147. if (!(normalsData instanceof Float32Array)) {
  34148. normalsData = new Float32Array(normalsData);
  34149. }
  34150. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34151. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34152. if (!matricesWeightsData || !matricesIndicesData) {
  34153. return this;
  34154. }
  34155. var needExtras = this.numBoneInfluencers > 4;
  34156. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34157. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34158. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34159. var tempVector3 = BABYLON.Vector3.Zero();
  34160. var finalMatrix = new BABYLON.Matrix();
  34161. var tempMatrix = new BABYLON.Matrix();
  34162. var matWeightIdx = 0;
  34163. var inf;
  34164. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34165. var weight;
  34166. for (inf = 0; inf < 4; inf++) {
  34167. weight = matricesWeightsData[matWeightIdx + inf];
  34168. if (weight > 0) {
  34169. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34170. finalMatrix.addToSelf(tempMatrix);
  34171. }
  34172. else
  34173. break;
  34174. }
  34175. if (needExtras) {
  34176. for (inf = 0; inf < 4; inf++) {
  34177. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34178. if (weight > 0) {
  34179. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34180. finalMatrix.addToSelf(tempMatrix);
  34181. }
  34182. else
  34183. break;
  34184. }
  34185. }
  34186. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34187. tempVector3.toArray(positionsData, index);
  34188. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34189. tempVector3.toArray(normalsData, index);
  34190. finalMatrix.reset();
  34191. }
  34192. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34193. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34194. return this;
  34195. };
  34196. // Tools
  34197. /**
  34198. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34199. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34200. */
  34201. Mesh.MinMax = function (meshes) {
  34202. var minVector = null;
  34203. var maxVector = null;
  34204. meshes.forEach(function (mesh, index, array) {
  34205. var boundingInfo = mesh.getBoundingInfo();
  34206. var boundingBox = boundingInfo.boundingBox;
  34207. if (!minVector || !maxVector) {
  34208. minVector = boundingBox.minimumWorld;
  34209. maxVector = boundingBox.maximumWorld;
  34210. }
  34211. else {
  34212. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34213. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34214. }
  34215. });
  34216. if (!minVector || !maxVector) {
  34217. return {
  34218. min: BABYLON.Vector3.Zero(),
  34219. max: BABYLON.Vector3.Zero()
  34220. };
  34221. }
  34222. return {
  34223. min: minVector,
  34224. max: maxVector
  34225. };
  34226. };
  34227. /**
  34228. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34229. */
  34230. Mesh.Center = function (meshesOrMinMaxVector) {
  34231. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34232. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34233. };
  34234. /**
  34235. * Merge the array of meshes into a single mesh for performance reasons.
  34236. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34237. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34238. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34239. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34240. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34241. */
  34242. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34243. if (disposeSource === void 0) { disposeSource = true; }
  34244. var index;
  34245. if (!allow32BitsIndices) {
  34246. var totalVertices = 0;
  34247. // Counting vertices
  34248. for (index = 0; index < meshes.length; index++) {
  34249. if (meshes[index]) {
  34250. totalVertices += meshes[index].getTotalVertices();
  34251. if (totalVertices > 65536) {
  34252. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34253. return null;
  34254. }
  34255. }
  34256. }
  34257. }
  34258. // Merge
  34259. var vertexData = null;
  34260. var otherVertexData;
  34261. var indiceArray = new Array();
  34262. var source = null;
  34263. for (index = 0; index < meshes.length; index++) {
  34264. if (meshes[index]) {
  34265. meshes[index].computeWorldMatrix(true);
  34266. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34267. otherVertexData.transform(meshes[index].getWorldMatrix());
  34268. if (vertexData) {
  34269. vertexData.merge(otherVertexData);
  34270. }
  34271. else {
  34272. vertexData = otherVertexData;
  34273. source = meshes[index];
  34274. }
  34275. if (subdivideWithSubMeshes) {
  34276. indiceArray.push(meshes[index].getTotalIndices());
  34277. }
  34278. }
  34279. }
  34280. source = source;
  34281. if (!meshSubclass) {
  34282. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34283. }
  34284. vertexData.applyToMesh(meshSubclass);
  34285. // Setting properties
  34286. meshSubclass.material = source.material;
  34287. meshSubclass.checkCollisions = source.checkCollisions;
  34288. // Cleaning
  34289. if (disposeSource) {
  34290. for (index = 0; index < meshes.length; index++) {
  34291. if (meshes[index]) {
  34292. meshes[index].dispose();
  34293. }
  34294. }
  34295. }
  34296. // Subdivide
  34297. if (subdivideWithSubMeshes) {
  34298. //-- removal of global submesh
  34299. meshSubclass.releaseSubMeshes();
  34300. index = 0;
  34301. var offset = 0;
  34302. //-- apply subdivision according to index table
  34303. while (index < indiceArray.length) {
  34304. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34305. offset += indiceArray[index];
  34306. index++;
  34307. }
  34308. }
  34309. return meshSubclass;
  34310. };
  34311. // Consts
  34312. Mesh._FRONTSIDE = 0;
  34313. Mesh._BACKSIDE = 1;
  34314. Mesh._DOUBLESIDE = 2;
  34315. Mesh._DEFAULTSIDE = 0;
  34316. Mesh._NO_CAP = 0;
  34317. Mesh._CAP_START = 1;
  34318. Mesh._CAP_END = 2;
  34319. Mesh._CAP_ALL = 3;
  34320. return Mesh;
  34321. }(BABYLON.AbstractMesh));
  34322. BABYLON.Mesh = Mesh;
  34323. })(BABYLON || (BABYLON = {}));
  34324. //# sourceMappingURL=babylon.mesh.js.map
  34325. var BABYLON;
  34326. (function (BABYLON) {
  34327. var BaseSubMesh = /** @class */ (function () {
  34328. function BaseSubMesh() {
  34329. }
  34330. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34331. get: function () {
  34332. return this._materialEffect;
  34333. },
  34334. enumerable: true,
  34335. configurable: true
  34336. });
  34337. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34338. if (defines === void 0) { defines = null; }
  34339. if (this._materialEffect === effect) {
  34340. if (!effect) {
  34341. this._materialDefines = null;
  34342. }
  34343. return;
  34344. }
  34345. this._materialDefines = defines;
  34346. this._materialEffect = effect;
  34347. };
  34348. return BaseSubMesh;
  34349. }());
  34350. BABYLON.BaseSubMesh = BaseSubMesh;
  34351. var SubMesh = /** @class */ (function (_super) {
  34352. __extends(SubMesh, _super);
  34353. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34354. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34355. var _this = _super.call(this) || this;
  34356. _this.materialIndex = materialIndex;
  34357. _this.verticesStart = verticesStart;
  34358. _this.verticesCount = verticesCount;
  34359. _this.indexStart = indexStart;
  34360. _this.indexCount = indexCount;
  34361. _this._renderId = 0;
  34362. _this._mesh = mesh;
  34363. _this._renderingMesh = renderingMesh || mesh;
  34364. mesh.subMeshes.push(_this);
  34365. _this._trianglePlanes = [];
  34366. _this._id = mesh.subMeshes.length - 1;
  34367. if (createBoundingBox) {
  34368. _this.refreshBoundingInfo();
  34369. mesh.computeWorldMatrix(true);
  34370. }
  34371. return _this;
  34372. }
  34373. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34374. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34375. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34376. };
  34377. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34378. get: function () {
  34379. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34380. },
  34381. enumerable: true,
  34382. configurable: true
  34383. });
  34384. /**
  34385. * Returns the submesh BoudingInfo object.
  34386. */
  34387. SubMesh.prototype.getBoundingInfo = function () {
  34388. if (this.IsGlobal) {
  34389. return this._mesh.getBoundingInfo();
  34390. }
  34391. return this._boundingInfo;
  34392. };
  34393. /**
  34394. * Sets the submesh BoundingInfo.
  34395. * Return the SubMesh.
  34396. */
  34397. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34398. this._boundingInfo = boundingInfo;
  34399. return this;
  34400. };
  34401. /**
  34402. * Returns the mesh of the current submesh.
  34403. */
  34404. SubMesh.prototype.getMesh = function () {
  34405. return this._mesh;
  34406. };
  34407. /**
  34408. * Returns the rendering mesh of the submesh.
  34409. */
  34410. SubMesh.prototype.getRenderingMesh = function () {
  34411. return this._renderingMesh;
  34412. };
  34413. /**
  34414. * Returns the submesh material.
  34415. */
  34416. SubMesh.prototype.getMaterial = function () {
  34417. var rootMaterial = this._renderingMesh.material;
  34418. if (rootMaterial === null || rootMaterial === undefined) {
  34419. return this._mesh.getScene().defaultMaterial;
  34420. }
  34421. else if (rootMaterial.getSubMaterial) {
  34422. var multiMaterial = rootMaterial;
  34423. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34424. if (this._currentMaterial !== effectiveMaterial) {
  34425. this._currentMaterial = effectiveMaterial;
  34426. this._materialDefines = null;
  34427. }
  34428. return effectiveMaterial;
  34429. }
  34430. return rootMaterial;
  34431. };
  34432. // Methods
  34433. /**
  34434. * Sets a new updated BoundingInfo object to the submesh.
  34435. * Returns the SubMesh.
  34436. */
  34437. SubMesh.prototype.refreshBoundingInfo = function () {
  34438. this._lastColliderWorldVertices = null;
  34439. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34440. return this;
  34441. }
  34442. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34443. if (!data) {
  34444. this._boundingInfo = this._mesh.getBoundingInfo();
  34445. return this;
  34446. }
  34447. var indices = this._renderingMesh.getIndices();
  34448. var extend;
  34449. //is this the only submesh?
  34450. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34451. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34452. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34453. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34454. }
  34455. else {
  34456. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34457. }
  34458. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34459. return this;
  34460. };
  34461. SubMesh.prototype._checkCollision = function (collider) {
  34462. var boundingInfo = this.getBoundingInfo();
  34463. return boundingInfo._checkCollision(collider);
  34464. };
  34465. /**
  34466. * Updates the submesh BoundingInfo.
  34467. * Returns the Submesh.
  34468. */
  34469. SubMesh.prototype.updateBoundingInfo = function (world) {
  34470. var boundingInfo = this.getBoundingInfo();
  34471. if (!boundingInfo) {
  34472. this.refreshBoundingInfo();
  34473. boundingInfo = this.getBoundingInfo();
  34474. }
  34475. boundingInfo.update(world);
  34476. return this;
  34477. };
  34478. /**
  34479. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34480. * Boolean returned.
  34481. */
  34482. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34483. var boundingInfo = this.getBoundingInfo();
  34484. if (!boundingInfo) {
  34485. return false;
  34486. }
  34487. return boundingInfo.isInFrustum(frustumPlanes);
  34488. };
  34489. /**
  34490. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34491. * Boolean returned.
  34492. */
  34493. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34494. var boundingInfo = this.getBoundingInfo();
  34495. if (!boundingInfo) {
  34496. return false;
  34497. }
  34498. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34499. };
  34500. /**
  34501. * Renders the submesh.
  34502. * Returns it.
  34503. */
  34504. SubMesh.prototype.render = function (enableAlphaMode) {
  34505. this._renderingMesh.render(this, enableAlphaMode);
  34506. return this;
  34507. };
  34508. /**
  34509. * Returns a new Index Buffer.
  34510. * Type returned : WebGLBuffer.
  34511. */
  34512. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34513. if (!this._linesIndexBuffer) {
  34514. var linesIndices = [];
  34515. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34516. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34517. }
  34518. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34519. this.linesIndexCount = linesIndices.length;
  34520. }
  34521. return this._linesIndexBuffer;
  34522. };
  34523. /**
  34524. * True is the passed Ray intersects the submesh bounding box.
  34525. * Boolean returned.
  34526. */
  34527. SubMesh.prototype.canIntersects = function (ray) {
  34528. var boundingInfo = this.getBoundingInfo();
  34529. if (!boundingInfo) {
  34530. return false;
  34531. }
  34532. return ray.intersectsBox(boundingInfo.boundingBox);
  34533. };
  34534. /**
  34535. * Returns an object IntersectionInfo.
  34536. */
  34537. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34538. var intersectInfo = null;
  34539. var material = this.getMaterial();
  34540. if (!material) {
  34541. return null;
  34542. }
  34543. switch (material.fillMode) {
  34544. case BABYLON.Material.PointListDrawMode:
  34545. case BABYLON.Material.LineListDrawMode:
  34546. case BABYLON.Material.LineLoopDrawMode:
  34547. case BABYLON.Material.LineStripDrawMode:
  34548. case BABYLON.Material.TriangleFanDrawMode:
  34549. case BABYLON.Material.TriangleStripDrawMode:
  34550. return null;
  34551. }
  34552. // LineMesh first as it's also a Mesh...
  34553. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34554. var lineMesh = this._mesh;
  34555. // Line test
  34556. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34557. var p0 = positions[indices[index]];
  34558. var p1 = positions[indices[index + 1]];
  34559. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34560. if (length < 0) {
  34561. continue;
  34562. }
  34563. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34564. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34565. if (fastCheck) {
  34566. break;
  34567. }
  34568. }
  34569. }
  34570. }
  34571. else {
  34572. // Triangles test
  34573. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34574. var p0 = positions[indices[index]];
  34575. var p1 = positions[indices[index + 1]];
  34576. var p2 = positions[indices[index + 2]];
  34577. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34578. if (currentIntersectInfo) {
  34579. if (currentIntersectInfo.distance < 0) {
  34580. continue;
  34581. }
  34582. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34583. intersectInfo = currentIntersectInfo;
  34584. intersectInfo.faceId = index / 3;
  34585. if (fastCheck) {
  34586. break;
  34587. }
  34588. }
  34589. }
  34590. }
  34591. }
  34592. return intersectInfo;
  34593. };
  34594. SubMesh.prototype._rebuild = function () {
  34595. if (this._linesIndexBuffer) {
  34596. this._linesIndexBuffer = null;
  34597. }
  34598. };
  34599. // Clone
  34600. /**
  34601. * Creates a new Submesh from the passed Mesh.
  34602. */
  34603. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34604. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34605. if (!this.IsGlobal) {
  34606. var boundingInfo = this.getBoundingInfo();
  34607. if (!boundingInfo) {
  34608. return result;
  34609. }
  34610. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34611. }
  34612. return result;
  34613. };
  34614. // Dispose
  34615. /**
  34616. * Disposes the Submesh.
  34617. * Returns nothing.
  34618. */
  34619. SubMesh.prototype.dispose = function () {
  34620. if (this._linesIndexBuffer) {
  34621. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34622. this._linesIndexBuffer = null;
  34623. }
  34624. // Remove from mesh
  34625. var index = this._mesh.subMeshes.indexOf(this);
  34626. this._mesh.subMeshes.splice(index, 1);
  34627. };
  34628. // Statics
  34629. /**
  34630. * Creates a new Submesh from the passed parameters :
  34631. * - materialIndex (integer) : the index of the main mesh material.
  34632. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34633. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34634. * - mesh (Mesh) : the main mesh to create the submesh from.
  34635. * - renderingMesh (optional Mesh) : rendering mesh.
  34636. */
  34637. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34638. var minVertexIndex = Number.MAX_VALUE;
  34639. var maxVertexIndex = -Number.MAX_VALUE;
  34640. renderingMesh = (renderingMesh || mesh);
  34641. var indices = renderingMesh.getIndices();
  34642. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34643. var vertexIndex = indices[index];
  34644. if (vertexIndex < minVertexIndex)
  34645. minVertexIndex = vertexIndex;
  34646. if (vertexIndex > maxVertexIndex)
  34647. maxVertexIndex = vertexIndex;
  34648. }
  34649. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34650. };
  34651. return SubMesh;
  34652. }(BaseSubMesh));
  34653. BABYLON.SubMesh = SubMesh;
  34654. })(BABYLON || (BABYLON = {}));
  34655. //# sourceMappingURL=babylon.subMesh.js.map
  34656. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34657. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34658. s = arguments[i];
  34659. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34660. t[p] = s[p];
  34661. }
  34662. return t;
  34663. };
  34664. var BABYLON;
  34665. (function (BABYLON) {
  34666. /**
  34667. * Manages the defines for the Material
  34668. */
  34669. var MaterialDefines = /** @class */ (function () {
  34670. function MaterialDefines() {
  34671. this._isDirty = true;
  34672. /** @hidden */
  34673. this._areLightsDirty = true;
  34674. /** @hidden */
  34675. this._areAttributesDirty = true;
  34676. /** @hidden */
  34677. this._areTexturesDirty = true;
  34678. /** @hidden */
  34679. this._areFresnelDirty = true;
  34680. /** @hidden */
  34681. this._areMiscDirty = true;
  34682. /** @hidden */
  34683. this._areImageProcessingDirty = true;
  34684. /** @hidden */
  34685. this._normals = false;
  34686. /** @hidden */
  34687. this._uvs = false;
  34688. /** @hidden */
  34689. this._needNormals = false;
  34690. /** @hidden */
  34691. this._needUVs = false;
  34692. }
  34693. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34694. /**
  34695. * Specifies if the material needs to be re-calculated
  34696. */
  34697. get: function () {
  34698. return this._isDirty;
  34699. },
  34700. enumerable: true,
  34701. configurable: true
  34702. });
  34703. /**
  34704. * Marks the material to indicate that it has been re-calculated
  34705. */
  34706. MaterialDefines.prototype.markAsProcessed = function () {
  34707. this._isDirty = false;
  34708. this._areAttributesDirty = false;
  34709. this._areTexturesDirty = false;
  34710. this._areFresnelDirty = false;
  34711. this._areLightsDirty = false;
  34712. this._areMiscDirty = false;
  34713. this._areImageProcessingDirty = false;
  34714. };
  34715. /**
  34716. * Marks the material to indicate that it needs to be re-calculated
  34717. */
  34718. MaterialDefines.prototype.markAsUnprocessed = function () {
  34719. this._isDirty = true;
  34720. };
  34721. /**
  34722. * Marks the material to indicate all of its defines need to be re-calculated
  34723. */
  34724. MaterialDefines.prototype.markAllAsDirty = function () {
  34725. this._areTexturesDirty = true;
  34726. this._areAttributesDirty = true;
  34727. this._areLightsDirty = true;
  34728. this._areFresnelDirty = true;
  34729. this._areMiscDirty = true;
  34730. this._areImageProcessingDirty = true;
  34731. this._isDirty = true;
  34732. };
  34733. /**
  34734. * Marks the material to indicate that image processing needs to be re-calculated
  34735. */
  34736. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34737. this._areImageProcessingDirty = true;
  34738. this._isDirty = true;
  34739. };
  34740. /**
  34741. * Marks the material to indicate the lights need to be re-calculated
  34742. */
  34743. MaterialDefines.prototype.markAsLightDirty = function () {
  34744. this._areLightsDirty = true;
  34745. this._isDirty = true;
  34746. };
  34747. /**
  34748. * Marks the attribute state as changed
  34749. */
  34750. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34751. this._areAttributesDirty = true;
  34752. this._isDirty = true;
  34753. };
  34754. /**
  34755. * Marks the texture state as changed
  34756. */
  34757. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34758. this._areTexturesDirty = true;
  34759. this._isDirty = true;
  34760. };
  34761. /**
  34762. * Marks the fresnel state as changed
  34763. */
  34764. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34765. this._areFresnelDirty = true;
  34766. this._isDirty = true;
  34767. };
  34768. /**
  34769. * Marks the misc state as changed
  34770. */
  34771. MaterialDefines.prototype.markAsMiscDirty = function () {
  34772. this._areMiscDirty = true;
  34773. this._isDirty = true;
  34774. };
  34775. /**
  34776. * Rebuilds the material defines
  34777. */
  34778. MaterialDefines.prototype.rebuild = function () {
  34779. if (this._keys) {
  34780. delete this._keys;
  34781. }
  34782. this._keys = [];
  34783. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34784. var key = _a[_i];
  34785. if (key[0] === "_") {
  34786. continue;
  34787. }
  34788. this._keys.push(key);
  34789. }
  34790. };
  34791. /**
  34792. * Specifies if two material defines are equal
  34793. * @param other - A material define instance to compare to
  34794. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34795. */
  34796. MaterialDefines.prototype.isEqual = function (other) {
  34797. if (this._keys.length !== other._keys.length) {
  34798. return false;
  34799. }
  34800. for (var index = 0; index < this._keys.length; index++) {
  34801. var prop = this._keys[index];
  34802. if (this[prop] !== other[prop]) {
  34803. return false;
  34804. }
  34805. }
  34806. return true;
  34807. };
  34808. /**
  34809. * Clones this instance's defines to another instance
  34810. * @param other - material defines to clone values to
  34811. */
  34812. MaterialDefines.prototype.cloneTo = function (other) {
  34813. if (this._keys.length !== other._keys.length) {
  34814. other._keys = this._keys.slice(0);
  34815. }
  34816. for (var index = 0; index < this._keys.length; index++) {
  34817. var prop = this._keys[index];
  34818. other[prop] = this[prop];
  34819. }
  34820. };
  34821. /**
  34822. * Resets the material define values
  34823. */
  34824. MaterialDefines.prototype.reset = function () {
  34825. for (var index = 0; index < this._keys.length; index++) {
  34826. var prop = this._keys[index];
  34827. var type = typeof this[prop];
  34828. switch (type) {
  34829. case "number":
  34830. this[prop] = 0;
  34831. break;
  34832. case "string":
  34833. this[prop] = "";
  34834. break;
  34835. default:
  34836. this[prop] = false;
  34837. break;
  34838. }
  34839. }
  34840. };
  34841. /**
  34842. * Converts the material define values to a string
  34843. * @returns - String of material define information
  34844. */
  34845. MaterialDefines.prototype.toString = function () {
  34846. var result = "";
  34847. for (var index = 0; index < this._keys.length; index++) {
  34848. var prop = this._keys[index];
  34849. var value = this[prop];
  34850. var type = typeof value;
  34851. switch (type) {
  34852. case "number":
  34853. case "string":
  34854. result += "#define " + prop + " " + value + "\n";
  34855. break;
  34856. default:
  34857. if (value) {
  34858. result += "#define " + prop + "\n";
  34859. }
  34860. break;
  34861. }
  34862. }
  34863. return result;
  34864. };
  34865. return MaterialDefines;
  34866. }());
  34867. BABYLON.MaterialDefines = MaterialDefines;
  34868. /**
  34869. * Base class for the main features of a material in Babylon.js
  34870. */
  34871. var Material = /** @class */ (function () {
  34872. /**
  34873. * Creates a material instance
  34874. * @param name defines the name of the material
  34875. * @param scene defines the scene to reference
  34876. * @param doNotAdd specifies if the material should be added to the scene
  34877. */
  34878. function Material(name, scene, doNotAdd) {
  34879. /**
  34880. * Specifies if the ready state should be checked on each call
  34881. */
  34882. this.checkReadyOnEveryCall = false;
  34883. /**
  34884. * Specifies if the ready state should be checked once
  34885. */
  34886. this.checkReadyOnlyOnce = false;
  34887. /**
  34888. * The state of the material
  34889. */
  34890. this.state = "";
  34891. /**
  34892. * The alpha value of the material
  34893. */
  34894. this._alpha = 1.0;
  34895. /**
  34896. * Specifies if back face culling is enabled
  34897. */
  34898. this._backFaceCulling = true;
  34899. /**
  34900. * Specifies if the material should be serialized
  34901. */
  34902. this.doNotSerialize = false;
  34903. /**
  34904. * Specifies if the effect should be stored on sub meshes
  34905. */
  34906. this.storeEffectOnSubMeshes = false;
  34907. /**
  34908. * An event triggered when the material is disposed
  34909. */
  34910. this.onDisposeObservable = new BABYLON.Observable();
  34911. /**
  34912. * An event triggered when the material is bound
  34913. */
  34914. this.onBindObservable = new BABYLON.Observable();
  34915. /**
  34916. * An event triggered when the material is unbound
  34917. */
  34918. this.onUnBindObservable = new BABYLON.Observable();
  34919. /**
  34920. * Stores the value of the alpha mode
  34921. */
  34922. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34923. /**
  34924. * Stores the state of the need depth pre-pass value
  34925. */
  34926. this._needDepthPrePass = false;
  34927. /**
  34928. * Specifies if depth writing should be disabled
  34929. */
  34930. this.disableDepthWrite = false;
  34931. /**
  34932. * Specifies if depth writing should be forced
  34933. */
  34934. this.forceDepthWrite = false;
  34935. /**
  34936. * Specifies if there should be a separate pass for culling
  34937. */
  34938. this.separateCullingPass = false;
  34939. /**
  34940. * Stores the state specifing if fog should be enabled
  34941. */
  34942. this._fogEnabled = true;
  34943. /**
  34944. * Stores the size of points
  34945. */
  34946. this.pointSize = 1.0;
  34947. /**
  34948. * Stores the z offset value
  34949. */
  34950. this.zOffset = 0;
  34951. /**
  34952. * Specifies if the material was previously ready
  34953. */
  34954. this._wasPreviouslyReady = false;
  34955. /**
  34956. * Stores the fill mode state
  34957. */
  34958. this._fillMode = Material.TriangleFillMode;
  34959. this.name = name;
  34960. this.id = name || BABYLON.Tools.RandomId();
  34961. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34962. this.uniqueId = this._scene.getUniqueId();
  34963. if (this._scene.useRightHandedSystem) {
  34964. this.sideOrientation = Material.ClockWiseSideOrientation;
  34965. }
  34966. else {
  34967. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34968. }
  34969. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34970. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34971. if (!doNotAdd) {
  34972. this._scene.materials.push(this);
  34973. }
  34974. }
  34975. Object.defineProperty(Material, "TriangleFillMode", {
  34976. /**
  34977. * Returns the triangle fill mode
  34978. */
  34979. get: function () {
  34980. return Material._TriangleFillMode;
  34981. },
  34982. enumerable: true,
  34983. configurable: true
  34984. });
  34985. Object.defineProperty(Material, "WireFrameFillMode", {
  34986. /**
  34987. * Returns the wireframe mode
  34988. */
  34989. get: function () {
  34990. return Material._WireFrameFillMode;
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. Object.defineProperty(Material, "PointFillMode", {
  34996. /**
  34997. * Returns the point fill mode
  34998. */
  34999. get: function () {
  35000. return Material._PointFillMode;
  35001. },
  35002. enumerable: true,
  35003. configurable: true
  35004. });
  35005. Object.defineProperty(Material, "PointListDrawMode", {
  35006. /**
  35007. * Returns the point list draw mode
  35008. */
  35009. get: function () {
  35010. return Material._PointListDrawMode;
  35011. },
  35012. enumerable: true,
  35013. configurable: true
  35014. });
  35015. Object.defineProperty(Material, "LineListDrawMode", {
  35016. /**
  35017. * Returns the line list draw mode
  35018. */
  35019. get: function () {
  35020. return Material._LineListDrawMode;
  35021. },
  35022. enumerable: true,
  35023. configurable: true
  35024. });
  35025. Object.defineProperty(Material, "LineLoopDrawMode", {
  35026. /**
  35027. * Returns the line loop draw mode
  35028. */
  35029. get: function () {
  35030. return Material._LineLoopDrawMode;
  35031. },
  35032. enumerable: true,
  35033. configurable: true
  35034. });
  35035. Object.defineProperty(Material, "LineStripDrawMode", {
  35036. /**
  35037. * Returns the line strip draw mode
  35038. */
  35039. get: function () {
  35040. return Material._LineStripDrawMode;
  35041. },
  35042. enumerable: true,
  35043. configurable: true
  35044. });
  35045. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35046. /**
  35047. * Returns the triangle strip draw mode
  35048. */
  35049. get: function () {
  35050. return Material._TriangleStripDrawMode;
  35051. },
  35052. enumerable: true,
  35053. configurable: true
  35054. });
  35055. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35056. /**
  35057. * Returns the triangle fan draw mode
  35058. */
  35059. get: function () {
  35060. return Material._TriangleFanDrawMode;
  35061. },
  35062. enumerable: true,
  35063. configurable: true
  35064. });
  35065. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35066. /**
  35067. * Returns the clock-wise side orientation
  35068. */
  35069. get: function () {
  35070. return Material._ClockWiseSideOrientation;
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35076. /**
  35077. * Returns the counter clock-wise side orientation
  35078. */
  35079. get: function () {
  35080. return Material._CounterClockWiseSideOrientation;
  35081. },
  35082. enumerable: true,
  35083. configurable: true
  35084. });
  35085. Object.defineProperty(Material, "TextureDirtyFlag", {
  35086. /**
  35087. * Returns the dirty texture flag value
  35088. */
  35089. get: function () {
  35090. return Material._TextureDirtyFlag;
  35091. },
  35092. enumerable: true,
  35093. configurable: true
  35094. });
  35095. Object.defineProperty(Material, "LightDirtyFlag", {
  35096. /**
  35097. * Returns the dirty light flag value
  35098. */
  35099. get: function () {
  35100. return Material._LightDirtyFlag;
  35101. },
  35102. enumerable: true,
  35103. configurable: true
  35104. });
  35105. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35106. /**
  35107. * Returns the dirty fresnel flag value
  35108. */
  35109. get: function () {
  35110. return Material._FresnelDirtyFlag;
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35116. /**
  35117. * Returns the dirty attributes flag value
  35118. */
  35119. get: function () {
  35120. return Material._AttributesDirtyFlag;
  35121. },
  35122. enumerable: true,
  35123. configurable: true
  35124. });
  35125. Object.defineProperty(Material, "MiscDirtyFlag", {
  35126. /**
  35127. * Returns the dirty misc flag value
  35128. */
  35129. get: function () {
  35130. return Material._MiscDirtyFlag;
  35131. },
  35132. enumerable: true,
  35133. configurable: true
  35134. });
  35135. Object.defineProperty(Material.prototype, "alpha", {
  35136. /**
  35137. * Gets the alpha value of the material
  35138. */
  35139. get: function () {
  35140. return this._alpha;
  35141. },
  35142. /**
  35143. * Sets the alpha value of the material
  35144. */
  35145. set: function (value) {
  35146. if (this._alpha === value) {
  35147. return;
  35148. }
  35149. this._alpha = value;
  35150. this.markAsDirty(Material.MiscDirtyFlag);
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35156. /**
  35157. * Gets the back-face culling state
  35158. */
  35159. get: function () {
  35160. return this._backFaceCulling;
  35161. },
  35162. /**
  35163. * Sets the back-face culling state
  35164. */
  35165. set: function (value) {
  35166. if (this._backFaceCulling === value) {
  35167. return;
  35168. }
  35169. this._backFaceCulling = value;
  35170. this.markAsDirty(Material.TextureDirtyFlag);
  35171. },
  35172. enumerable: true,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(Material.prototype, "onDispose", {
  35176. /**
  35177. * Called during a dispose event
  35178. */
  35179. set: function (callback) {
  35180. if (this._onDisposeObserver) {
  35181. this.onDisposeObservable.remove(this._onDisposeObserver);
  35182. }
  35183. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(Material.prototype, "onBind", {
  35189. /**
  35190. * Called during a bind event
  35191. */
  35192. set: function (callback) {
  35193. if (this._onBindObserver) {
  35194. this.onBindObservable.remove(this._onBindObserver);
  35195. }
  35196. this._onBindObserver = this.onBindObservable.add(callback);
  35197. },
  35198. enumerable: true,
  35199. configurable: true
  35200. });
  35201. Object.defineProperty(Material.prototype, "alphaMode", {
  35202. /**
  35203. * Gets the value of the alpha mode
  35204. */
  35205. get: function () {
  35206. return this._alphaMode;
  35207. },
  35208. /**
  35209. * Sets the value of the alpha mode.
  35210. *
  35211. * | Value | Type | Description |
  35212. * | --- | --- | --- |
  35213. * | 0 | ALPHA_DISABLE | |
  35214. * | 1 | ALPHA_ADD | |
  35215. * | 2 | ALPHA_COMBINE | |
  35216. * | 3 | ALPHA_SUBTRACT | |
  35217. * | 4 | ALPHA_MULTIPLY | |
  35218. * | 5 | ALPHA_MAXIMIZED | |
  35219. * | 6 | ALPHA_ONEONE | |
  35220. * | 7 | ALPHA_PREMULTIPLIED | |
  35221. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35222. * | 9 | ALPHA_INTERPOLATE | |
  35223. * | 10 | ALPHA_SCREENMODE | |
  35224. *
  35225. */
  35226. set: function (value) {
  35227. if (this._alphaMode === value) {
  35228. return;
  35229. }
  35230. this._alphaMode = value;
  35231. this.markAsDirty(Material.TextureDirtyFlag);
  35232. },
  35233. enumerable: true,
  35234. configurable: true
  35235. });
  35236. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35237. /**
  35238. * Gets the depth pre-pass value
  35239. */
  35240. get: function () {
  35241. return this._needDepthPrePass;
  35242. },
  35243. /**
  35244. * Sets the need depth pre-pass value
  35245. */
  35246. set: function (value) {
  35247. if (this._needDepthPrePass === value) {
  35248. return;
  35249. }
  35250. this._needDepthPrePass = value;
  35251. if (this._needDepthPrePass) {
  35252. this.checkReadyOnEveryCall = true;
  35253. }
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(Material.prototype, "fogEnabled", {
  35259. /**
  35260. * Gets the value of the fog enabled state
  35261. */
  35262. get: function () {
  35263. return this._fogEnabled;
  35264. },
  35265. /**
  35266. * Sets the state for enabling fog
  35267. */
  35268. set: function (value) {
  35269. if (this._fogEnabled === value) {
  35270. return;
  35271. }
  35272. this._fogEnabled = value;
  35273. this.markAsDirty(Material.MiscDirtyFlag);
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(Material.prototype, "wireframe", {
  35279. /**
  35280. * Gets a value specifying if wireframe mode is enabled
  35281. */
  35282. get: function () {
  35283. switch (this._fillMode) {
  35284. case Material.WireFrameFillMode:
  35285. case Material.LineListDrawMode:
  35286. case Material.LineLoopDrawMode:
  35287. case Material.LineStripDrawMode:
  35288. return true;
  35289. }
  35290. return this._scene.forceWireframe;
  35291. },
  35292. /**
  35293. * Sets the state of wireframe mode
  35294. */
  35295. set: function (value) {
  35296. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(Material.prototype, "pointsCloud", {
  35302. /**
  35303. * Gets the value specifying if point clouds are enabled
  35304. */
  35305. get: function () {
  35306. switch (this._fillMode) {
  35307. case Material.PointFillMode:
  35308. case Material.PointListDrawMode:
  35309. return true;
  35310. }
  35311. return this._scene.forcePointsCloud;
  35312. },
  35313. /**
  35314. * Sets the state of point cloud mode
  35315. */
  35316. set: function (value) {
  35317. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. Object.defineProperty(Material.prototype, "fillMode", {
  35323. /**
  35324. * Gets the material fill mode
  35325. */
  35326. get: function () {
  35327. return this._fillMode;
  35328. },
  35329. /**
  35330. * Sets the material fill mode
  35331. */
  35332. set: function (value) {
  35333. if (this._fillMode === value) {
  35334. return;
  35335. }
  35336. this._fillMode = value;
  35337. this.markAsDirty(Material.MiscDirtyFlag);
  35338. },
  35339. enumerable: true,
  35340. configurable: true
  35341. });
  35342. /**
  35343. * Returns a string representation of the current material
  35344. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35345. * @returns a string with material information
  35346. */
  35347. Material.prototype.toString = function (fullDetails) {
  35348. var ret = "Name: " + this.name;
  35349. if (fullDetails) {
  35350. }
  35351. return ret;
  35352. };
  35353. /**
  35354. * Gets the class name of the material
  35355. * @returns a string with the class name of the material
  35356. */
  35357. Material.prototype.getClassName = function () {
  35358. return "Material";
  35359. };
  35360. Object.defineProperty(Material.prototype, "isFrozen", {
  35361. /**
  35362. * Specifies if updates for the material been locked
  35363. */
  35364. get: function () {
  35365. return this.checkReadyOnlyOnce;
  35366. },
  35367. enumerable: true,
  35368. configurable: true
  35369. });
  35370. /**
  35371. * Locks updates for the material
  35372. */
  35373. Material.prototype.freeze = function () {
  35374. this.checkReadyOnlyOnce = true;
  35375. };
  35376. /**
  35377. * Unlocks updates for the material
  35378. */
  35379. Material.prototype.unfreeze = function () {
  35380. this.checkReadyOnlyOnce = false;
  35381. };
  35382. /**
  35383. * Specifies if the material is ready to be used
  35384. * @param mesh defines the mesh to check
  35385. * @param useInstances specifies if instances should be used
  35386. * @returns a boolean indicating if the material is ready to be used
  35387. */
  35388. Material.prototype.isReady = function (mesh, useInstances) {
  35389. return true;
  35390. };
  35391. /**
  35392. * Specifies that the submesh is ready to be used
  35393. * @param mesh defines the mesh to check
  35394. * @param subMesh defines which submesh to check
  35395. * @param useInstances specifies that instances should be used
  35396. * @returns a boolean indicating that the submesh is ready or not
  35397. */
  35398. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35399. return false;
  35400. };
  35401. /**
  35402. * Returns the material effect
  35403. * @returns the effect associated with the material
  35404. */
  35405. Material.prototype.getEffect = function () {
  35406. return this._effect;
  35407. };
  35408. /**
  35409. * Returns the current scene
  35410. * @returns a Scene
  35411. */
  35412. Material.prototype.getScene = function () {
  35413. return this._scene;
  35414. };
  35415. /**
  35416. * Specifies if the material will require alpha blending
  35417. * @returns a boolean specifying if alpha blending is needed
  35418. */
  35419. Material.prototype.needAlphaBlending = function () {
  35420. return (this.alpha < 1.0);
  35421. };
  35422. /**
  35423. * Specifies if the mesh will require alpha blending
  35424. * @param mesh defines the mesh to check
  35425. * @returns a boolean specifying if alpha blending is needed for the mesh
  35426. */
  35427. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35428. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35429. };
  35430. /**
  35431. * Specifies if this material should be rendered in alpha test mode
  35432. * @returns a boolean specifying if an alpha test is needed.
  35433. */
  35434. Material.prototype.needAlphaTesting = function () {
  35435. return false;
  35436. };
  35437. /**
  35438. * Gets the texture used for the alpha test
  35439. * @returns the texture to use for alpha testing
  35440. */
  35441. Material.prototype.getAlphaTestTexture = function () {
  35442. return null;
  35443. };
  35444. /**
  35445. * Marks the material to indicate that it needs to be re-calculated
  35446. */
  35447. Material.prototype.markDirty = function () {
  35448. this._wasPreviouslyReady = false;
  35449. };
  35450. /** @hidden */
  35451. Material.prototype._preBind = function (effect, overrideOrientation) {
  35452. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35453. var engine = this._scene.getEngine();
  35454. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35455. var reverse = orientation === Material.ClockWiseSideOrientation;
  35456. engine.enableEffect(effect ? effect : this._effect);
  35457. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35458. return reverse;
  35459. };
  35460. /**
  35461. * Binds the material to the mesh
  35462. * @param world defines the world transformation matrix
  35463. * @param mesh defines the mesh to bind the material to
  35464. */
  35465. Material.prototype.bind = function (world, mesh) {
  35466. };
  35467. /**
  35468. * Binds the submesh to the material
  35469. * @param world defines the world transformation matrix
  35470. * @param mesh defines the mesh containing the submesh
  35471. * @param subMesh defines the submesh to bind the material to
  35472. */
  35473. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35474. };
  35475. /**
  35476. * Binds the world matrix to the material
  35477. * @param world defines the world transformation matrix
  35478. */
  35479. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35480. };
  35481. /**
  35482. * Binds the scene's uniform buffer to the effect.
  35483. * @param effect defines the effect to bind to the scene uniform buffer
  35484. * @param sceneUbo defines the uniform buffer storing scene data
  35485. */
  35486. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35487. sceneUbo.bindToEffect(effect, "Scene");
  35488. };
  35489. /**
  35490. * Binds the view matrix to the effect
  35491. * @param effect defines the effect to bind the view matrix to
  35492. */
  35493. Material.prototype.bindView = function (effect) {
  35494. if (!this._useUBO) {
  35495. effect.setMatrix("view", this.getScene().getViewMatrix());
  35496. }
  35497. else {
  35498. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35499. }
  35500. };
  35501. /**
  35502. * Binds the view projection matrix to the effect
  35503. * @param effect defines the effect to bind the view projection matrix to
  35504. */
  35505. Material.prototype.bindViewProjection = function (effect) {
  35506. if (!this._useUBO) {
  35507. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35508. }
  35509. else {
  35510. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35511. }
  35512. };
  35513. /**
  35514. * Specifies if material alpha testing should be turned on for the mesh
  35515. * @param mesh defines the mesh to check
  35516. */
  35517. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35518. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35519. };
  35520. /**
  35521. * Processes to execute after binding the material to a mesh
  35522. * @param mesh defines the rendered mesh
  35523. */
  35524. Material.prototype._afterBind = function (mesh) {
  35525. this._scene._cachedMaterial = this;
  35526. if (mesh) {
  35527. this._scene._cachedVisibility = mesh.visibility;
  35528. }
  35529. else {
  35530. this._scene._cachedVisibility = 1;
  35531. }
  35532. if (mesh) {
  35533. this.onBindObservable.notifyObservers(mesh);
  35534. }
  35535. if (this.disableDepthWrite) {
  35536. var engine = this._scene.getEngine();
  35537. this._cachedDepthWriteState = engine.getDepthWrite();
  35538. engine.setDepthWrite(false);
  35539. }
  35540. };
  35541. /**
  35542. * Unbinds the material from the mesh
  35543. */
  35544. Material.prototype.unbind = function () {
  35545. this.onUnBindObservable.notifyObservers(this);
  35546. if (this.disableDepthWrite) {
  35547. var engine = this._scene.getEngine();
  35548. engine.setDepthWrite(this._cachedDepthWriteState);
  35549. }
  35550. };
  35551. /**
  35552. * Gets the active textures from the material
  35553. * @returns an array of textures
  35554. */
  35555. Material.prototype.getActiveTextures = function () {
  35556. return [];
  35557. };
  35558. /**
  35559. * Specifies if the material uses a texture
  35560. * @param texture defines the texture to check against the material
  35561. * @returns a boolean specifying if the material uses the texture
  35562. */
  35563. Material.prototype.hasTexture = function (texture) {
  35564. return false;
  35565. };
  35566. /**
  35567. * Makes a duplicate of the material, and gives it a new name
  35568. * @param name defines the new name for the duplicated material
  35569. * @returns the cloned material
  35570. */
  35571. Material.prototype.clone = function (name) {
  35572. return null;
  35573. };
  35574. /**
  35575. * Gets the meshes bound to the material
  35576. * @returns an array of meshes bound to the material
  35577. */
  35578. Material.prototype.getBindedMeshes = function () {
  35579. var result = new Array();
  35580. for (var index = 0; index < this._scene.meshes.length; index++) {
  35581. var mesh = this._scene.meshes[index];
  35582. if (mesh.material === this) {
  35583. result.push(mesh);
  35584. }
  35585. }
  35586. return result;
  35587. };
  35588. /**
  35589. * Force shader compilation
  35590. * @param mesh defines the mesh associated with this material
  35591. * @param onCompiled defines a function to execute once the material is compiled
  35592. * @param options defines the options to configure the compilation
  35593. */
  35594. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35595. var _this = this;
  35596. var localOptions = __assign({ clipPlane: false }, options);
  35597. var subMesh = new BABYLON.BaseSubMesh();
  35598. var scene = this.getScene();
  35599. var checkReady = function () {
  35600. if (!_this._scene || !_this._scene.getEngine()) {
  35601. return;
  35602. }
  35603. if (subMesh._materialDefines) {
  35604. subMesh._materialDefines._renderId = -1;
  35605. }
  35606. var clipPlaneState = scene.clipPlane;
  35607. if (localOptions.clipPlane) {
  35608. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35609. }
  35610. if (_this.storeEffectOnSubMeshes) {
  35611. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35612. if (onCompiled) {
  35613. onCompiled(_this);
  35614. }
  35615. }
  35616. else {
  35617. setTimeout(checkReady, 16);
  35618. }
  35619. }
  35620. else {
  35621. if (_this.isReady(mesh)) {
  35622. if (onCompiled) {
  35623. onCompiled(_this);
  35624. }
  35625. }
  35626. else {
  35627. setTimeout(checkReady, 16);
  35628. }
  35629. }
  35630. if (localOptions.clipPlane) {
  35631. scene.clipPlane = clipPlaneState;
  35632. }
  35633. };
  35634. checkReady();
  35635. };
  35636. /**
  35637. * Force shader compilation
  35638. * @param mesh defines the mesh that will use this material
  35639. * @param options defines additional options for compiling the shaders
  35640. * @returns a promise that resolves when the compilation completes
  35641. */
  35642. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35643. var _this = this;
  35644. return new Promise(function (resolve) {
  35645. _this.forceCompilation(mesh, function () {
  35646. resolve();
  35647. }, options);
  35648. });
  35649. };
  35650. /**
  35651. * Marks a define in the material to indicate that it needs to be re-computed
  35652. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35653. */
  35654. Material.prototype.markAsDirty = function (flag) {
  35655. if (flag & Material.TextureDirtyFlag) {
  35656. this._markAllSubMeshesAsTexturesDirty();
  35657. }
  35658. if (flag & Material.LightDirtyFlag) {
  35659. this._markAllSubMeshesAsLightsDirty();
  35660. }
  35661. if (flag & Material.FresnelDirtyFlag) {
  35662. this._markAllSubMeshesAsFresnelDirty();
  35663. }
  35664. if (flag & Material.AttributesDirtyFlag) {
  35665. this._markAllSubMeshesAsAttributesDirty();
  35666. }
  35667. if (flag & Material.MiscDirtyFlag) {
  35668. this._markAllSubMeshesAsMiscDirty();
  35669. }
  35670. this.getScene().resetCachedMaterial();
  35671. };
  35672. /**
  35673. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35674. * @param func defines a function which checks material defines against the submeshes
  35675. */
  35676. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35677. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35678. var mesh = _a[_i];
  35679. if (!mesh.subMeshes) {
  35680. continue;
  35681. }
  35682. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35683. var subMesh = _c[_b];
  35684. if (subMesh.getMaterial() !== this) {
  35685. continue;
  35686. }
  35687. if (!subMesh._materialDefines) {
  35688. continue;
  35689. }
  35690. func(subMesh._materialDefines);
  35691. }
  35692. }
  35693. };
  35694. /**
  35695. * Indicates that image processing needs to be re-calculated for all submeshes
  35696. */
  35697. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35698. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35699. };
  35700. /**
  35701. * Indicates that textures need to be re-calculated for all submeshes
  35702. */
  35703. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35704. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35705. };
  35706. /**
  35707. * Indicates that fresnel needs to be re-calculated for all submeshes
  35708. */
  35709. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35710. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35711. };
  35712. /**
  35713. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35714. */
  35715. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35716. this._markAllSubMeshesAsDirty(function (defines) {
  35717. defines.markAsFresnelDirty();
  35718. defines.markAsMiscDirty();
  35719. });
  35720. };
  35721. /**
  35722. * Indicates that lights need to be re-calculated for all submeshes
  35723. */
  35724. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35725. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35726. };
  35727. /**
  35728. * Indicates that attributes need to be re-calculated for all submeshes
  35729. */
  35730. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35731. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35732. };
  35733. /**
  35734. * Indicates that misc needs to be re-calculated for all submeshes
  35735. */
  35736. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35737. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35738. };
  35739. /**
  35740. * Indicates that textures and misc need to be re-calculated for all submeshes
  35741. */
  35742. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35743. this._markAllSubMeshesAsDirty(function (defines) {
  35744. defines.markAsTexturesDirty();
  35745. defines.markAsMiscDirty();
  35746. });
  35747. };
  35748. /**
  35749. * Disposes the material
  35750. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35751. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35752. */
  35753. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35754. // Animations
  35755. this.getScene().stopAnimation(this);
  35756. this.getScene().freeProcessedMaterials();
  35757. // Remove from scene
  35758. var index = this._scene.materials.indexOf(this);
  35759. if (index >= 0) {
  35760. this._scene.materials.splice(index, 1);
  35761. }
  35762. // Remove from meshes
  35763. for (index = 0; index < this._scene.meshes.length; index++) {
  35764. var mesh = this._scene.meshes[index];
  35765. if (mesh.material === this) {
  35766. mesh.material = null;
  35767. if (mesh.geometry) {
  35768. var geometry = (mesh.geometry);
  35769. if (this.storeEffectOnSubMeshes) {
  35770. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35771. var subMesh = _a[_i];
  35772. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35773. if (forceDisposeEffect && subMesh._materialEffect) {
  35774. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35775. }
  35776. }
  35777. }
  35778. else {
  35779. geometry._releaseVertexArrayObject(this._effect);
  35780. }
  35781. }
  35782. }
  35783. }
  35784. this._uniformBuffer.dispose();
  35785. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35786. if (forceDisposeEffect && this._effect) {
  35787. if (!this.storeEffectOnSubMeshes) {
  35788. this._scene.getEngine()._releaseEffect(this._effect);
  35789. }
  35790. this._effect = null;
  35791. }
  35792. // Callback
  35793. this.onDisposeObservable.notifyObservers(this);
  35794. this.onDisposeObservable.clear();
  35795. this.onBindObservable.clear();
  35796. this.onUnBindObservable.clear();
  35797. };
  35798. /**
  35799. * Serializes this material
  35800. * @returns the serialized material object
  35801. */
  35802. Material.prototype.serialize = function () {
  35803. return BABYLON.SerializationHelper.Serialize(this);
  35804. };
  35805. /**
  35806. * Creates a MultiMaterial from parsed MultiMaterial data.
  35807. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35808. * @param scene defines the hosting scene
  35809. * @returns a new MultiMaterial
  35810. */
  35811. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35812. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35813. multiMaterial.id = parsedMultiMaterial.id;
  35814. if (BABYLON.Tags) {
  35815. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35816. }
  35817. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35818. var subMatId = parsedMultiMaterial.materials[matIndex];
  35819. if (subMatId) {
  35820. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35821. }
  35822. else {
  35823. multiMaterial.subMaterials.push(null);
  35824. }
  35825. }
  35826. return multiMaterial;
  35827. };
  35828. /**
  35829. * Creates a material from parsed material data
  35830. * @param parsedMaterial defines parsed material data
  35831. * @param scene defines the hosting scene
  35832. * @param rootUrl defines the root URL to use to load textures
  35833. * @returns a new material
  35834. */
  35835. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35836. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35837. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35838. }
  35839. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35840. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35841. if (!BABYLON.LegacyPBRMaterial) {
  35842. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35843. return;
  35844. }
  35845. }
  35846. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35847. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35848. };
  35849. // Triangle views
  35850. Material._TriangleFillMode = 0;
  35851. Material._WireFrameFillMode = 1;
  35852. Material._PointFillMode = 2;
  35853. // Draw modes
  35854. Material._PointListDrawMode = 3;
  35855. Material._LineListDrawMode = 4;
  35856. Material._LineLoopDrawMode = 5;
  35857. Material._LineStripDrawMode = 6;
  35858. Material._TriangleStripDrawMode = 7;
  35859. Material._TriangleFanDrawMode = 8;
  35860. /**
  35861. * Stores the clock-wise side orientation
  35862. */
  35863. Material._ClockWiseSideOrientation = 0;
  35864. /**
  35865. * Stores the counter clock-wise side orientation
  35866. */
  35867. Material._CounterClockWiseSideOrientation = 1;
  35868. /**
  35869. * The dirty texture flag value
  35870. */
  35871. Material._TextureDirtyFlag = 1;
  35872. /**
  35873. * The dirty light flag value
  35874. */
  35875. Material._LightDirtyFlag = 2;
  35876. /**
  35877. * The dirty fresnel flag value
  35878. */
  35879. Material._FresnelDirtyFlag = 4;
  35880. /**
  35881. * The dirty attribute flag value
  35882. */
  35883. Material._AttributesDirtyFlag = 8;
  35884. /**
  35885. * The dirty misc flag value
  35886. */
  35887. Material._MiscDirtyFlag = 16;
  35888. __decorate([
  35889. BABYLON.serialize()
  35890. ], Material.prototype, "id", void 0);
  35891. __decorate([
  35892. BABYLON.serialize()
  35893. ], Material.prototype, "uniqueId", void 0);
  35894. __decorate([
  35895. BABYLON.serialize()
  35896. ], Material.prototype, "name", void 0);
  35897. __decorate([
  35898. BABYLON.serialize()
  35899. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35900. __decorate([
  35901. BABYLON.serialize()
  35902. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35903. __decorate([
  35904. BABYLON.serialize()
  35905. ], Material.prototype, "state", void 0);
  35906. __decorate([
  35907. BABYLON.serialize("alpha")
  35908. ], Material.prototype, "_alpha", void 0);
  35909. __decorate([
  35910. BABYLON.serialize("backFaceCulling")
  35911. ], Material.prototype, "_backFaceCulling", void 0);
  35912. __decorate([
  35913. BABYLON.serialize()
  35914. ], Material.prototype, "sideOrientation", void 0);
  35915. __decorate([
  35916. BABYLON.serialize("alphaMode")
  35917. ], Material.prototype, "_alphaMode", void 0);
  35918. __decorate([
  35919. BABYLON.serialize()
  35920. ], Material.prototype, "_needDepthPrePass", void 0);
  35921. __decorate([
  35922. BABYLON.serialize()
  35923. ], Material.prototype, "disableDepthWrite", void 0);
  35924. __decorate([
  35925. BABYLON.serialize()
  35926. ], Material.prototype, "forceDepthWrite", void 0);
  35927. __decorate([
  35928. BABYLON.serialize()
  35929. ], Material.prototype, "separateCullingPass", void 0);
  35930. __decorate([
  35931. BABYLON.serialize("fogEnabled")
  35932. ], Material.prototype, "_fogEnabled", void 0);
  35933. __decorate([
  35934. BABYLON.serialize()
  35935. ], Material.prototype, "pointSize", void 0);
  35936. __decorate([
  35937. BABYLON.serialize()
  35938. ], Material.prototype, "zOffset", void 0);
  35939. __decorate([
  35940. BABYLON.serialize()
  35941. ], Material.prototype, "wireframe", null);
  35942. __decorate([
  35943. BABYLON.serialize()
  35944. ], Material.prototype, "pointsCloud", null);
  35945. __decorate([
  35946. BABYLON.serialize()
  35947. ], Material.prototype, "fillMode", null);
  35948. return Material;
  35949. }());
  35950. BABYLON.Material = Material;
  35951. })(BABYLON || (BABYLON = {}));
  35952. //# sourceMappingURL=babylon.material.js.map
  35953. var BABYLON;
  35954. (function (BABYLON) {
  35955. var UniformBuffer = /** @class */ (function () {
  35956. /**
  35957. * Uniform buffer objects.
  35958. *
  35959. * Handles blocks of uniform on the GPU.
  35960. *
  35961. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35962. *
  35963. * For more information, please refer to :
  35964. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35965. */
  35966. function UniformBuffer(engine, data, dynamic) {
  35967. this._engine = engine;
  35968. this._noUBO = !engine.supportsUniformBuffers;
  35969. this._dynamic = dynamic;
  35970. this._data = data || [];
  35971. this._uniformLocations = {};
  35972. this._uniformSizes = {};
  35973. this._uniformLocationPointer = 0;
  35974. this._needSync = false;
  35975. if (this._noUBO) {
  35976. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35977. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35978. this.updateFloat = this._updateFloatForEffect;
  35979. this.updateFloat2 = this._updateFloat2ForEffect;
  35980. this.updateFloat3 = this._updateFloat3ForEffect;
  35981. this.updateFloat4 = this._updateFloat4ForEffect;
  35982. this.updateMatrix = this._updateMatrixForEffect;
  35983. this.updateVector3 = this._updateVector3ForEffect;
  35984. this.updateVector4 = this._updateVector4ForEffect;
  35985. this.updateColor3 = this._updateColor3ForEffect;
  35986. this.updateColor4 = this._updateColor4ForEffect;
  35987. }
  35988. else {
  35989. this._engine._uniformBuffers.push(this);
  35990. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35991. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35992. this.updateFloat = this._updateFloatForUniform;
  35993. this.updateFloat2 = this._updateFloat2ForUniform;
  35994. this.updateFloat3 = this._updateFloat3ForUniform;
  35995. this.updateFloat4 = this._updateFloat4ForUniform;
  35996. this.updateMatrix = this._updateMatrixForUniform;
  35997. this.updateVector3 = this._updateVector3ForUniform;
  35998. this.updateVector4 = this._updateVector4ForUniform;
  35999. this.updateColor3 = this._updateColor3ForUniform;
  36000. this.updateColor4 = this._updateColor4ForUniform;
  36001. }
  36002. }
  36003. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36004. // Properties
  36005. /**
  36006. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36007. * or just falling back on setUniformXXX calls.
  36008. */
  36009. get: function () {
  36010. return !this._noUBO;
  36011. },
  36012. enumerable: true,
  36013. configurable: true
  36014. });
  36015. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36016. /**
  36017. * Indicates if the WebGL underlying uniform buffer is in sync
  36018. * with the javascript cache data.
  36019. */
  36020. get: function () {
  36021. return !this._needSync;
  36022. },
  36023. enumerable: true,
  36024. configurable: true
  36025. });
  36026. /**
  36027. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36028. * Also, a dynamic UniformBuffer will disable cache verification and always
  36029. * update the underlying WebGL uniform buffer to the GPU.
  36030. */
  36031. UniformBuffer.prototype.isDynamic = function () {
  36032. return this._dynamic !== undefined;
  36033. };
  36034. /**
  36035. * The data cache on JS side.
  36036. */
  36037. UniformBuffer.prototype.getData = function () {
  36038. return this._bufferData;
  36039. };
  36040. /**
  36041. * The underlying WebGL Uniform buffer.
  36042. */
  36043. UniformBuffer.prototype.getBuffer = function () {
  36044. return this._buffer;
  36045. };
  36046. /**
  36047. * std140 layout specifies how to align data within an UBO structure.
  36048. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36049. * for specs.
  36050. */
  36051. UniformBuffer.prototype._fillAlignment = function (size) {
  36052. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36053. // and 4x4 matrices
  36054. // TODO : change if other types are used
  36055. var alignment;
  36056. if (size <= 2) {
  36057. alignment = size;
  36058. }
  36059. else {
  36060. alignment = 4;
  36061. }
  36062. if ((this._uniformLocationPointer % alignment) !== 0) {
  36063. var oldPointer = this._uniformLocationPointer;
  36064. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36065. var diff = this._uniformLocationPointer - oldPointer;
  36066. for (var i = 0; i < diff; i++) {
  36067. this._data.push(0);
  36068. }
  36069. }
  36070. };
  36071. /**
  36072. * Adds an uniform in the buffer.
  36073. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36074. * for the layout to be correct !
  36075. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36076. * @param {number|number[]} size Data size, or data directly.
  36077. */
  36078. UniformBuffer.prototype.addUniform = function (name, size) {
  36079. if (this._noUBO) {
  36080. return;
  36081. }
  36082. if (this._uniformLocations[name] !== undefined) {
  36083. // Already existing uniform
  36084. return;
  36085. }
  36086. // This function must be called in the order of the shader layout !
  36087. // size can be the size of the uniform, or data directly
  36088. var data;
  36089. if (size instanceof Array) {
  36090. data = size;
  36091. size = data.length;
  36092. }
  36093. else {
  36094. size = size;
  36095. data = [];
  36096. // Fill with zeros
  36097. for (var i = 0; i < size; i++) {
  36098. data.push(0);
  36099. }
  36100. }
  36101. this._fillAlignment(size);
  36102. this._uniformSizes[name] = size;
  36103. this._uniformLocations[name] = this._uniformLocationPointer;
  36104. this._uniformLocationPointer += size;
  36105. for (var i = 0; i < size; i++) {
  36106. this._data.push(data[i]);
  36107. }
  36108. this._needSync = true;
  36109. };
  36110. /**
  36111. * Wrapper for addUniform.
  36112. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36113. * @param {Matrix} mat A 4x4 matrix.
  36114. */
  36115. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36116. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36117. };
  36118. /**
  36119. * Wrapper for addUniform.
  36120. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36121. * @param {number} x
  36122. * @param {number} y
  36123. */
  36124. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36125. var temp = [x, y];
  36126. this.addUniform(name, temp);
  36127. };
  36128. /**
  36129. * Wrapper for addUniform.
  36130. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36131. * @param {number} x
  36132. * @param {number} y
  36133. * @param {number} z
  36134. */
  36135. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36136. var temp = [x, y, z];
  36137. this.addUniform(name, temp);
  36138. };
  36139. /**
  36140. * Wrapper for addUniform.
  36141. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36142. * @param {Color3} color
  36143. */
  36144. UniformBuffer.prototype.addColor3 = function (name, color) {
  36145. var temp = new Array();
  36146. color.toArray(temp);
  36147. this.addUniform(name, temp);
  36148. };
  36149. /**
  36150. * Wrapper for addUniform.
  36151. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36152. * @param {Color3} color
  36153. * @param {number} alpha
  36154. */
  36155. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36156. var temp = new Array();
  36157. color.toArray(temp);
  36158. temp.push(alpha);
  36159. this.addUniform(name, temp);
  36160. };
  36161. /**
  36162. * Wrapper for addUniform.
  36163. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36164. * @param {Vector3} vector
  36165. */
  36166. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36167. var temp = new Array();
  36168. vector.toArray(temp);
  36169. this.addUniform(name, temp);
  36170. };
  36171. /**
  36172. * Wrapper for addUniform.
  36173. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36174. */
  36175. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36176. this.addUniform(name, 12);
  36177. };
  36178. /**
  36179. * Wrapper for addUniform.
  36180. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36181. */
  36182. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36183. this.addUniform(name, 8);
  36184. };
  36185. /**
  36186. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36187. */
  36188. UniformBuffer.prototype.create = function () {
  36189. if (this._noUBO) {
  36190. return;
  36191. }
  36192. if (this._buffer) {
  36193. return; // nothing to do
  36194. }
  36195. // See spec, alignment must be filled as a vec4
  36196. this._fillAlignment(4);
  36197. this._bufferData = new Float32Array(this._data);
  36198. this._rebuild();
  36199. this._needSync = true;
  36200. };
  36201. UniformBuffer.prototype._rebuild = function () {
  36202. if (this._noUBO) {
  36203. return;
  36204. }
  36205. if (this._dynamic) {
  36206. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36207. }
  36208. else {
  36209. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36210. }
  36211. };
  36212. /**
  36213. * Updates the WebGL Uniform Buffer on the GPU.
  36214. * If the `dynamic` flag is set to true, no cache comparison is done.
  36215. * Otherwise, the buffer will be updated only if the cache differs.
  36216. */
  36217. UniformBuffer.prototype.update = function () {
  36218. if (!this._buffer) {
  36219. this.create();
  36220. return;
  36221. }
  36222. if (!this._dynamic && !this._needSync) {
  36223. return;
  36224. }
  36225. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36226. this._needSync = false;
  36227. };
  36228. /**
  36229. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36230. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36231. * @param {number[]|Float32Array} data Flattened data
  36232. * @param {number} size Size of the data.
  36233. */
  36234. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36235. var location = this._uniformLocations[uniformName];
  36236. if (location === undefined) {
  36237. if (this._buffer) {
  36238. // Cannot add an uniform if the buffer is already created
  36239. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36240. return;
  36241. }
  36242. this.addUniform(uniformName, size);
  36243. location = this._uniformLocations[uniformName];
  36244. }
  36245. if (!this._buffer) {
  36246. this.create();
  36247. }
  36248. if (!this._dynamic) {
  36249. // Cache for static uniform buffers
  36250. var changed = false;
  36251. for (var i = 0; i < size; i++) {
  36252. if (this._bufferData[location + i] !== data[i]) {
  36253. changed = true;
  36254. this._bufferData[location + i] = data[i];
  36255. }
  36256. }
  36257. this._needSync = this._needSync || changed;
  36258. }
  36259. else {
  36260. // No cache for dynamic
  36261. for (var i = 0; i < size; i++) {
  36262. this._bufferData[location + i] = data[i];
  36263. }
  36264. }
  36265. };
  36266. // Update methods
  36267. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36268. // To match std140, matrix must be realigned
  36269. for (var i = 0; i < 3; i++) {
  36270. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36271. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36272. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36273. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36274. }
  36275. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36276. };
  36277. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36278. this._currentEffect.setMatrix3x3(name, matrix);
  36279. };
  36280. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36281. this._currentEffect.setMatrix2x2(name, matrix);
  36282. };
  36283. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36284. // To match std140, matrix must be realigned
  36285. for (var i = 0; i < 2; i++) {
  36286. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36287. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36288. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36289. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36290. }
  36291. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36292. };
  36293. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36294. this._currentEffect.setFloat(name, x);
  36295. };
  36296. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36297. UniformBuffer._tempBuffer[0] = x;
  36298. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36299. };
  36300. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36301. if (suffix === void 0) { suffix = ""; }
  36302. this._currentEffect.setFloat2(name + suffix, x, y);
  36303. };
  36304. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36305. if (suffix === void 0) { suffix = ""; }
  36306. UniformBuffer._tempBuffer[0] = x;
  36307. UniformBuffer._tempBuffer[1] = y;
  36308. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36309. };
  36310. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36311. if (suffix === void 0) { suffix = ""; }
  36312. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36313. };
  36314. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36315. if (suffix === void 0) { suffix = ""; }
  36316. UniformBuffer._tempBuffer[0] = x;
  36317. UniformBuffer._tempBuffer[1] = y;
  36318. UniformBuffer._tempBuffer[2] = z;
  36319. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36320. };
  36321. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36322. if (suffix === void 0) { suffix = ""; }
  36323. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36324. };
  36325. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36326. if (suffix === void 0) { suffix = ""; }
  36327. UniformBuffer._tempBuffer[0] = x;
  36328. UniformBuffer._tempBuffer[1] = y;
  36329. UniformBuffer._tempBuffer[2] = z;
  36330. UniformBuffer._tempBuffer[3] = w;
  36331. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36332. };
  36333. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36334. this._currentEffect.setMatrix(name, mat);
  36335. };
  36336. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36337. this.updateUniform(name, mat.toArray(), 16);
  36338. };
  36339. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36340. this._currentEffect.setVector3(name, vector);
  36341. };
  36342. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36343. vector.toArray(UniformBuffer._tempBuffer);
  36344. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36345. };
  36346. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36347. this._currentEffect.setVector4(name, vector);
  36348. };
  36349. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36350. vector.toArray(UniformBuffer._tempBuffer);
  36351. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36352. };
  36353. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36354. if (suffix === void 0) { suffix = ""; }
  36355. this._currentEffect.setColor3(name + suffix, color);
  36356. };
  36357. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36358. if (suffix === void 0) { suffix = ""; }
  36359. color.toArray(UniformBuffer._tempBuffer);
  36360. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36361. };
  36362. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36363. if (suffix === void 0) { suffix = ""; }
  36364. this._currentEffect.setColor4(name + suffix, color, alpha);
  36365. };
  36366. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36367. if (suffix === void 0) { suffix = ""; }
  36368. color.toArray(UniformBuffer._tempBuffer);
  36369. UniformBuffer._tempBuffer[3] = alpha;
  36370. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36371. };
  36372. /**
  36373. * Sets a sampler uniform on the effect.
  36374. * @param {string} name Name of the sampler.
  36375. * @param {Texture} texture
  36376. */
  36377. UniformBuffer.prototype.setTexture = function (name, texture) {
  36378. this._currentEffect.setTexture(name, texture);
  36379. };
  36380. /**
  36381. * Directly updates the value of the uniform in the cache AND on the GPU.
  36382. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36383. * @param {number[]|Float32Array} data Flattened data
  36384. */
  36385. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36386. this.updateUniform(uniformName, data, data.length);
  36387. this.update();
  36388. };
  36389. /**
  36390. * Binds this uniform buffer to an effect.
  36391. * @param {Effect} effect
  36392. * @param {string} name Name of the uniform block in the shader.
  36393. */
  36394. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36395. this._currentEffect = effect;
  36396. if (this._noUBO || !this._buffer) {
  36397. return;
  36398. }
  36399. effect.bindUniformBuffer(this._buffer, name);
  36400. };
  36401. /**
  36402. * Disposes the uniform buffer.
  36403. */
  36404. UniformBuffer.prototype.dispose = function () {
  36405. if (this._noUBO) {
  36406. return;
  36407. }
  36408. var index = this._engine._uniformBuffers.indexOf(this);
  36409. if (index !== -1) {
  36410. this._engine._uniformBuffers.splice(index, 1);
  36411. }
  36412. if (!this._buffer) {
  36413. return;
  36414. }
  36415. if (this._engine._releaseBuffer(this._buffer)) {
  36416. this._buffer = null;
  36417. }
  36418. };
  36419. // Pool for avoiding memory leaks
  36420. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36421. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36422. return UniformBuffer;
  36423. }());
  36424. BABYLON.UniformBuffer = UniformBuffer;
  36425. })(BABYLON || (BABYLON = {}));
  36426. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36427. var BABYLON;
  36428. (function (BABYLON) {
  36429. /**
  36430. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36431. */
  36432. var VertexData = /** @class */ (function () {
  36433. function VertexData() {
  36434. }
  36435. /**
  36436. * Uses the passed data array to set the set the values for the specified kind of data
  36437. * @param data a linear array of floating numbers
  36438. * @param kind the type of data that is being set, eg positions, colors etc
  36439. */
  36440. VertexData.prototype.set = function (data, kind) {
  36441. switch (kind) {
  36442. case BABYLON.VertexBuffer.PositionKind:
  36443. this.positions = data;
  36444. break;
  36445. case BABYLON.VertexBuffer.NormalKind:
  36446. this.normals = data;
  36447. break;
  36448. case BABYLON.VertexBuffer.TangentKind:
  36449. this.tangents = data;
  36450. break;
  36451. case BABYLON.VertexBuffer.UVKind:
  36452. this.uvs = data;
  36453. break;
  36454. case BABYLON.VertexBuffer.UV2Kind:
  36455. this.uvs2 = data;
  36456. break;
  36457. case BABYLON.VertexBuffer.UV3Kind:
  36458. this.uvs3 = data;
  36459. break;
  36460. case BABYLON.VertexBuffer.UV4Kind:
  36461. this.uvs4 = data;
  36462. break;
  36463. case BABYLON.VertexBuffer.UV5Kind:
  36464. this.uvs5 = data;
  36465. break;
  36466. case BABYLON.VertexBuffer.UV6Kind:
  36467. this.uvs6 = data;
  36468. break;
  36469. case BABYLON.VertexBuffer.ColorKind:
  36470. this.colors = data;
  36471. break;
  36472. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36473. this.matricesIndices = data;
  36474. break;
  36475. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36476. this.matricesWeights = data;
  36477. break;
  36478. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36479. this.matricesIndicesExtra = data;
  36480. break;
  36481. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36482. this.matricesWeightsExtra = data;
  36483. break;
  36484. }
  36485. };
  36486. /**
  36487. * Associates the vertexData to the passed Mesh.
  36488. * Sets it as updatable or not (default `false`)
  36489. * @param mesh the mesh the vertexData is applied to
  36490. * @param updatable when used and having the value true allows new data to update the vertexData
  36491. * @returns the VertexData
  36492. */
  36493. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36494. this._applyTo(mesh, updatable);
  36495. return this;
  36496. };
  36497. /**
  36498. * Associates the vertexData to the passed Geometry.
  36499. * Sets it as updatable or not (default `false`)
  36500. * @param geometry the geometry the vertexData is applied to
  36501. * @param updatable when used and having the value true allows new data to update the vertexData
  36502. * @returns VertexData
  36503. */
  36504. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36505. this._applyTo(geometry, updatable);
  36506. return this;
  36507. };
  36508. /**
  36509. * Updates the associated mesh
  36510. * @param mesh the mesh to be updated
  36511. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36512. * @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
  36513. * @returns VertexData
  36514. */
  36515. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36516. this._update(mesh);
  36517. return this;
  36518. };
  36519. /**
  36520. * Updates the associated geometry
  36521. * @param geometry the geometry to be updated
  36522. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36523. * @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
  36524. * @returns VertexData.
  36525. */
  36526. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36527. this._update(geometry);
  36528. return this;
  36529. };
  36530. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36531. if (updatable === void 0) { updatable = false; }
  36532. if (this.positions) {
  36533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36534. }
  36535. if (this.normals) {
  36536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36537. }
  36538. if (this.tangents) {
  36539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36540. }
  36541. if (this.uvs) {
  36542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36543. }
  36544. if (this.uvs2) {
  36545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36546. }
  36547. if (this.uvs3) {
  36548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36549. }
  36550. if (this.uvs4) {
  36551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36552. }
  36553. if (this.uvs5) {
  36554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36555. }
  36556. if (this.uvs6) {
  36557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36558. }
  36559. if (this.colors) {
  36560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36561. }
  36562. if (this.matricesIndices) {
  36563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36564. }
  36565. if (this.matricesWeights) {
  36566. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36567. }
  36568. if (this.matricesIndicesExtra) {
  36569. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36570. }
  36571. if (this.matricesWeightsExtra) {
  36572. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36573. }
  36574. if (this.indices) {
  36575. meshOrGeometry.setIndices(this.indices, null, updatable);
  36576. }
  36577. else {
  36578. meshOrGeometry.setIndices([], null);
  36579. }
  36580. return this;
  36581. };
  36582. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36583. if (this.positions) {
  36584. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36585. }
  36586. if (this.normals) {
  36587. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36588. }
  36589. if (this.tangents) {
  36590. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36591. }
  36592. if (this.uvs) {
  36593. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36594. }
  36595. if (this.uvs2) {
  36596. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36597. }
  36598. if (this.uvs3) {
  36599. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36600. }
  36601. if (this.uvs4) {
  36602. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36603. }
  36604. if (this.uvs5) {
  36605. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36606. }
  36607. if (this.uvs6) {
  36608. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36609. }
  36610. if (this.colors) {
  36611. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36612. }
  36613. if (this.matricesIndices) {
  36614. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36615. }
  36616. if (this.matricesWeights) {
  36617. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36618. }
  36619. if (this.matricesIndicesExtra) {
  36620. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36621. }
  36622. if (this.matricesWeightsExtra) {
  36623. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36624. }
  36625. if (this.indices) {
  36626. meshOrGeometry.setIndices(this.indices, null);
  36627. }
  36628. return this;
  36629. };
  36630. /**
  36631. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36632. * @param matrix the transforming matrix
  36633. * @returns the VertexData
  36634. */
  36635. VertexData.prototype.transform = function (matrix) {
  36636. var transformed = BABYLON.Vector3.Zero();
  36637. var index;
  36638. if (this.positions) {
  36639. var position = BABYLON.Vector3.Zero();
  36640. for (index = 0; index < this.positions.length; index += 3) {
  36641. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36642. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36643. this.positions[index] = transformed.x;
  36644. this.positions[index + 1] = transformed.y;
  36645. this.positions[index + 2] = transformed.z;
  36646. }
  36647. }
  36648. if (this.normals) {
  36649. var normal = BABYLON.Vector3.Zero();
  36650. for (index = 0; index < this.normals.length; index += 3) {
  36651. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36652. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36653. this.normals[index] = transformed.x;
  36654. this.normals[index + 1] = transformed.y;
  36655. this.normals[index + 2] = transformed.z;
  36656. }
  36657. }
  36658. if (this.tangents) {
  36659. var tangent = BABYLON.Vector4.Zero();
  36660. var tangentTransformed = BABYLON.Vector4.Zero();
  36661. for (index = 0; index < this.tangents.length; index += 4) {
  36662. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36663. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36664. this.tangents[index] = tangentTransformed.x;
  36665. this.tangents[index + 1] = tangentTransformed.y;
  36666. this.tangents[index + 2] = tangentTransformed.z;
  36667. this.tangents[index + 3] = tangentTransformed.w;
  36668. }
  36669. }
  36670. return this;
  36671. };
  36672. /**
  36673. * Merges the passed VertexData into the current one
  36674. * @param other the VertexData to be merged into the current one
  36675. * @returns the modified VertexData
  36676. */
  36677. VertexData.prototype.merge = function (other) {
  36678. this._validate();
  36679. other._validate();
  36680. if (!this.normals !== !other.normals ||
  36681. !this.tangents !== !other.tangents ||
  36682. !this.uvs !== !other.uvs ||
  36683. !this.uvs2 !== !other.uvs2 ||
  36684. !this.uvs3 !== !other.uvs3 ||
  36685. !this.uvs4 !== !other.uvs4 ||
  36686. !this.uvs5 !== !other.uvs5 ||
  36687. !this.uvs6 !== !other.uvs6 ||
  36688. !this.colors !== !other.colors ||
  36689. !this.matricesIndices !== !other.matricesIndices ||
  36690. !this.matricesWeights !== !other.matricesWeights ||
  36691. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36692. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36693. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36694. }
  36695. if (other.indices) {
  36696. if (!this.indices) {
  36697. this.indices = [];
  36698. }
  36699. var offset = this.positions ? this.positions.length / 3 : 0;
  36700. for (var index = 0; index < other.indices.length; index++) {
  36701. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36702. this.indices.push(other.indices[index] + offset);
  36703. }
  36704. }
  36705. this.positions = this._mergeElement(this.positions, other.positions);
  36706. this.normals = this._mergeElement(this.normals, other.normals);
  36707. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36708. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36709. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36710. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36711. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36712. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36713. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36714. this.colors = this._mergeElement(this.colors, other.colors);
  36715. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36716. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36717. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36718. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36719. return this;
  36720. };
  36721. VertexData.prototype._mergeElement = function (source, other) {
  36722. if (!source) {
  36723. return other;
  36724. }
  36725. if (!other) {
  36726. return source;
  36727. }
  36728. var len = other.length + source.length;
  36729. var isSrcTypedArray = source instanceof Float32Array;
  36730. var isOthTypedArray = other instanceof Float32Array;
  36731. // use non-loop method when the source is Float32Array
  36732. if (isSrcTypedArray) {
  36733. var ret32 = new Float32Array(len);
  36734. ret32.set(source);
  36735. ret32.set(other, source.length);
  36736. return ret32;
  36737. // source is number[], when other is also use concat
  36738. }
  36739. else if (!isOthTypedArray) {
  36740. return source.concat(other);
  36741. // source is a number[], but other is a Float32Array, loop required
  36742. }
  36743. else {
  36744. var ret = source.slice(0); // copy source to a separate array
  36745. for (var i = 0, len = other.length; i < len; i++) {
  36746. ret.push(other[i]);
  36747. }
  36748. return ret;
  36749. }
  36750. };
  36751. VertexData.prototype._validate = function () {
  36752. if (!this.positions) {
  36753. throw new Error("Positions are required");
  36754. }
  36755. var getElementCount = function (kind, values) {
  36756. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36757. if ((values.length % stride) !== 0) {
  36758. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36759. }
  36760. return values.length / stride;
  36761. };
  36762. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36763. var validateElementCount = function (kind, values) {
  36764. var elementCount = getElementCount(kind, values);
  36765. if (elementCount !== positionsElementCount) {
  36766. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36767. }
  36768. };
  36769. if (this.normals)
  36770. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36771. if (this.tangents)
  36772. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36773. if (this.uvs)
  36774. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36775. if (this.uvs2)
  36776. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36777. if (this.uvs3)
  36778. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36779. if (this.uvs4)
  36780. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36781. if (this.uvs5)
  36782. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36783. if (this.uvs6)
  36784. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36785. if (this.colors)
  36786. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36787. if (this.matricesIndices)
  36788. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36789. if (this.matricesWeights)
  36790. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36791. if (this.matricesIndicesExtra)
  36792. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36793. if (this.matricesWeightsExtra)
  36794. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36795. };
  36796. /**
  36797. * Serializes the VertexData
  36798. * @returns a serialized object
  36799. */
  36800. VertexData.prototype.serialize = function () {
  36801. var serializationObject = this.serialize();
  36802. if (this.positions) {
  36803. serializationObject.positions = this.positions;
  36804. }
  36805. if (this.normals) {
  36806. serializationObject.normals = this.normals;
  36807. }
  36808. if (this.tangents) {
  36809. serializationObject.tangents = this.tangents;
  36810. }
  36811. if (this.uvs) {
  36812. serializationObject.uvs = this.uvs;
  36813. }
  36814. if (this.uvs2) {
  36815. serializationObject.uvs2 = this.uvs2;
  36816. }
  36817. if (this.uvs3) {
  36818. serializationObject.uvs3 = this.uvs3;
  36819. }
  36820. if (this.uvs4) {
  36821. serializationObject.uvs4 = this.uvs4;
  36822. }
  36823. if (this.uvs5) {
  36824. serializationObject.uvs5 = this.uvs5;
  36825. }
  36826. if (this.uvs6) {
  36827. serializationObject.uvs6 = this.uvs6;
  36828. }
  36829. if (this.colors) {
  36830. serializationObject.colors = this.colors;
  36831. }
  36832. if (this.matricesIndices) {
  36833. serializationObject.matricesIndices = this.matricesIndices;
  36834. serializationObject.matricesIndices._isExpanded = true;
  36835. }
  36836. if (this.matricesWeights) {
  36837. serializationObject.matricesWeights = this.matricesWeights;
  36838. }
  36839. if (this.matricesIndicesExtra) {
  36840. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36841. serializationObject.matricesIndicesExtra._isExpanded = true;
  36842. }
  36843. if (this.matricesWeightsExtra) {
  36844. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36845. }
  36846. serializationObject.indices = this.indices;
  36847. return serializationObject;
  36848. };
  36849. // Statics
  36850. /**
  36851. * Extracts the vertexData from a mesh
  36852. * @param mesh the mesh from which to extract the VertexData
  36853. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36854. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36855. * @returns the object VertexData associated to the passed mesh
  36856. */
  36857. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36858. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36859. };
  36860. /**
  36861. * Extracts the vertexData from the geometry
  36862. * @param geometry the geometry from which to extract the VertexData
  36863. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36864. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36865. * @returns the object VertexData associated to the passed mesh
  36866. */
  36867. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36868. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36869. };
  36870. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36871. var result = new VertexData();
  36872. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36873. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36874. }
  36875. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36876. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36877. }
  36878. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36879. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36880. }
  36881. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36882. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36883. }
  36884. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36885. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36886. }
  36887. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36888. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36889. }
  36890. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36891. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36892. }
  36893. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36894. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36895. }
  36896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36897. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36898. }
  36899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36900. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36901. }
  36902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36903. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36904. }
  36905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36906. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36907. }
  36908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36909. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36910. }
  36911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36912. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36913. }
  36914. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36915. return result;
  36916. };
  36917. /**
  36918. * Creates the VertexData for a Ribbon
  36919. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36920. * * pathArray array of paths, each of which an array of successive Vector3
  36921. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36922. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36923. * * 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
  36924. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36925. * * 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)
  36926. * * 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)
  36927. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36928. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36929. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36930. * @returns the VertexData of the ribbon
  36931. */
  36932. VertexData.CreateRibbon = function (options) {
  36933. var pathArray = options.pathArray;
  36934. var closeArray = options.closeArray || false;
  36935. var closePath = options.closePath || false;
  36936. var invertUV = options.invertUV || false;
  36937. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36938. var offset = options.offset || defaultOffset;
  36939. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36940. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36941. var customUV = options.uvs;
  36942. var customColors = options.colors;
  36943. var positions = [];
  36944. var indices = [];
  36945. var normals = [];
  36946. var uvs = [];
  36947. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36948. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36949. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36950. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36951. var minlg; // minimal length among all paths from pathArray
  36952. var lg = []; // array of path lengths : nb of vertex per path
  36953. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36954. var p; // path iterator
  36955. var i; // point iterator
  36956. var j; // point iterator
  36957. // if single path in pathArray
  36958. if (pathArray.length < 2) {
  36959. var ar1 = [];
  36960. var ar2 = [];
  36961. for (i = 0; i < pathArray[0].length - offset; i++) {
  36962. ar1.push(pathArray[0][i]);
  36963. ar2.push(pathArray[0][i + offset]);
  36964. }
  36965. pathArray = [ar1, ar2];
  36966. }
  36967. // positions and horizontal distances (u)
  36968. var idc = 0;
  36969. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36970. var path;
  36971. var l;
  36972. minlg = pathArray[0].length;
  36973. var vectlg;
  36974. var dist;
  36975. for (p = 0; p < pathArray.length; p++) {
  36976. uTotalDistance[p] = 0;
  36977. us[p] = [0];
  36978. path = pathArray[p];
  36979. l = path.length;
  36980. minlg = (minlg < l) ? minlg : l;
  36981. j = 0;
  36982. while (j < l) {
  36983. positions.push(path[j].x, path[j].y, path[j].z);
  36984. if (j > 0) {
  36985. vectlg = path[j].subtract(path[j - 1]).length();
  36986. dist = vectlg + uTotalDistance[p];
  36987. us[p].push(dist);
  36988. uTotalDistance[p] = dist;
  36989. }
  36990. j++;
  36991. }
  36992. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36993. j--;
  36994. positions.push(path[0].x, path[0].y, path[0].z);
  36995. vectlg = path[j].subtract(path[0]).length();
  36996. dist = vectlg + uTotalDistance[p];
  36997. us[p].push(dist);
  36998. uTotalDistance[p] = dist;
  36999. }
  37000. lg[p] = l + closePathCorr;
  37001. idx[p] = idc;
  37002. idc += (l + closePathCorr);
  37003. }
  37004. // vertical distances (v)
  37005. var path1;
  37006. var path2;
  37007. var vertex1 = null;
  37008. var vertex2 = null;
  37009. for (i = 0; i < minlg + closePathCorr; i++) {
  37010. vTotalDistance[i] = 0;
  37011. vs[i] = [0];
  37012. for (p = 0; p < pathArray.length - 1; p++) {
  37013. path1 = pathArray[p];
  37014. path2 = pathArray[p + 1];
  37015. if (i === minlg) { // closePath
  37016. vertex1 = path1[0];
  37017. vertex2 = path2[0];
  37018. }
  37019. else {
  37020. vertex1 = path1[i];
  37021. vertex2 = path2[i];
  37022. }
  37023. vectlg = vertex2.subtract(vertex1).length();
  37024. dist = vectlg + vTotalDistance[i];
  37025. vs[i].push(dist);
  37026. vTotalDistance[i] = dist;
  37027. }
  37028. if (closeArray && vertex2 && vertex1) {
  37029. path1 = pathArray[p];
  37030. path2 = pathArray[0];
  37031. if (i === minlg) { // closePath
  37032. vertex2 = path2[0];
  37033. }
  37034. vectlg = vertex2.subtract(vertex1).length();
  37035. dist = vectlg + vTotalDistance[i];
  37036. vTotalDistance[i] = dist;
  37037. }
  37038. }
  37039. // uvs
  37040. var u;
  37041. var v;
  37042. if (customUV) {
  37043. for (p = 0; p < customUV.length; p++) {
  37044. uvs.push(customUV[p].x, customUV[p].y);
  37045. }
  37046. }
  37047. else {
  37048. for (p = 0; p < pathArray.length; p++) {
  37049. for (i = 0; i < minlg + closePathCorr; i++) {
  37050. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37051. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37052. if (invertUV) {
  37053. uvs.push(v, u);
  37054. }
  37055. else {
  37056. uvs.push(u, v);
  37057. }
  37058. }
  37059. }
  37060. }
  37061. // indices
  37062. p = 0; // path index
  37063. var pi = 0; // positions array index
  37064. var l1 = lg[p] - 1; // path1 length
  37065. var l2 = lg[p + 1] - 1; // path2 length
  37066. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37067. var shft = idx[1] - idx[0]; // shift
  37068. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37069. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37070. // 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
  37071. indices.push(pi, pi + shft, pi + 1);
  37072. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37073. pi += 1;
  37074. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37075. p++;
  37076. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37077. shft = idx[0] - idx[p];
  37078. l1 = lg[p] - 1;
  37079. l2 = lg[0] - 1;
  37080. }
  37081. else {
  37082. shft = idx[p + 1] - idx[p];
  37083. l1 = lg[p] - 1;
  37084. l2 = lg[p + 1] - 1;
  37085. }
  37086. pi = idx[p];
  37087. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37088. }
  37089. }
  37090. // normals
  37091. VertexData.ComputeNormals(positions, indices, normals);
  37092. if (closePath) { // update both the first and last vertex normals to their average value
  37093. var indexFirst = 0;
  37094. var indexLast = 0;
  37095. for (p = 0; p < pathArray.length; p++) {
  37096. indexFirst = idx[p] * 3;
  37097. if (p + 1 < pathArray.length) {
  37098. indexLast = (idx[p + 1] - 1) * 3;
  37099. }
  37100. else {
  37101. indexLast = normals.length - 3;
  37102. }
  37103. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37104. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37105. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37106. normals[indexLast] = normals[indexFirst];
  37107. normals[indexLast + 1] = normals[indexFirst + 1];
  37108. normals[indexLast + 2] = normals[indexFirst + 2];
  37109. }
  37110. }
  37111. // sides
  37112. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37113. // Colors
  37114. var colors = null;
  37115. if (customColors) {
  37116. colors = new Float32Array(customColors.length * 4);
  37117. for (var c = 0; c < customColors.length; c++) {
  37118. colors[c * 4] = customColors[c].r;
  37119. colors[c * 4 + 1] = customColors[c].g;
  37120. colors[c * 4 + 2] = customColors[c].b;
  37121. colors[c * 4 + 3] = customColors[c].a;
  37122. }
  37123. }
  37124. // Result
  37125. var vertexData = new VertexData();
  37126. var positions32 = new Float32Array(positions);
  37127. var normals32 = new Float32Array(normals);
  37128. var uvs32 = new Float32Array(uvs);
  37129. vertexData.indices = indices;
  37130. vertexData.positions = positions32;
  37131. vertexData.normals = normals32;
  37132. vertexData.uvs = uvs32;
  37133. if (colors) {
  37134. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37135. }
  37136. if (closePath) {
  37137. vertexData._idx = idx;
  37138. }
  37139. return vertexData;
  37140. };
  37141. /**
  37142. * Creates the VertexData for a box
  37143. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37144. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37145. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37146. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37147. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37148. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37149. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37150. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37151. * * 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)
  37152. * * 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)
  37153. * @returns the VertexData of the box
  37154. */
  37155. VertexData.CreateBox = function (options) {
  37156. var normalsSource = [
  37157. new BABYLON.Vector3(0, 0, 1),
  37158. new BABYLON.Vector3(0, 0, -1),
  37159. new BABYLON.Vector3(1, 0, 0),
  37160. new BABYLON.Vector3(-1, 0, 0),
  37161. new BABYLON.Vector3(0, 1, 0),
  37162. new BABYLON.Vector3(0, -1, 0)
  37163. ];
  37164. var indices = [];
  37165. var positions = [];
  37166. var normals = [];
  37167. var uvs = [];
  37168. var width = options.width || options.size || 1;
  37169. var height = options.height || options.size || 1;
  37170. var depth = options.depth || options.size || 1;
  37171. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37172. var faceUV = options.faceUV || new Array(6);
  37173. var faceColors = options.faceColors;
  37174. var colors = [];
  37175. // default face colors and UV if undefined
  37176. for (var f = 0; f < 6; f++) {
  37177. if (faceUV[f] === undefined) {
  37178. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37179. }
  37180. if (faceColors && faceColors[f] === undefined) {
  37181. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37182. }
  37183. }
  37184. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37185. // Create each face in turn.
  37186. for (var index = 0; index < normalsSource.length; index++) {
  37187. var normal = normalsSource[index];
  37188. // Get two vectors perpendicular to the face normal and to each other.
  37189. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37190. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37191. // Six indices (two triangles) per face.
  37192. var verticesLength = positions.length / 3;
  37193. indices.push(verticesLength);
  37194. indices.push(verticesLength + 1);
  37195. indices.push(verticesLength + 2);
  37196. indices.push(verticesLength);
  37197. indices.push(verticesLength + 2);
  37198. indices.push(verticesLength + 3);
  37199. // Four vertices per face.
  37200. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37201. positions.push(vertex.x, vertex.y, vertex.z);
  37202. normals.push(normal.x, normal.y, normal.z);
  37203. uvs.push(faceUV[index].z, faceUV[index].w);
  37204. if (faceColors) {
  37205. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37206. }
  37207. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37208. positions.push(vertex.x, vertex.y, vertex.z);
  37209. normals.push(normal.x, normal.y, normal.z);
  37210. uvs.push(faceUV[index].x, faceUV[index].w);
  37211. if (faceColors) {
  37212. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37213. }
  37214. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37215. positions.push(vertex.x, vertex.y, vertex.z);
  37216. normals.push(normal.x, normal.y, normal.z);
  37217. uvs.push(faceUV[index].x, faceUV[index].y);
  37218. if (faceColors) {
  37219. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37220. }
  37221. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37222. positions.push(vertex.x, vertex.y, vertex.z);
  37223. normals.push(normal.x, normal.y, normal.z);
  37224. uvs.push(faceUV[index].z, faceUV[index].y);
  37225. if (faceColors) {
  37226. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37227. }
  37228. }
  37229. // sides
  37230. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37231. // Result
  37232. var vertexData = new VertexData();
  37233. vertexData.indices = indices;
  37234. vertexData.positions = positions;
  37235. vertexData.normals = normals;
  37236. vertexData.uvs = uvs;
  37237. if (faceColors) {
  37238. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37239. vertexData.colors = totalColors;
  37240. }
  37241. return vertexData;
  37242. };
  37243. /**
  37244. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37245. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37246. * * segments sets the number of horizontal strips optional, default 32
  37247. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37248. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37249. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37250. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37251. * * 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
  37252. * * 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
  37253. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37254. * * 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)
  37255. * * 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)
  37256. * @returns the VertexData of the ellipsoid
  37257. */
  37258. VertexData.CreateSphere = function (options) {
  37259. var segments = options.segments || 32;
  37260. var diameterX = options.diameterX || options.diameter || 1;
  37261. var diameterY = options.diameterY || options.diameter || 1;
  37262. var diameterZ = options.diameterZ || options.diameter || 1;
  37263. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37264. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37266. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37267. var totalZRotationSteps = 2 + segments;
  37268. var totalYRotationSteps = 2 * totalZRotationSteps;
  37269. var indices = [];
  37270. var positions = [];
  37271. var normals = [];
  37272. var uvs = [];
  37273. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37274. var normalizedZ = zRotationStep / totalZRotationSteps;
  37275. var angleZ = normalizedZ * Math.PI * slice;
  37276. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37277. var normalizedY = yRotationStep / totalYRotationSteps;
  37278. var angleY = normalizedY * Math.PI * 2 * arc;
  37279. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37280. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37281. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37282. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37283. var vertex = complete.multiply(radius);
  37284. var normal = complete.divide(radius).normalize();
  37285. positions.push(vertex.x, vertex.y, vertex.z);
  37286. normals.push(normal.x, normal.y, normal.z);
  37287. uvs.push(normalizedY, normalizedZ);
  37288. }
  37289. if (zRotationStep > 0) {
  37290. var verticesCount = positions.length / 3;
  37291. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37292. indices.push((firstIndex));
  37293. indices.push((firstIndex + 1));
  37294. indices.push(firstIndex + totalYRotationSteps + 1);
  37295. indices.push((firstIndex + totalYRotationSteps + 1));
  37296. indices.push((firstIndex + 1));
  37297. indices.push((firstIndex + totalYRotationSteps + 2));
  37298. }
  37299. }
  37300. }
  37301. // Sides
  37302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37303. // Result
  37304. var vertexData = new VertexData();
  37305. vertexData.indices = indices;
  37306. vertexData.positions = positions;
  37307. vertexData.normals = normals;
  37308. vertexData.uvs = uvs;
  37309. return vertexData;
  37310. };
  37311. /**
  37312. * Creates the VertexData for a cylinder, cone or prism
  37313. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37314. * * height sets the height (y direction) of the cylinder, optional, default 2
  37315. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37316. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37317. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37318. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37319. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37320. * * 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
  37321. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37322. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37323. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37324. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37325. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37326. * * 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)
  37327. * * 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)
  37328. * @returns the VertexData of the cylinder, cone or prism
  37329. */
  37330. VertexData.CreateCylinder = function (options) {
  37331. var height = options.height || 2;
  37332. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37333. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37334. var tessellation = options.tessellation || 24;
  37335. var subdivisions = options.subdivisions || 1;
  37336. var hasRings = options.hasRings ? true : false;
  37337. var enclose = options.enclose ? true : false;
  37338. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37339. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37340. var faceUV = options.faceUV || new Array(3);
  37341. var faceColors = options.faceColors;
  37342. // default face colors and UV if undefined
  37343. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37344. var ringNb = (hasRings) ? subdivisions : 1;
  37345. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37346. var f;
  37347. for (f = 0; f < surfaceNb; f++) {
  37348. if (faceColors && faceColors[f] === undefined) {
  37349. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37350. }
  37351. }
  37352. for (f = 0; f < surfaceNb; f++) {
  37353. if (faceUV && faceUV[f] === undefined) {
  37354. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37355. }
  37356. }
  37357. var indices = new Array();
  37358. var positions = new Array();
  37359. var normals = new Array();
  37360. var uvs = new Array();
  37361. var colors = new Array();
  37362. var angle_step = Math.PI * 2 * arc / tessellation;
  37363. var angle;
  37364. var h;
  37365. var radius;
  37366. var tan = (diameterBottom - diameterTop) / 2 / height;
  37367. var ringVertex = BABYLON.Vector3.Zero();
  37368. var ringNormal = BABYLON.Vector3.Zero();
  37369. var ringFirstVertex = BABYLON.Vector3.Zero();
  37370. var ringFirstNormal = BABYLON.Vector3.Zero();
  37371. var quadNormal = BABYLON.Vector3.Zero();
  37372. var Y = BABYLON.Axis.Y;
  37373. // positions, normals, uvs
  37374. var i;
  37375. var j;
  37376. var r;
  37377. var ringIdx = 1;
  37378. var s = 1; // surface index
  37379. var cs = 0;
  37380. var v = 0;
  37381. for (i = 0; i <= subdivisions; i++) {
  37382. h = i / subdivisions;
  37383. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37384. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37385. for (r = 0; r < ringIdx; r++) {
  37386. if (hasRings) {
  37387. s += r;
  37388. }
  37389. if (enclose) {
  37390. s += 2 * r;
  37391. }
  37392. for (j = 0; j <= tessellation; j++) {
  37393. angle = j * angle_step;
  37394. // position
  37395. ringVertex.x = Math.cos(-angle) * radius;
  37396. ringVertex.y = -height / 2 + h * height;
  37397. ringVertex.z = Math.sin(-angle) * radius;
  37398. // normal
  37399. if (diameterTop === 0 && i === subdivisions) {
  37400. // if no top cap, reuse former normals
  37401. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37402. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37403. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37404. }
  37405. else {
  37406. ringNormal.x = ringVertex.x;
  37407. ringNormal.z = ringVertex.z;
  37408. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37409. ringNormal.normalize();
  37410. }
  37411. // keep first ring vertex values for enclose
  37412. if (j === 0) {
  37413. ringFirstVertex.copyFrom(ringVertex);
  37414. ringFirstNormal.copyFrom(ringNormal);
  37415. }
  37416. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37417. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37418. if (hasRings) {
  37419. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37420. }
  37421. else {
  37422. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37423. }
  37424. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37425. if (faceColors) {
  37426. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37427. }
  37428. }
  37429. // if enclose, add four vertices and their dedicated normals
  37430. if (arc !== 1 && enclose) {
  37431. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37432. positions.push(0, ringVertex.y, 0);
  37433. positions.push(0, ringVertex.y, 0);
  37434. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37435. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37436. quadNormal.normalize();
  37437. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37438. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37439. quadNormal.normalize();
  37440. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37441. if (hasRings) {
  37442. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37443. }
  37444. else {
  37445. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37446. }
  37447. uvs.push(faceUV[s + 1].x, v);
  37448. uvs.push(faceUV[s + 1].z, v);
  37449. if (hasRings) {
  37450. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37451. }
  37452. else {
  37453. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37454. }
  37455. uvs.push(faceUV[s + 2].x, v);
  37456. uvs.push(faceUV[s + 2].z, v);
  37457. if (faceColors) {
  37458. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37459. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37460. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37461. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37462. }
  37463. }
  37464. if (cs !== s) {
  37465. cs = s;
  37466. }
  37467. }
  37468. }
  37469. // indices
  37470. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37471. var s;
  37472. i = 0;
  37473. for (s = 0; s < subdivisions; s++) {
  37474. var i0 = 0;
  37475. var i1 = 0;
  37476. var i2 = 0;
  37477. var i3 = 0;
  37478. for (j = 0; j < tessellation; j++) {
  37479. i0 = i * (e + 1) + j;
  37480. i1 = (i + 1) * (e + 1) + j;
  37481. i2 = i * (e + 1) + (j + 1);
  37482. i3 = (i + 1) * (e + 1) + (j + 1);
  37483. indices.push(i0, i1, i2);
  37484. indices.push(i3, i2, i1);
  37485. }
  37486. if (arc !== 1 && enclose) { // if enclose, add two quads
  37487. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37488. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37489. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37490. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37491. }
  37492. i = (hasRings) ? (i + 2) : (i + 1);
  37493. }
  37494. // Caps
  37495. var createCylinderCap = function (isTop) {
  37496. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37497. if (radius === 0) {
  37498. return;
  37499. }
  37500. // Cap positions, normals & uvs
  37501. var angle;
  37502. var circleVector;
  37503. var i;
  37504. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37505. var c = null;
  37506. if (faceColors) {
  37507. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37508. }
  37509. // cap center
  37510. var vbase = positions.length / 3;
  37511. var offset = isTop ? height / 2 : -height / 2;
  37512. var center = new BABYLON.Vector3(0, offset, 0);
  37513. positions.push(center.x, center.y, center.z);
  37514. normals.push(0, isTop ? 1 : -1, 0);
  37515. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37516. if (c) {
  37517. colors.push(c.r, c.g, c.b, c.a);
  37518. }
  37519. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37520. for (i = 0; i <= tessellation; i++) {
  37521. angle = Math.PI * 2 * i * arc / tessellation;
  37522. var cos = Math.cos(-angle);
  37523. var sin = Math.sin(-angle);
  37524. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37525. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37526. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37527. normals.push(0, isTop ? 1 : -1, 0);
  37528. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37529. if (c) {
  37530. colors.push(c.r, c.g, c.b, c.a);
  37531. }
  37532. }
  37533. // Cap indices
  37534. for (i = 0; i < tessellation; i++) {
  37535. if (!isTop) {
  37536. indices.push(vbase);
  37537. indices.push(vbase + (i + 1));
  37538. indices.push(vbase + (i + 2));
  37539. }
  37540. else {
  37541. indices.push(vbase);
  37542. indices.push(vbase + (i + 2));
  37543. indices.push(vbase + (i + 1));
  37544. }
  37545. }
  37546. };
  37547. // add caps to geometry
  37548. createCylinderCap(false);
  37549. createCylinderCap(true);
  37550. // Sides
  37551. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37552. var vertexData = new VertexData();
  37553. vertexData.indices = indices;
  37554. vertexData.positions = positions;
  37555. vertexData.normals = normals;
  37556. vertexData.uvs = uvs;
  37557. if (faceColors) {
  37558. vertexData.colors = colors;
  37559. }
  37560. return vertexData;
  37561. };
  37562. /**
  37563. * Creates the VertexData for a torus
  37564. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37565. * * diameter the diameter of the torus, optional default 1
  37566. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37567. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37568. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37569. * * 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)
  37570. * * 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)
  37571. * @returns the VertexData of the torus
  37572. */
  37573. VertexData.CreateTorus = function (options) {
  37574. var indices = [];
  37575. var positions = [];
  37576. var normals = [];
  37577. var uvs = [];
  37578. var diameter = options.diameter || 1;
  37579. var thickness = options.thickness || 0.5;
  37580. var tessellation = options.tessellation || 16;
  37581. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37582. var stride = tessellation + 1;
  37583. for (var i = 0; i <= tessellation; i++) {
  37584. var u = i / tessellation;
  37585. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37586. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37587. for (var j = 0; j <= tessellation; j++) {
  37588. var v = 1 - j / tessellation;
  37589. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37590. var dx = Math.cos(innerAngle);
  37591. var dy = Math.sin(innerAngle);
  37592. // Create a vertex.
  37593. var normal = new BABYLON.Vector3(dx, dy, 0);
  37594. var position = normal.scale(thickness / 2);
  37595. var textureCoordinate = new BABYLON.Vector2(u, v);
  37596. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37597. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37598. positions.push(position.x, position.y, position.z);
  37599. normals.push(normal.x, normal.y, normal.z);
  37600. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37601. // And create indices for two triangles.
  37602. var nextI = (i + 1) % stride;
  37603. var nextJ = (j + 1) % stride;
  37604. indices.push(i * stride + j);
  37605. indices.push(i * stride + nextJ);
  37606. indices.push(nextI * stride + j);
  37607. indices.push(i * stride + nextJ);
  37608. indices.push(nextI * stride + nextJ);
  37609. indices.push(nextI * stride + j);
  37610. }
  37611. }
  37612. // Sides
  37613. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37614. // Result
  37615. var vertexData = new VertexData();
  37616. vertexData.indices = indices;
  37617. vertexData.positions = positions;
  37618. vertexData.normals = normals;
  37619. vertexData.uvs = uvs;
  37620. return vertexData;
  37621. };
  37622. /**
  37623. * Creates the VertexData of the LineSystem
  37624. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37625. * - lines an array of lines, each line being an array of successive Vector3
  37626. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37627. * @returns the VertexData of the LineSystem
  37628. */
  37629. VertexData.CreateLineSystem = function (options) {
  37630. var indices = [];
  37631. var positions = [];
  37632. var lines = options.lines;
  37633. var colors = options.colors;
  37634. var vertexColors = [];
  37635. var idx = 0;
  37636. for (var l = 0; l < lines.length; l++) {
  37637. var points = lines[l];
  37638. for (var index = 0; index < points.length; index++) {
  37639. positions.push(points[index].x, points[index].y, points[index].z);
  37640. if (colors) {
  37641. var color = colors[l];
  37642. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37643. }
  37644. if (index > 0) {
  37645. indices.push(idx - 1);
  37646. indices.push(idx);
  37647. }
  37648. idx++;
  37649. }
  37650. }
  37651. var vertexData = new VertexData();
  37652. vertexData.indices = indices;
  37653. vertexData.positions = positions;
  37654. if (colors) {
  37655. vertexData.colors = vertexColors;
  37656. }
  37657. return vertexData;
  37658. };
  37659. /**
  37660. * Create the VertexData for a DashedLines
  37661. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37662. * - points an array successive Vector3
  37663. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37664. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37665. * - dashNb the intended total number of dashes, optional, default 200
  37666. * @returns the VertexData for the DashedLines
  37667. */
  37668. VertexData.CreateDashedLines = function (options) {
  37669. var dashSize = options.dashSize || 3;
  37670. var gapSize = options.gapSize || 1;
  37671. var dashNb = options.dashNb || 200;
  37672. var points = options.points;
  37673. var positions = new Array();
  37674. var indices = new Array();
  37675. var curvect = BABYLON.Vector3.Zero();
  37676. var lg = 0;
  37677. var nb = 0;
  37678. var shft = 0;
  37679. var dashshft = 0;
  37680. var curshft = 0;
  37681. var idx = 0;
  37682. var i = 0;
  37683. for (i = 0; i < points.length - 1; i++) {
  37684. points[i + 1].subtractToRef(points[i], curvect);
  37685. lg += curvect.length();
  37686. }
  37687. shft = lg / dashNb;
  37688. dashshft = dashSize * shft / (dashSize + gapSize);
  37689. for (i = 0; i < points.length - 1; i++) {
  37690. points[i + 1].subtractToRef(points[i], curvect);
  37691. nb = Math.floor(curvect.length() / shft);
  37692. curvect.normalize();
  37693. for (var j = 0; j < nb; j++) {
  37694. curshft = shft * j;
  37695. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37696. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37697. indices.push(idx, idx + 1);
  37698. idx += 2;
  37699. }
  37700. }
  37701. // Result
  37702. var vertexData = new VertexData();
  37703. vertexData.positions = positions;
  37704. vertexData.indices = indices;
  37705. return vertexData;
  37706. };
  37707. /**
  37708. * Creates the VertexData for a Ground
  37709. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37710. * - width the width (x direction) of the ground, optional, default 1
  37711. * - height the height (z direction) of the ground, optional, default 1
  37712. * - subdivisions the number of subdivisions per side, optional, default 1
  37713. * @returns the VertexData of the Ground
  37714. */
  37715. VertexData.CreateGround = function (options) {
  37716. var indices = [];
  37717. var positions = [];
  37718. var normals = [];
  37719. var uvs = [];
  37720. var row, col;
  37721. var width = options.width || 1;
  37722. var height = options.height || 1;
  37723. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37724. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37725. for (row = 0; row <= subdivisionsY; row++) {
  37726. for (col = 0; col <= subdivisionsX; col++) {
  37727. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37728. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37729. positions.push(position.x, position.y, position.z);
  37730. normals.push(normal.x, normal.y, normal.z);
  37731. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37732. }
  37733. }
  37734. for (row = 0; row < subdivisionsY; row++) {
  37735. for (col = 0; col < subdivisionsX; col++) {
  37736. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37737. indices.push(col + 1 + row * (subdivisionsX + 1));
  37738. indices.push(col + row * (subdivisionsX + 1));
  37739. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37740. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37741. indices.push(col + row * (subdivisionsX + 1));
  37742. }
  37743. }
  37744. // Result
  37745. var vertexData = new VertexData();
  37746. vertexData.indices = indices;
  37747. vertexData.positions = positions;
  37748. vertexData.normals = normals;
  37749. vertexData.uvs = uvs;
  37750. return vertexData;
  37751. };
  37752. /**
  37753. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37754. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37755. * * xmin the ground minimum X coordinate, optional, default -1
  37756. * * zmin the ground minimum Z coordinate, optional, default -1
  37757. * * xmax the ground maximum X coordinate, optional, default 1
  37758. * * zmax the ground maximum Z coordinate, optional, default 1
  37759. * * 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}
  37760. * * 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}
  37761. * @returns the VertexData of the TiledGround
  37762. */
  37763. VertexData.CreateTiledGround = function (options) {
  37764. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37765. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37766. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37767. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37768. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37769. var precision = options.precision || { w: 1, h: 1 };
  37770. var indices = new Array();
  37771. var positions = new Array();
  37772. var normals = new Array();
  37773. var uvs = new Array();
  37774. var row, col, tileRow, tileCol;
  37775. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37776. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37777. precision.w = (precision.w < 1) ? 1 : precision.w;
  37778. precision.h = (precision.h < 1) ? 1 : precision.h;
  37779. var tileSize = {
  37780. 'w': (xmax - xmin) / subdivisions.w,
  37781. 'h': (zmax - zmin) / subdivisions.h
  37782. };
  37783. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37784. // Indices
  37785. var base = positions.length / 3;
  37786. var rowLength = precision.w + 1;
  37787. for (row = 0; row < precision.h; row++) {
  37788. for (col = 0; col < precision.w; col++) {
  37789. var square = [
  37790. base + col + row * rowLength,
  37791. base + (col + 1) + row * rowLength,
  37792. base + (col + 1) + (row + 1) * rowLength,
  37793. base + col + (row + 1) * rowLength
  37794. ];
  37795. indices.push(square[1]);
  37796. indices.push(square[2]);
  37797. indices.push(square[3]);
  37798. indices.push(square[0]);
  37799. indices.push(square[1]);
  37800. indices.push(square[3]);
  37801. }
  37802. }
  37803. // Position, normals and uvs
  37804. var position = BABYLON.Vector3.Zero();
  37805. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37806. for (row = 0; row <= precision.h; row++) {
  37807. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37808. for (col = 0; col <= precision.w; col++) {
  37809. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37810. position.y = 0;
  37811. positions.push(position.x, position.y, position.z);
  37812. normals.push(normal.x, normal.y, normal.z);
  37813. uvs.push(col / precision.w, row / precision.h);
  37814. }
  37815. }
  37816. }
  37817. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37818. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37819. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37820. }
  37821. }
  37822. // Result
  37823. var vertexData = new VertexData();
  37824. vertexData.indices = indices;
  37825. vertexData.positions = positions;
  37826. vertexData.normals = normals;
  37827. vertexData.uvs = uvs;
  37828. return vertexData;
  37829. };
  37830. /**
  37831. * Creates the VertexData of the Ground designed from a heightmap
  37832. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37833. * * width the width (x direction) of the ground
  37834. * * height the height (z direction) of the ground
  37835. * * subdivisions the number of subdivisions per side
  37836. * * minHeight the minimum altitude on the ground, optional, default 0
  37837. * * maxHeight the maximum altitude on the ground, optional default 1
  37838. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37839. * * buffer the array holding the image color data
  37840. * * bufferWidth the width of image
  37841. * * bufferHeight the height of image
  37842. * @returns the VertexData of the Ground designed from a heightmap
  37843. */
  37844. VertexData.CreateGroundFromHeightMap = function (options) {
  37845. var indices = [];
  37846. var positions = [];
  37847. var normals = [];
  37848. var uvs = [];
  37849. var row, col;
  37850. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37851. // Vertices
  37852. for (row = 0; row <= options.subdivisions; row++) {
  37853. for (col = 0; col <= options.subdivisions; col++) {
  37854. 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));
  37855. // Compute height
  37856. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37857. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37858. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37859. var r = options.buffer[pos] / 255.0;
  37860. var g = options.buffer[pos + 1] / 255.0;
  37861. var b = options.buffer[pos + 2] / 255.0;
  37862. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37863. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37864. // Add vertex
  37865. positions.push(position.x, position.y, position.z);
  37866. normals.push(0, 0, 0);
  37867. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37868. }
  37869. }
  37870. // Indices
  37871. for (row = 0; row < options.subdivisions; row++) {
  37872. for (col = 0; col < options.subdivisions; col++) {
  37873. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37874. indices.push(col + 1 + row * (options.subdivisions + 1));
  37875. indices.push(col + row * (options.subdivisions + 1));
  37876. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37877. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37878. indices.push(col + row * (options.subdivisions + 1));
  37879. }
  37880. }
  37881. // Normals
  37882. VertexData.ComputeNormals(positions, indices, normals);
  37883. // Result
  37884. var vertexData = new VertexData();
  37885. vertexData.indices = indices;
  37886. vertexData.positions = positions;
  37887. vertexData.normals = normals;
  37888. vertexData.uvs = uvs;
  37889. return vertexData;
  37890. };
  37891. /**
  37892. * Creates the VertexData for a Plane
  37893. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37894. * * size sets the width and height of the plane to the value of size, optional default 1
  37895. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37896. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37897. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37898. * * 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)
  37899. * * 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)
  37900. * @returns the VertexData of the box
  37901. */
  37902. VertexData.CreatePlane = function (options) {
  37903. var indices = [];
  37904. var positions = [];
  37905. var normals = [];
  37906. var uvs = [];
  37907. var width = options.width || options.size || 1;
  37908. var height = options.height || options.size || 1;
  37909. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37910. // Vertices
  37911. var halfWidth = width / 2.0;
  37912. var halfHeight = height / 2.0;
  37913. positions.push(-halfWidth, -halfHeight, 0);
  37914. normals.push(0, 0, -1.0);
  37915. uvs.push(0.0, 0.0);
  37916. positions.push(halfWidth, -halfHeight, 0);
  37917. normals.push(0, 0, -1.0);
  37918. uvs.push(1.0, 0.0);
  37919. positions.push(halfWidth, halfHeight, 0);
  37920. normals.push(0, 0, -1.0);
  37921. uvs.push(1.0, 1.0);
  37922. positions.push(-halfWidth, halfHeight, 0);
  37923. normals.push(0, 0, -1.0);
  37924. uvs.push(0.0, 1.0);
  37925. // Indices
  37926. indices.push(0);
  37927. indices.push(1);
  37928. indices.push(2);
  37929. indices.push(0);
  37930. indices.push(2);
  37931. indices.push(3);
  37932. // Sides
  37933. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37934. // Result
  37935. var vertexData = new VertexData();
  37936. vertexData.indices = indices;
  37937. vertexData.positions = positions;
  37938. vertexData.normals = normals;
  37939. vertexData.uvs = uvs;
  37940. return vertexData;
  37941. };
  37942. /**
  37943. * Creates the VertexData of the Disc or regular Polygon
  37944. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37945. * * radius the radius of the disc, optional default 0.5
  37946. * * tessellation the number of polygon sides, optional, default 64
  37947. * * 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
  37948. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37949. * * 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)
  37950. * * 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)
  37951. * @returns the VertexData of the box
  37952. */
  37953. VertexData.CreateDisc = function (options) {
  37954. var positions = new Array();
  37955. var indices = new Array();
  37956. var normals = new Array();
  37957. var uvs = new Array();
  37958. var radius = options.radius || 0.5;
  37959. var tessellation = options.tessellation || 64;
  37960. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37961. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37962. // positions and uvs
  37963. positions.push(0, 0, 0); // disc center first
  37964. uvs.push(0.5, 0.5);
  37965. var theta = Math.PI * 2 * arc;
  37966. var step = theta / tessellation;
  37967. for (var a = 0; a < theta; a += step) {
  37968. var x = Math.cos(a);
  37969. var y = Math.sin(a);
  37970. var u = (x + 1) / 2;
  37971. var v = (1 - y) / 2;
  37972. positions.push(radius * x, radius * y, 0);
  37973. uvs.push(u, v);
  37974. }
  37975. if (arc === 1) {
  37976. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37977. uvs.push(uvs[2], uvs[3]);
  37978. }
  37979. //indices
  37980. var vertexNb = positions.length / 3;
  37981. for (var i = 1; i < vertexNb - 1; i++) {
  37982. indices.push(i + 1, 0, i);
  37983. }
  37984. // result
  37985. VertexData.ComputeNormals(positions, indices, normals);
  37986. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37987. var vertexData = new VertexData();
  37988. vertexData.indices = indices;
  37989. vertexData.positions = positions;
  37990. vertexData.normals = normals;
  37991. vertexData.uvs = uvs;
  37992. return vertexData;
  37993. };
  37994. /**
  37995. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37996. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37997. * @param polygon a mesh built from polygonTriangulation.build()
  37998. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37999. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38000. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38001. * @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)
  38002. * @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)
  38003. * @returns the VertexData of the Polygon
  38004. */
  38005. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38006. var faceUV = fUV || new Array(3);
  38007. var faceColors = fColors;
  38008. var colors = [];
  38009. // default face colors and UV if undefined
  38010. for (var f = 0; f < 3; f++) {
  38011. if (faceUV[f] === undefined) {
  38012. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38013. }
  38014. if (faceColors && faceColors[f] === undefined) {
  38015. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38016. }
  38017. }
  38018. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38019. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38020. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38021. var indices = polygon.getIndices();
  38022. // set face colours and textures
  38023. var idx = 0;
  38024. var face = 0;
  38025. for (var index = 0; index < normals.length; index += 3) {
  38026. //Edge Face no. 1
  38027. if (Math.abs(normals[index + 1]) < 0.001) {
  38028. face = 1;
  38029. }
  38030. //Top Face no. 0
  38031. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38032. face = 0;
  38033. }
  38034. //Bottom Face no. 2
  38035. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38036. face = 2;
  38037. }
  38038. idx = index / 3;
  38039. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38040. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38041. if (faceColors) {
  38042. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38043. }
  38044. }
  38045. // sides
  38046. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38047. // Result
  38048. var vertexData = new VertexData();
  38049. vertexData.indices = indices;
  38050. vertexData.positions = positions;
  38051. vertexData.normals = normals;
  38052. vertexData.uvs = uvs;
  38053. if (faceColors) {
  38054. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38055. vertexData.colors = totalColors;
  38056. }
  38057. return vertexData;
  38058. };
  38059. /**
  38060. * Creates the VertexData of the IcoSphere
  38061. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38062. * * radius the radius of the IcoSphere, optional default 1
  38063. * * radiusX allows stretching in the x direction, optional, default radius
  38064. * * radiusY allows stretching in the y direction, optional, default radius
  38065. * * radiusZ allows stretching in the z direction, optional, default radius
  38066. * * flat when true creates a flat shaded mesh, optional, default true
  38067. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38068. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38069. * * 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)
  38070. * * 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)
  38071. * @returns the VertexData of the IcoSphere
  38072. */
  38073. VertexData.CreateIcoSphere = function (options) {
  38074. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38075. var radius = options.radius || 1;
  38076. var flat = (options.flat === undefined) ? true : options.flat;
  38077. var subdivisions = options.subdivisions || 4;
  38078. var radiusX = options.radiusX || radius;
  38079. var radiusY = options.radiusY || radius;
  38080. var radiusZ = options.radiusZ || radius;
  38081. var t = (1 + Math.sqrt(5)) / 2;
  38082. // 12 vertex x,y,z
  38083. var ico_vertices = [
  38084. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38085. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38086. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38087. ];
  38088. // index of 3 vertex makes a face of icopshere
  38089. var ico_indices = [
  38090. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38091. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38092. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38093. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38094. ];
  38095. // vertex for uv have aliased position, not for UV
  38096. var vertices_unalias_id = [
  38097. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38098. // vertex alias
  38099. 0,
  38100. 2,
  38101. 3,
  38102. 3,
  38103. 3,
  38104. 4,
  38105. 7,
  38106. 8,
  38107. 9,
  38108. 9,
  38109. 10,
  38110. 11 // 23: B + 12
  38111. ];
  38112. // uv as integer step (not pixels !)
  38113. var ico_vertexuv = [
  38114. 5, 1, 3, 1, 6, 4, 0, 0,
  38115. 5, 3, 4, 2, 2, 2, 4, 0,
  38116. 2, 0, 1, 1, 6, 0, 6, 2,
  38117. // vertex alias (for same vertex on different faces)
  38118. 0, 4,
  38119. 3, 3,
  38120. 4, 4,
  38121. 3, 1,
  38122. 4, 2,
  38123. 4, 4,
  38124. 0, 2,
  38125. 1, 1,
  38126. 2, 2,
  38127. 3, 3,
  38128. 1, 3,
  38129. 2, 4 // 23: B + 12
  38130. ];
  38131. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38132. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38133. // First island of uv mapping
  38134. // v = 4h 3+ 2
  38135. // v = 3h 9+ 4
  38136. // v = 2h 9+ 5 B
  38137. // v = 1h 9 1 0
  38138. // v = 0h 3 8 7 A
  38139. // u = 0 1 2 3 4 5 6 *a
  38140. // Second island of uv mapping
  38141. // v = 4h 0+ B+ 4+
  38142. // v = 3h A+ 2+
  38143. // v = 2h 7+ 6 3+
  38144. // v = 1h 8+ 3+
  38145. // v = 0h
  38146. // u = 0 1 2 3 4 5 6 *a
  38147. // Face layout on texture UV mapping
  38148. // ============
  38149. // \ 4 /\ 16 / ======
  38150. // \ / \ / /\ 11 /
  38151. // \/ 7 \/ / \ /
  38152. // ======= / 10 \/
  38153. // /\ 17 /\ =======
  38154. // / \ / \ \ 15 /\
  38155. // / 8 \/ 12 \ \ / \
  38156. // ============ \/ 6 \
  38157. // \ 18 /\ ============
  38158. // \ / \ \ 5 /\ 0 /
  38159. // \/ 13 \ \ / \ /
  38160. // ======= \/ 1 \/
  38161. // =============
  38162. // /\ 19 /\ 2 /\
  38163. // / \ / \ / \
  38164. // / 14 \/ 9 \/ 3 \
  38165. // ===================
  38166. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38167. var ustep = 138 / 1024;
  38168. var vstep = 239 / 1024;
  38169. var uoffset = 60 / 1024;
  38170. var voffset = 26 / 1024;
  38171. // Second island should have margin, not to touch the first island
  38172. // avoid any borderline artefact in pixel rounding
  38173. var island_u_offset = -40 / 1024;
  38174. var island_v_offset = +20 / 1024;
  38175. // face is either island 0 or 1 :
  38176. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38177. var island = [
  38178. 0, 0, 0, 0, 1,
  38179. 0, 0, 1, 1, 0,
  38180. 0, 0, 1, 1, 0,
  38181. 0, 1, 1, 1, 0 // 15 - 19
  38182. ];
  38183. var indices = new Array();
  38184. var positions = new Array();
  38185. var normals = new Array();
  38186. var uvs = new Array();
  38187. var current_indice = 0;
  38188. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38189. var face_vertex_pos = new Array(3);
  38190. var face_vertex_uv = new Array(3);
  38191. var v012;
  38192. for (v012 = 0; v012 < 3; v012++) {
  38193. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38194. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38195. }
  38196. // create all with normals
  38197. for (var face = 0; face < 20; face++) {
  38198. // 3 vertex per face
  38199. for (v012 = 0; v012 < 3; v012++) {
  38200. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38201. var v_id = ico_indices[3 * face + v012];
  38202. // vertex have 3D position (x,y,z)
  38203. 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]);
  38204. // Normalize to get normal, then scale to radius
  38205. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38206. // uv Coordinates from vertex ID
  38207. 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);
  38208. }
  38209. // Subdivide the face (interpolate pos, norm, uv)
  38210. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38211. // - norm is linear interpolation of vertex corner normal
  38212. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38213. // - uv is linear interpolation
  38214. //
  38215. // Topology is as below for sub-divide by 2
  38216. // vertex shown as v0,v1,v2
  38217. // interp index is i1 to progress in range [v0,v1[
  38218. // interp index is i2 to progress in range [v0,v2[
  38219. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38220. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38221. //
  38222. //
  38223. // i2 v2
  38224. // ^ ^
  38225. // / / \
  38226. // / / \
  38227. // / / \
  38228. // / / (0,1) \
  38229. // / #---------\
  38230. // / / \ (0,0)'/ \
  38231. // / / \ / \
  38232. // / / \ / \
  38233. // / / (0,0) \ / (1,0) \
  38234. // / #---------#---------\
  38235. // v0 v1
  38236. //
  38237. // --------------------> i1
  38238. //
  38239. // interp of (i1,i2):
  38240. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38241. // along i1 : lerp(x0,x1, i1/(S-i2))
  38242. //
  38243. // centroid of triangle is needed to get help normal computation
  38244. // (c1,c2) are used for centroid location
  38245. var interp_vertex = function (i1, i2, c1, c2) {
  38246. // vertex is interpolated from
  38247. // - face_vertex_pos[0..2]
  38248. // - face_vertex_uv[0..2]
  38249. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38250. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38251. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38252. pos_interp.normalize();
  38253. var vertex_normal;
  38254. if (flat) {
  38255. // in flat mode, recalculate normal as face centroid normal
  38256. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38257. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38258. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38259. }
  38260. else {
  38261. // in smooth mode, recalculate normal from each single vertex position
  38262. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38263. }
  38264. // Vertex normal need correction due to X,Y,Z radius scaling
  38265. vertex_normal.x /= radiusX;
  38266. vertex_normal.y /= radiusY;
  38267. vertex_normal.z /= radiusZ;
  38268. vertex_normal.normalize();
  38269. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38270. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38271. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38272. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38273. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38274. uvs.push(uv_interp.x, uv_interp.y);
  38275. // push each vertex has member of a face
  38276. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38277. indices.push(current_indice);
  38278. current_indice++;
  38279. };
  38280. for (var i2 = 0; i2 < subdivisions; i2++) {
  38281. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38282. // face : (i1,i2) for /\ :
  38283. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38284. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38285. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38286. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38287. if (i1 + i2 + 1 < subdivisions) {
  38288. // face : (i1,i2)' for \/ :
  38289. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38290. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38291. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38292. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38293. }
  38294. }
  38295. }
  38296. }
  38297. // Sides
  38298. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38299. // Result
  38300. var vertexData = new VertexData();
  38301. vertexData.indices = indices;
  38302. vertexData.positions = positions;
  38303. vertexData.normals = normals;
  38304. vertexData.uvs = uvs;
  38305. return vertexData;
  38306. };
  38307. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38308. /**
  38309. * Creates the VertexData for a Polyhedron
  38310. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38311. * * type provided types are:
  38312. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38313. * * 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)
  38314. * * size the size of the IcoSphere, optional default 1
  38315. * * sizeX allows stretching in the x direction, optional, default size
  38316. * * sizeY allows stretching in the y direction, optional, default size
  38317. * * sizeZ allows stretching in the z direction, optional, default size
  38318. * * 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
  38319. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38320. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38321. * * flat when true creates a flat shaded mesh, optional, default true
  38322. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38323. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38324. * * 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)
  38325. * * 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)
  38326. * @returns the VertexData of the Polyhedron
  38327. */
  38328. VertexData.CreatePolyhedron = function (options) {
  38329. // provided polyhedron types :
  38330. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38331. // 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)
  38332. var polyhedra = [];
  38333. 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]] };
  38334. 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]] };
  38335. polyhedra[2] = {
  38336. 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]],
  38337. 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]]
  38338. };
  38339. polyhedra[3] = {
  38340. 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]],
  38341. 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]]
  38342. };
  38343. polyhedra[4] = {
  38344. 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]],
  38345. 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]]
  38346. };
  38347. 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]] };
  38348. 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]] };
  38349. 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]] };
  38350. 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]] };
  38351. 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]] };
  38352. 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]] };
  38353. 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]] };
  38354. 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]] };
  38355. 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]] };
  38356. polyhedra[14] = {
  38357. 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]],
  38358. 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]]
  38359. };
  38360. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38361. var size = options.size;
  38362. var sizeX = options.sizeX || size || 1;
  38363. var sizeY = options.sizeY || size || 1;
  38364. var sizeZ = options.sizeZ || size || 1;
  38365. var data = options.custom || polyhedra[type];
  38366. var nbfaces = data.face.length;
  38367. var faceUV = options.faceUV || new Array(nbfaces);
  38368. var faceColors = options.faceColors;
  38369. var flat = (options.flat === undefined) ? true : options.flat;
  38370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38371. var positions = new Array();
  38372. var indices = new Array();
  38373. var normals = new Array();
  38374. var uvs = new Array();
  38375. var colors = new Array();
  38376. var index = 0;
  38377. var faceIdx = 0; // face cursor in the array "indexes"
  38378. var indexes = new Array();
  38379. var i = 0;
  38380. var f = 0;
  38381. var u, v, ang, x, y, tmp;
  38382. // default face colors and UV if undefined
  38383. if (flat) {
  38384. for (f = 0; f < nbfaces; f++) {
  38385. if (faceColors && faceColors[f] === undefined) {
  38386. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38387. }
  38388. if (faceUV && faceUV[f] === undefined) {
  38389. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38390. }
  38391. }
  38392. }
  38393. if (!flat) {
  38394. for (i = 0; i < data.vertex.length; i++) {
  38395. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38396. uvs.push(0, 0);
  38397. }
  38398. for (f = 0; f < nbfaces; f++) {
  38399. for (i = 0; i < data.face[f].length - 2; i++) {
  38400. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38401. }
  38402. }
  38403. }
  38404. else {
  38405. for (f = 0; f < nbfaces; f++) {
  38406. var fl = data.face[f].length; // number of vertices of the current face
  38407. ang = 2 * Math.PI / fl;
  38408. x = 0.5 * Math.tan(ang / 2);
  38409. y = 0.5;
  38410. // positions, uvs, colors
  38411. for (i = 0; i < fl; i++) {
  38412. // positions
  38413. 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);
  38414. indexes.push(index);
  38415. index++;
  38416. // uvs
  38417. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38418. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38419. uvs.push(u, v);
  38420. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38421. y = x * Math.sin(ang) + y * Math.cos(ang);
  38422. x = tmp;
  38423. // colors
  38424. if (faceColors) {
  38425. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38426. }
  38427. }
  38428. // indices from indexes
  38429. for (i = 0; i < fl - 2; i++) {
  38430. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38431. }
  38432. faceIdx += fl;
  38433. }
  38434. }
  38435. VertexData.ComputeNormals(positions, indices, normals);
  38436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38437. var vertexData = new VertexData();
  38438. vertexData.positions = positions;
  38439. vertexData.indices = indices;
  38440. vertexData.normals = normals;
  38441. vertexData.uvs = uvs;
  38442. if (faceColors && flat) {
  38443. vertexData.colors = colors;
  38444. }
  38445. return vertexData;
  38446. };
  38447. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38448. /**
  38449. * Creates the VertexData for a TorusKnot
  38450. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38451. * * radius the radius of the torus knot, optional, default 2
  38452. * * tube the thickness of the tube, optional, default 0.5
  38453. * * radialSegments the number of sides on each tube segments, optional, default 32
  38454. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38455. * * p the number of windings around the z axis, optional, default 2
  38456. * * q the number of windings around the x axis, optional, default 3
  38457. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38458. * * 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)
  38459. * * 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)
  38460. * @returns the VertexData of the Torus Knot
  38461. */
  38462. VertexData.CreateTorusKnot = function (options) {
  38463. var indices = new Array();
  38464. var positions = new Array();
  38465. var normals = new Array();
  38466. var uvs = new Array();
  38467. var radius = options.radius || 2;
  38468. var tube = options.tube || 0.5;
  38469. var radialSegments = options.radialSegments || 32;
  38470. var tubularSegments = options.tubularSegments || 32;
  38471. var p = options.p || 2;
  38472. var q = options.q || 3;
  38473. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38474. // Helper
  38475. var getPos = function (angle) {
  38476. var cu = Math.cos(angle);
  38477. var su = Math.sin(angle);
  38478. var quOverP = q / p * angle;
  38479. var cs = Math.cos(quOverP);
  38480. var tx = radius * (2 + cs) * 0.5 * cu;
  38481. var ty = radius * (2 + cs) * su * 0.5;
  38482. var tz = radius * Math.sin(quOverP) * 0.5;
  38483. return new BABYLON.Vector3(tx, ty, tz);
  38484. };
  38485. // Vertices
  38486. var i;
  38487. var j;
  38488. for (i = 0; i <= radialSegments; i++) {
  38489. var modI = i % radialSegments;
  38490. var u = modI / radialSegments * 2 * p * Math.PI;
  38491. var p1 = getPos(u);
  38492. var p2 = getPos(u + 0.01);
  38493. var tang = p2.subtract(p1);
  38494. var n = p2.add(p1);
  38495. var bitan = BABYLON.Vector3.Cross(tang, n);
  38496. n = BABYLON.Vector3.Cross(bitan, tang);
  38497. bitan.normalize();
  38498. n.normalize();
  38499. for (j = 0; j < tubularSegments; j++) {
  38500. var modJ = j % tubularSegments;
  38501. var v = modJ / tubularSegments * 2 * Math.PI;
  38502. var cx = -tube * Math.cos(v);
  38503. var cy = tube * Math.sin(v);
  38504. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38505. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38506. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38507. uvs.push(i / radialSegments);
  38508. uvs.push(j / tubularSegments);
  38509. }
  38510. }
  38511. for (i = 0; i < radialSegments; i++) {
  38512. for (j = 0; j < tubularSegments; j++) {
  38513. var jNext = (j + 1) % tubularSegments;
  38514. var a = i * tubularSegments + j;
  38515. var b = (i + 1) * tubularSegments + j;
  38516. var c = (i + 1) * tubularSegments + jNext;
  38517. var d = i * tubularSegments + jNext;
  38518. indices.push(d);
  38519. indices.push(b);
  38520. indices.push(a);
  38521. indices.push(d);
  38522. indices.push(c);
  38523. indices.push(b);
  38524. }
  38525. }
  38526. // Normals
  38527. VertexData.ComputeNormals(positions, indices, normals);
  38528. // Sides
  38529. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38530. // Result
  38531. var vertexData = new VertexData();
  38532. vertexData.indices = indices;
  38533. vertexData.positions = positions;
  38534. vertexData.normals = normals;
  38535. vertexData.uvs = uvs;
  38536. return vertexData;
  38537. };
  38538. // Tools
  38539. /**
  38540. * Compute normals for given positions and indices
  38541. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38542. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38543. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38544. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38545. * * facetNormals : optional array of facet normals (vector3)
  38546. * * facetPositions : optional array of facet positions (vector3)
  38547. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38548. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38549. * * bInfo : optional bounding info, required for facetPartitioning computation
  38550. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38551. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38552. * * useRightHandedSystem: optional boolean to for right handed system computation
  38553. * * depthSort : optional boolean to enable the facet depth sort computation
  38554. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38555. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38556. */
  38557. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38558. // temporary scalar variables
  38559. var index = 0; // facet index
  38560. var p1p2x = 0.0; // p1p2 vector x coordinate
  38561. var p1p2y = 0.0; // p1p2 vector y coordinate
  38562. var p1p2z = 0.0; // p1p2 vector z coordinate
  38563. var p3p2x = 0.0; // p3p2 vector x coordinate
  38564. var p3p2y = 0.0; // p3p2 vector y coordinate
  38565. var p3p2z = 0.0; // p3p2 vector z coordinate
  38566. var faceNormalx = 0.0; // facet normal x coordinate
  38567. var faceNormaly = 0.0; // facet normal y coordinate
  38568. var faceNormalz = 0.0; // facet normal z coordinate
  38569. var length = 0.0; // facet normal length before normalization
  38570. var v1x = 0; // vector1 x index in the positions array
  38571. var v1y = 0; // vector1 y index in the positions array
  38572. var v1z = 0; // vector1 z index in the positions array
  38573. var v2x = 0; // vector2 x index in the positions array
  38574. var v2y = 0; // vector2 y index in the positions array
  38575. var v2z = 0; // vector2 z index in the positions array
  38576. var v3x = 0; // vector3 x index in the positions array
  38577. var v3y = 0; // vector3 y index in the positions array
  38578. var v3z = 0; // vector3 z index in the positions array
  38579. var computeFacetNormals = false;
  38580. var computeFacetPositions = false;
  38581. var computeFacetPartitioning = false;
  38582. var computeDepthSort = false;
  38583. var faceNormalSign = 1;
  38584. var ratio = 0;
  38585. var distanceTo = null;
  38586. if (options) {
  38587. computeFacetNormals = (options.facetNormals) ? true : false;
  38588. computeFacetPositions = (options.facetPositions) ? true : false;
  38589. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38590. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38591. ratio = options.ratio || 0;
  38592. computeDepthSort = (options.depthSort) ? true : false;
  38593. distanceTo = (options.distanceTo);
  38594. if (computeDepthSort) {
  38595. if (distanceTo === undefined) {
  38596. distanceTo = BABYLON.Vector3.Zero();
  38597. }
  38598. var depthSortedFacets = options.depthSortedFacets;
  38599. }
  38600. }
  38601. // facetPartitioning reinit if needed
  38602. var xSubRatio = 0;
  38603. var ySubRatio = 0;
  38604. var zSubRatio = 0;
  38605. var subSq = 0;
  38606. if (computeFacetPartitioning && options && options.bbSize) {
  38607. var ox = 0; // X partitioning index for facet position
  38608. var oy = 0; // Y partinioning index for facet position
  38609. var oz = 0; // Z partinioning index for facet position
  38610. var b1x = 0; // X partitioning index for facet v1 vertex
  38611. var b1y = 0; // Y partitioning index for facet v1 vertex
  38612. var b1z = 0; // z partitioning index for facet v1 vertex
  38613. var b2x = 0; // X partitioning index for facet v2 vertex
  38614. var b2y = 0; // Y partitioning index for facet v2 vertex
  38615. var b2z = 0; // Z partitioning index for facet v2 vertex
  38616. var b3x = 0; // X partitioning index for facet v3 vertex
  38617. var b3y = 0; // Y partitioning index for facet v3 vertex
  38618. var b3z = 0; // Z partitioning index for facet v3 vertex
  38619. var block_idx_o = 0; // facet barycenter block index
  38620. var block_idx_v1 = 0; // v1 vertex block index
  38621. var block_idx_v2 = 0; // v2 vertex block index
  38622. var block_idx_v3 = 0; // v3 vertex block index
  38623. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38624. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38625. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38626. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38627. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38628. subSq = options.subDiv.max * options.subDiv.max;
  38629. options.facetPartitioning.length = 0;
  38630. }
  38631. // reset the normals
  38632. for (index = 0; index < positions.length; index++) {
  38633. normals[index] = 0.0;
  38634. }
  38635. // Loop : 1 indice triplet = 1 facet
  38636. var nbFaces = (indices.length / 3) | 0;
  38637. for (index = 0; index < nbFaces; index++) {
  38638. // get the indexes of the coordinates of each vertex of the facet
  38639. v1x = indices[index * 3] * 3;
  38640. v1y = v1x + 1;
  38641. v1z = v1x + 2;
  38642. v2x = indices[index * 3 + 1] * 3;
  38643. v2y = v2x + 1;
  38644. v2z = v2x + 2;
  38645. v3x = indices[index * 3 + 2] * 3;
  38646. v3y = v3x + 1;
  38647. v3z = v3x + 2;
  38648. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38649. p1p2y = positions[v1y] - positions[v2y];
  38650. p1p2z = positions[v1z] - positions[v2z];
  38651. p3p2x = positions[v3x] - positions[v2x];
  38652. p3p2y = positions[v3y] - positions[v2y];
  38653. p3p2z = positions[v3z] - positions[v2z];
  38654. // compute the face normal with the cross product
  38655. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38656. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38657. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38658. // normalize this normal and store it in the array facetData
  38659. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38660. length = (length === 0) ? 1.0 : length;
  38661. faceNormalx /= length;
  38662. faceNormaly /= length;
  38663. faceNormalz /= length;
  38664. if (computeFacetNormals && options) {
  38665. options.facetNormals[index].x = faceNormalx;
  38666. options.facetNormals[index].y = faceNormaly;
  38667. options.facetNormals[index].z = faceNormalz;
  38668. }
  38669. if (computeFacetPositions && options) {
  38670. // compute and the facet barycenter coordinates in the array facetPositions
  38671. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38672. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38673. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38674. }
  38675. if (computeFacetPartitioning && options) {
  38676. // store the facet indexes in arrays in the main facetPartitioning array :
  38677. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38678. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38679. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38680. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38681. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38682. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38683. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38684. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38685. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38686. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38687. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38688. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38689. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38690. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38691. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38692. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38693. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38694. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38695. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38696. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38697. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38698. // push each facet index in each block containing the vertex
  38699. options.facetPartitioning[block_idx_v1].push(index);
  38700. if (block_idx_v2 != block_idx_v1) {
  38701. options.facetPartitioning[block_idx_v2].push(index);
  38702. }
  38703. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38704. options.facetPartitioning[block_idx_v3].push(index);
  38705. }
  38706. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38707. options.facetPartitioning[block_idx_o].push(index);
  38708. }
  38709. }
  38710. if (computeDepthSort && options && options.facetPositions) {
  38711. var dsf = depthSortedFacets[index];
  38712. dsf.ind = index * 3;
  38713. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38714. }
  38715. // compute the normals anyway
  38716. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38717. normals[v1y] += faceNormaly;
  38718. normals[v1z] += faceNormalz;
  38719. normals[v2x] += faceNormalx;
  38720. normals[v2y] += faceNormaly;
  38721. normals[v2z] += faceNormalz;
  38722. normals[v3x] += faceNormalx;
  38723. normals[v3y] += faceNormaly;
  38724. normals[v3z] += faceNormalz;
  38725. }
  38726. // last normalization of each normal
  38727. for (index = 0; index < normals.length / 3; index++) {
  38728. faceNormalx = normals[index * 3];
  38729. faceNormaly = normals[index * 3 + 1];
  38730. faceNormalz = normals[index * 3 + 2];
  38731. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38732. length = (length === 0) ? 1.0 : length;
  38733. faceNormalx /= length;
  38734. faceNormaly /= length;
  38735. faceNormalz /= length;
  38736. normals[index * 3] = faceNormalx;
  38737. normals[index * 3 + 1] = faceNormaly;
  38738. normals[index * 3 + 2] = faceNormalz;
  38739. }
  38740. };
  38741. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38742. var li = indices.length;
  38743. var ln = normals.length;
  38744. var i;
  38745. var n;
  38746. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38747. switch (sideOrientation) {
  38748. case BABYLON.Mesh.FRONTSIDE:
  38749. // nothing changed
  38750. break;
  38751. case BABYLON.Mesh.BACKSIDE:
  38752. var tmp;
  38753. // indices
  38754. for (i = 0; i < li; i += 3) {
  38755. tmp = indices[i];
  38756. indices[i] = indices[i + 2];
  38757. indices[i + 2] = tmp;
  38758. }
  38759. // normals
  38760. for (n = 0; n < ln; n++) {
  38761. normals[n] = -normals[n];
  38762. }
  38763. break;
  38764. case BABYLON.Mesh.DOUBLESIDE:
  38765. // positions
  38766. var lp = positions.length;
  38767. var l = lp / 3;
  38768. for (var p = 0; p < lp; p++) {
  38769. positions[lp + p] = positions[p];
  38770. }
  38771. // indices
  38772. for (i = 0; i < li; i += 3) {
  38773. indices[i + li] = indices[i + 2] + l;
  38774. indices[i + 1 + li] = indices[i + 1] + l;
  38775. indices[i + 2 + li] = indices[i] + l;
  38776. }
  38777. // normals
  38778. for (n = 0; n < ln; n++) {
  38779. normals[ln + n] = -normals[n];
  38780. }
  38781. // uvs
  38782. var lu = uvs.length;
  38783. var u = 0;
  38784. for (u = 0; u < lu; u++) {
  38785. uvs[u + lu] = uvs[u];
  38786. }
  38787. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38788. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38789. u = 0;
  38790. for (i = 0; i < lu / 2; i++) {
  38791. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38792. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38793. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38794. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38795. u += 2;
  38796. }
  38797. break;
  38798. }
  38799. };
  38800. /**
  38801. * Applies VertexData created from the imported parameters to the geometry
  38802. * @param parsedVertexData the parsed data from an imported file
  38803. * @param geometry the geometry to apply the VertexData to
  38804. */
  38805. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38806. var vertexData = new VertexData();
  38807. // positions
  38808. var positions = parsedVertexData.positions;
  38809. if (positions) {
  38810. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38811. }
  38812. // normals
  38813. var normals = parsedVertexData.normals;
  38814. if (normals) {
  38815. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38816. }
  38817. // tangents
  38818. var tangents = parsedVertexData.tangents;
  38819. if (tangents) {
  38820. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38821. }
  38822. // uvs
  38823. var uvs = parsedVertexData.uvs;
  38824. if (uvs) {
  38825. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38826. }
  38827. // uv2s
  38828. var uv2s = parsedVertexData.uv2s;
  38829. if (uv2s) {
  38830. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38831. }
  38832. // uv3s
  38833. var uv3s = parsedVertexData.uv3s;
  38834. if (uv3s) {
  38835. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38836. }
  38837. // uv4s
  38838. var uv4s = parsedVertexData.uv4s;
  38839. if (uv4s) {
  38840. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38841. }
  38842. // uv5s
  38843. var uv5s = parsedVertexData.uv5s;
  38844. if (uv5s) {
  38845. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38846. }
  38847. // uv6s
  38848. var uv6s = parsedVertexData.uv6s;
  38849. if (uv6s) {
  38850. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38851. }
  38852. // colors
  38853. var colors = parsedVertexData.colors;
  38854. if (colors) {
  38855. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38856. }
  38857. // matricesIndices
  38858. var matricesIndices = parsedVertexData.matricesIndices;
  38859. if (matricesIndices) {
  38860. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38861. }
  38862. // matricesWeights
  38863. var matricesWeights = parsedVertexData.matricesWeights;
  38864. if (matricesWeights) {
  38865. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38866. }
  38867. // indices
  38868. var indices = parsedVertexData.indices;
  38869. if (indices) {
  38870. vertexData.indices = indices;
  38871. }
  38872. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38873. };
  38874. return VertexData;
  38875. }());
  38876. BABYLON.VertexData = VertexData;
  38877. })(BABYLON || (BABYLON = {}));
  38878. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38879. var BABYLON;
  38880. (function (BABYLON) {
  38881. /**
  38882. * Class used to store geometry data (vertex buffers + index buffer)
  38883. */
  38884. var Geometry = /** @class */ (function () {
  38885. /**
  38886. * Creates a new geometry
  38887. * @param id defines the unique ID
  38888. * @param scene defines the hosting scene
  38889. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38890. * @param updatable defines if geometry must be updatable (false by default)
  38891. * @param mesh defines the mesh that will be associated with the geometry
  38892. */
  38893. function Geometry(id, scene, vertexData, updatable, mesh) {
  38894. if (updatable === void 0) { updatable = false; }
  38895. if (mesh === void 0) { mesh = null; }
  38896. /**
  38897. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38898. */
  38899. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38900. this._totalVertices = 0;
  38901. this._isDisposed = false;
  38902. this._indexBufferIsUpdatable = false;
  38903. this.id = id;
  38904. this._engine = scene.getEngine();
  38905. this._meshes = [];
  38906. this._scene = scene;
  38907. //Init vertex buffer cache
  38908. this._vertexBuffers = {};
  38909. this._indices = [];
  38910. this._updatable = updatable;
  38911. // vertexData
  38912. if (vertexData) {
  38913. this.setAllVerticesData(vertexData, updatable);
  38914. }
  38915. else {
  38916. this._totalVertices = 0;
  38917. this._indices = [];
  38918. }
  38919. if (this._engine.getCaps().vertexArrayObject) {
  38920. this._vertexArrayObjects = {};
  38921. }
  38922. // applyToMesh
  38923. if (mesh) {
  38924. if (mesh.getClassName() === "LinesMesh") {
  38925. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38926. this._updateExtend();
  38927. }
  38928. this.applyToMesh(mesh);
  38929. mesh.computeWorldMatrix(true);
  38930. }
  38931. }
  38932. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38933. /**
  38934. * 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
  38935. */
  38936. get: function () {
  38937. return this._boundingBias;
  38938. },
  38939. /**
  38940. * 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
  38941. */
  38942. set: function (value) {
  38943. if (this._boundingBias && this._boundingBias.equals(value)) {
  38944. return;
  38945. }
  38946. this._boundingBias = value.clone();
  38947. this._updateBoundingInfo(true, null);
  38948. },
  38949. enumerable: true,
  38950. configurable: true
  38951. });
  38952. /**
  38953. * Static function used to attach a new empty geometry to a mesh
  38954. * @param mesh defines the mesh to attach the geometry to
  38955. * @returns the new {BABYLON.Geometry}
  38956. */
  38957. Geometry.CreateGeometryForMesh = function (mesh) {
  38958. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38959. geometry.applyToMesh(mesh);
  38960. return geometry;
  38961. };
  38962. Object.defineProperty(Geometry.prototype, "extend", {
  38963. /**
  38964. * Gets the current extend of the geometry
  38965. */
  38966. get: function () {
  38967. return this._extend;
  38968. },
  38969. enumerable: true,
  38970. configurable: true
  38971. });
  38972. /**
  38973. * Gets the hosting scene
  38974. * @returns the hosting {BABYLON.Scene}
  38975. */
  38976. Geometry.prototype.getScene = function () {
  38977. return this._scene;
  38978. };
  38979. /**
  38980. * Gets the hosting engine
  38981. * @returns the hosting {BABYLON.Engine}
  38982. */
  38983. Geometry.prototype.getEngine = function () {
  38984. return this._engine;
  38985. };
  38986. /**
  38987. * Defines if the geometry is ready to use
  38988. * @returns true if the geometry is ready to be used
  38989. */
  38990. Geometry.prototype.isReady = function () {
  38991. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38992. };
  38993. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38994. /**
  38995. * Gets a value indicating that the geometry should not be serialized
  38996. */
  38997. get: function () {
  38998. for (var index = 0; index < this._meshes.length; index++) {
  38999. if (!this._meshes[index].doNotSerialize) {
  39000. return false;
  39001. }
  39002. }
  39003. return true;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. /** @hidden */
  39009. Geometry.prototype._rebuild = function () {
  39010. if (this._vertexArrayObjects) {
  39011. this._vertexArrayObjects = {};
  39012. }
  39013. // Index buffer
  39014. if (this._meshes.length !== 0 && this._indices) {
  39015. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39016. }
  39017. // Vertex buffers
  39018. for (var key in this._vertexBuffers) {
  39019. var vertexBuffer = this._vertexBuffers[key];
  39020. vertexBuffer._rebuild();
  39021. }
  39022. };
  39023. /**
  39024. * Affects all gemetry data in one call
  39025. * @param vertexData defines the geometry data
  39026. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39027. */
  39028. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39029. vertexData.applyToGeometry(this, updatable);
  39030. this.notifyUpdate();
  39031. };
  39032. /**
  39033. * Set specific vertex data
  39034. * @param kind defines the data kind (Position, normal, etc...)
  39035. * @param data defines the vertex data to use
  39036. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39037. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39038. */
  39039. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39040. if (updatable === void 0) { updatable = false; }
  39041. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39042. this.setVerticesBuffer(buffer);
  39043. };
  39044. /**
  39045. * Removes a specific vertex data
  39046. * @param kind defines the data kind (Position, normal, etc...)
  39047. */
  39048. Geometry.prototype.removeVerticesData = function (kind) {
  39049. if (this._vertexBuffers[kind]) {
  39050. this._vertexBuffers[kind].dispose();
  39051. delete this._vertexBuffers[kind];
  39052. }
  39053. };
  39054. /**
  39055. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39056. * @param buffer defines the vertex buffer to use
  39057. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39058. */
  39059. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39060. if (totalVertices === void 0) { totalVertices = null; }
  39061. var kind = buffer.getKind();
  39062. if (this._vertexBuffers[kind]) {
  39063. this._vertexBuffers[kind].dispose();
  39064. }
  39065. this._vertexBuffers[kind] = buffer;
  39066. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39067. var data = buffer.getData();
  39068. if (totalVertices != null) {
  39069. this._totalVertices = totalVertices;
  39070. }
  39071. else {
  39072. if (data != null) {
  39073. this._totalVertices = data.length / (buffer.byteStride / 4);
  39074. }
  39075. }
  39076. this._updateExtend(data);
  39077. this._resetPointsArrayCache();
  39078. var meshes = this._meshes;
  39079. var numOfMeshes = meshes.length;
  39080. for (var index = 0; index < numOfMeshes; index++) {
  39081. var mesh = meshes[index];
  39082. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39083. mesh._createGlobalSubMesh(false);
  39084. mesh.computeWorldMatrix(true);
  39085. }
  39086. }
  39087. this.notifyUpdate(kind);
  39088. if (this._vertexArrayObjects) {
  39089. this._disposeVertexArrayObjects();
  39090. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39091. }
  39092. };
  39093. /**
  39094. * Update a specific vertex buffer
  39095. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39096. * It will do nothing if the buffer is not updatable
  39097. * @param kind defines the data kind (Position, normal, etc...)
  39098. * @param data defines the data to use
  39099. * @param offset defines the offset in the target buffer where to store the data
  39100. * @param useBytes set to true if the offset is in bytes
  39101. */
  39102. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39103. if (useBytes === void 0) { useBytes = false; }
  39104. var vertexBuffer = this.getVertexBuffer(kind);
  39105. if (!vertexBuffer) {
  39106. return;
  39107. }
  39108. vertexBuffer.updateDirectly(data, offset, useBytes);
  39109. this.notifyUpdate(kind);
  39110. };
  39111. /**
  39112. * Update a specific vertex buffer
  39113. * This function will create a new buffer if the current one is not updatable
  39114. * @param kind defines the data kind (Position, normal, etc...)
  39115. * @param data defines the data to use
  39116. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39117. */
  39118. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39119. if (updateExtends === void 0) { updateExtends = false; }
  39120. var vertexBuffer = this.getVertexBuffer(kind);
  39121. if (!vertexBuffer) {
  39122. return;
  39123. }
  39124. vertexBuffer.update(data);
  39125. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39126. this._updateBoundingInfo(updateExtends, data);
  39127. }
  39128. this.notifyUpdate(kind);
  39129. };
  39130. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39131. if (updateExtends) {
  39132. this._updateExtend(data);
  39133. }
  39134. var meshes = this._meshes;
  39135. var numOfMeshes = meshes.length;
  39136. this._resetPointsArrayCache();
  39137. for (var index = 0; index < numOfMeshes; index++) {
  39138. var mesh = meshes[index];
  39139. if (updateExtends) {
  39140. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39141. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39142. var subMesh = mesh.subMeshes[subIndex];
  39143. subMesh.refreshBoundingInfo();
  39144. }
  39145. }
  39146. }
  39147. };
  39148. /** @hidden */
  39149. Geometry.prototype._bind = function (effect, indexToBind) {
  39150. if (!effect) {
  39151. return;
  39152. }
  39153. if (indexToBind === undefined) {
  39154. indexToBind = this._indexBuffer;
  39155. }
  39156. var vbs = this.getVertexBuffers();
  39157. if (!vbs) {
  39158. return;
  39159. }
  39160. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39161. this._engine.bindBuffers(vbs, indexToBind, effect);
  39162. return;
  39163. }
  39164. // Using VAO
  39165. if (!this._vertexArrayObjects[effect.key]) {
  39166. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39167. }
  39168. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39169. };
  39170. /**
  39171. * Gets total number of vertices
  39172. * @returns the total number of vertices
  39173. */
  39174. Geometry.prototype.getTotalVertices = function () {
  39175. if (!this.isReady()) {
  39176. return 0;
  39177. }
  39178. return this._totalVertices;
  39179. };
  39180. /**
  39181. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39182. * @param kind defines the data kind (Position, normal, etc...)
  39183. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39184. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39185. * @returns a float array containing vertex data
  39186. */
  39187. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39188. var vertexBuffer = this.getVertexBuffer(kind);
  39189. if (!vertexBuffer) {
  39190. return null;
  39191. }
  39192. var data = vertexBuffer.getData();
  39193. if (!data) {
  39194. return null;
  39195. }
  39196. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39197. var count = this._totalVertices * vertexBuffer.getSize();
  39198. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39199. var copy_1 = new Array(count);
  39200. vertexBuffer.forEach(count, function (value, index) {
  39201. copy_1[index] = value;
  39202. });
  39203. return copy_1;
  39204. }
  39205. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39206. if (data instanceof Array) {
  39207. var offset = vertexBuffer.byteOffset / 4;
  39208. return BABYLON.Tools.Slice(data, offset, offset + count);
  39209. }
  39210. else if (data instanceof ArrayBuffer) {
  39211. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39212. }
  39213. else {
  39214. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39215. }
  39216. }
  39217. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39218. return BABYLON.Tools.Slice(data);
  39219. }
  39220. return data;
  39221. };
  39222. /**
  39223. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39224. * @param kind defines the data kind (Position, normal, etc...)
  39225. * @returns true if the vertex buffer with the specified kind is updatable
  39226. */
  39227. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39228. var vb = this._vertexBuffers[kind];
  39229. if (!vb) {
  39230. return false;
  39231. }
  39232. return vb.isUpdatable();
  39233. };
  39234. /**
  39235. * Gets a specific vertex buffer
  39236. * @param kind defines the data kind (Position, normal, etc...)
  39237. * @returns a {BABYLON.VertexBuffer}
  39238. */
  39239. Geometry.prototype.getVertexBuffer = function (kind) {
  39240. if (!this.isReady()) {
  39241. return null;
  39242. }
  39243. return this._vertexBuffers[kind];
  39244. };
  39245. /**
  39246. * Returns all vertex buffers
  39247. * @return an object holding all vertex buffers indexed by kind
  39248. */
  39249. Geometry.prototype.getVertexBuffers = function () {
  39250. if (!this.isReady()) {
  39251. return null;
  39252. }
  39253. return this._vertexBuffers;
  39254. };
  39255. /**
  39256. * Gets a boolean indicating if specific vertex buffer is present
  39257. * @param kind defines the data kind (Position, normal, etc...)
  39258. * @returns true if data is present
  39259. */
  39260. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39261. if (!this._vertexBuffers) {
  39262. if (this._delayInfo) {
  39263. return this._delayInfo.indexOf(kind) !== -1;
  39264. }
  39265. return false;
  39266. }
  39267. return this._vertexBuffers[kind] !== undefined;
  39268. };
  39269. /**
  39270. * Gets a list of all attached data kinds (Position, normal, etc...)
  39271. * @returns a list of string containing all kinds
  39272. */
  39273. Geometry.prototype.getVerticesDataKinds = function () {
  39274. var result = [];
  39275. var kind;
  39276. if (!this._vertexBuffers && this._delayInfo) {
  39277. for (kind in this._delayInfo) {
  39278. result.push(kind);
  39279. }
  39280. }
  39281. else {
  39282. for (kind in this._vertexBuffers) {
  39283. result.push(kind);
  39284. }
  39285. }
  39286. return result;
  39287. };
  39288. /**
  39289. * Update index buffer
  39290. * @param indices defines the indices to store in the index buffer
  39291. * @param offset defines the offset in the target buffer where to store the data
  39292. */
  39293. Geometry.prototype.updateIndices = function (indices, offset) {
  39294. if (!this._indexBuffer) {
  39295. return;
  39296. }
  39297. if (!this._indexBufferIsUpdatable) {
  39298. this.setIndices(indices, null, true);
  39299. }
  39300. else {
  39301. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39302. }
  39303. };
  39304. /**
  39305. * Creates a new index buffer
  39306. * @param indices defines the indices to store in the index buffer
  39307. * @param totalVertices defines the total number of vertices (could be null)
  39308. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39309. */
  39310. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39311. if (totalVertices === void 0) { totalVertices = null; }
  39312. if (updatable === void 0) { updatable = false; }
  39313. if (this._indexBuffer) {
  39314. this._engine._releaseBuffer(this._indexBuffer);
  39315. }
  39316. this._disposeVertexArrayObjects();
  39317. this._indices = indices;
  39318. this._indexBufferIsUpdatable = updatable;
  39319. if (this._meshes.length !== 0 && this._indices) {
  39320. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39321. }
  39322. if (totalVertices != undefined) { // including null and undefined
  39323. this._totalVertices = totalVertices;
  39324. }
  39325. var meshes = this._meshes;
  39326. var numOfMeshes = meshes.length;
  39327. for (var index = 0; index < numOfMeshes; index++) {
  39328. meshes[index]._createGlobalSubMesh(true);
  39329. }
  39330. this.notifyUpdate();
  39331. };
  39332. /**
  39333. * Return the total number of indices
  39334. * @returns the total number of indices
  39335. */
  39336. Geometry.prototype.getTotalIndices = function () {
  39337. if (!this.isReady()) {
  39338. return 0;
  39339. }
  39340. return this._indices.length;
  39341. };
  39342. /**
  39343. * Gets the index buffer array
  39344. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39345. * @returns the index buffer array
  39346. */
  39347. Geometry.prototype.getIndices = function (copyWhenShared) {
  39348. if (!this.isReady()) {
  39349. return null;
  39350. }
  39351. var orig = this._indices;
  39352. if (!copyWhenShared || this._meshes.length === 1) {
  39353. return orig;
  39354. }
  39355. else {
  39356. var len = orig.length;
  39357. var copy = [];
  39358. for (var i = 0; i < len; i++) {
  39359. copy.push(orig[i]);
  39360. }
  39361. return copy;
  39362. }
  39363. };
  39364. /**
  39365. * Gets the index buffer
  39366. * @return the index buffer
  39367. */
  39368. Geometry.prototype.getIndexBuffer = function () {
  39369. if (!this.isReady()) {
  39370. return null;
  39371. }
  39372. return this._indexBuffer;
  39373. };
  39374. /** @hidden */
  39375. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39376. if (effect === void 0) { effect = null; }
  39377. if (!effect || !this._vertexArrayObjects) {
  39378. return;
  39379. }
  39380. if (this._vertexArrayObjects[effect.key]) {
  39381. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39382. delete this._vertexArrayObjects[effect.key];
  39383. }
  39384. };
  39385. /**
  39386. * Release the associated resources for a specific mesh
  39387. * @param mesh defines the source mesh
  39388. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39389. */
  39390. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39391. var meshes = this._meshes;
  39392. var index = meshes.indexOf(mesh);
  39393. if (index === -1) {
  39394. return;
  39395. }
  39396. meshes.splice(index, 1);
  39397. mesh._geometry = null;
  39398. if (meshes.length === 0 && shouldDispose) {
  39399. this.dispose();
  39400. }
  39401. };
  39402. /**
  39403. * Apply current geometry to a given mesh
  39404. * @param mesh defines the mesh to apply geometry to
  39405. */
  39406. Geometry.prototype.applyToMesh = function (mesh) {
  39407. if (mesh._geometry === this) {
  39408. return;
  39409. }
  39410. var previousGeometry = mesh._geometry;
  39411. if (previousGeometry) {
  39412. previousGeometry.releaseForMesh(mesh);
  39413. }
  39414. var meshes = this._meshes;
  39415. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39416. mesh._geometry = this;
  39417. this._scene.pushGeometry(this);
  39418. meshes.push(mesh);
  39419. if (this.isReady()) {
  39420. this._applyToMesh(mesh);
  39421. }
  39422. else {
  39423. mesh._boundingInfo = this._boundingInfo;
  39424. }
  39425. };
  39426. Geometry.prototype._updateExtend = function (data) {
  39427. if (data === void 0) { data = null; }
  39428. if (!data) {
  39429. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39430. }
  39431. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39432. };
  39433. Geometry.prototype._applyToMesh = function (mesh) {
  39434. var numOfMeshes = this._meshes.length;
  39435. // vertexBuffers
  39436. for (var kind in this._vertexBuffers) {
  39437. if (numOfMeshes === 1) {
  39438. this._vertexBuffers[kind].create();
  39439. }
  39440. var buffer = this._vertexBuffers[kind].getBuffer();
  39441. if (buffer)
  39442. buffer.references = numOfMeshes;
  39443. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39444. if (!this._extend) {
  39445. this._updateExtend();
  39446. }
  39447. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39448. mesh._createGlobalSubMesh(false);
  39449. //bounding info was just created again, world matrix should be applied again.
  39450. mesh._updateBoundingInfo();
  39451. }
  39452. }
  39453. // indexBuffer
  39454. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39455. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39456. }
  39457. if (this._indexBuffer) {
  39458. this._indexBuffer.references = numOfMeshes;
  39459. }
  39460. };
  39461. Geometry.prototype.notifyUpdate = function (kind) {
  39462. if (this.onGeometryUpdated) {
  39463. this.onGeometryUpdated(this, kind);
  39464. }
  39465. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39466. var mesh = _a[_i];
  39467. mesh._markSubMeshesAsAttributesDirty();
  39468. }
  39469. };
  39470. /**
  39471. * Load the geometry if it was flagged as delay loaded
  39472. * @param scene defines the hosting scene
  39473. * @param onLoaded defines a callback called when the geometry is loaded
  39474. */
  39475. Geometry.prototype.load = function (scene, onLoaded) {
  39476. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39477. return;
  39478. }
  39479. if (this.isReady()) {
  39480. if (onLoaded) {
  39481. onLoaded();
  39482. }
  39483. return;
  39484. }
  39485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39486. this._queueLoad(scene, onLoaded);
  39487. };
  39488. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39489. var _this = this;
  39490. if (!this.delayLoadingFile) {
  39491. return;
  39492. }
  39493. scene._addPendingData(this);
  39494. scene._loadFile(this.delayLoadingFile, function (data) {
  39495. if (!_this._delayLoadingFunction) {
  39496. return;
  39497. }
  39498. _this._delayLoadingFunction(JSON.parse(data), _this);
  39499. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39500. _this._delayInfo = [];
  39501. scene._removePendingData(_this);
  39502. var meshes = _this._meshes;
  39503. var numOfMeshes = meshes.length;
  39504. for (var index = 0; index < numOfMeshes; index++) {
  39505. _this._applyToMesh(meshes[index]);
  39506. }
  39507. if (onLoaded) {
  39508. onLoaded();
  39509. }
  39510. }, undefined, true);
  39511. };
  39512. /**
  39513. * Invert the geometry to move from a right handed system to a left handed one.
  39514. */
  39515. Geometry.prototype.toLeftHanded = function () {
  39516. // Flip faces
  39517. var tIndices = this.getIndices(false);
  39518. if (tIndices != null && tIndices.length > 0) {
  39519. for (var i = 0; i < tIndices.length; i += 3) {
  39520. var tTemp = tIndices[i + 0];
  39521. tIndices[i + 0] = tIndices[i + 2];
  39522. tIndices[i + 2] = tTemp;
  39523. }
  39524. this.setIndices(tIndices);
  39525. }
  39526. // Negate position.z
  39527. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39528. if (tPositions != null && tPositions.length > 0) {
  39529. for (var i = 0; i < tPositions.length; i += 3) {
  39530. tPositions[i + 2] = -tPositions[i + 2];
  39531. }
  39532. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39533. }
  39534. // Negate normal.z
  39535. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39536. if (tNormals != null && tNormals.length > 0) {
  39537. for (var i = 0; i < tNormals.length; i += 3) {
  39538. tNormals[i + 2] = -tNormals[i + 2];
  39539. }
  39540. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39541. }
  39542. };
  39543. // Cache
  39544. /** @hidden */
  39545. Geometry.prototype._resetPointsArrayCache = function () {
  39546. this._positions = null;
  39547. };
  39548. /** @hidden */
  39549. Geometry.prototype._generatePointsArray = function () {
  39550. if (this._positions)
  39551. return true;
  39552. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39553. if (!data || data.length === 0) {
  39554. return false;
  39555. }
  39556. this._positions = [];
  39557. for (var index = 0; index < data.length; index += 3) {
  39558. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39559. }
  39560. return true;
  39561. };
  39562. /**
  39563. * Gets a value indicating if the geometry is disposed
  39564. * @returns true if the geometry was disposed
  39565. */
  39566. Geometry.prototype.isDisposed = function () {
  39567. return this._isDisposed;
  39568. };
  39569. Geometry.prototype._disposeVertexArrayObjects = function () {
  39570. if (this._vertexArrayObjects) {
  39571. for (var kind in this._vertexArrayObjects) {
  39572. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39573. }
  39574. this._vertexArrayObjects = {};
  39575. }
  39576. };
  39577. /**
  39578. * Free all associated resources
  39579. */
  39580. Geometry.prototype.dispose = function () {
  39581. var meshes = this._meshes;
  39582. var numOfMeshes = meshes.length;
  39583. var index;
  39584. for (index = 0; index < numOfMeshes; index++) {
  39585. this.releaseForMesh(meshes[index]);
  39586. }
  39587. this._meshes = [];
  39588. this._disposeVertexArrayObjects();
  39589. for (var kind in this._vertexBuffers) {
  39590. this._vertexBuffers[kind].dispose();
  39591. }
  39592. this._vertexBuffers = {};
  39593. this._totalVertices = 0;
  39594. if (this._indexBuffer) {
  39595. this._engine._releaseBuffer(this._indexBuffer);
  39596. }
  39597. this._indexBuffer = null;
  39598. this._indices = [];
  39599. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39600. this.delayLoadingFile = null;
  39601. this._delayLoadingFunction = null;
  39602. this._delayInfo = [];
  39603. this._boundingInfo = null;
  39604. this._scene.removeGeometry(this);
  39605. this._isDisposed = true;
  39606. };
  39607. /**
  39608. * Clone the current geometry into a new geometry
  39609. * @param id defines the unique ID of the new geometry
  39610. * @returns a new geometry object
  39611. */
  39612. Geometry.prototype.copy = function (id) {
  39613. var vertexData = new BABYLON.VertexData();
  39614. vertexData.indices = [];
  39615. var indices = this.getIndices();
  39616. if (indices) {
  39617. for (var index = 0; index < indices.length; index++) {
  39618. vertexData.indices.push(indices[index]);
  39619. }
  39620. }
  39621. var updatable = false;
  39622. var stopChecking = false;
  39623. var kind;
  39624. for (kind in this._vertexBuffers) {
  39625. // using slice() to make a copy of the array and not just reference it
  39626. var data = this.getVerticesData(kind);
  39627. if (data instanceof Float32Array) {
  39628. vertexData.set(new Float32Array(data), kind);
  39629. }
  39630. else {
  39631. vertexData.set(data.slice(0), kind);
  39632. }
  39633. if (!stopChecking) {
  39634. var vb = this.getVertexBuffer(kind);
  39635. if (vb) {
  39636. updatable = vb.isUpdatable();
  39637. stopChecking = !updatable;
  39638. }
  39639. }
  39640. }
  39641. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39642. geometry.delayLoadState = this.delayLoadState;
  39643. geometry.delayLoadingFile = this.delayLoadingFile;
  39644. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39645. for (kind in this._delayInfo) {
  39646. geometry._delayInfo = geometry._delayInfo || [];
  39647. geometry._delayInfo.push(kind);
  39648. }
  39649. // Bounding info
  39650. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39651. return geometry;
  39652. };
  39653. /**
  39654. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39655. * @return a JSON representation of the current geometry data (without the vertices data)
  39656. */
  39657. Geometry.prototype.serialize = function () {
  39658. var serializationObject = {};
  39659. serializationObject.id = this.id;
  39660. serializationObject.updatable = this._updatable;
  39661. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39662. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39663. }
  39664. return serializationObject;
  39665. };
  39666. Geometry.prototype.toNumberArray = function (origin) {
  39667. if (Array.isArray(origin)) {
  39668. return origin;
  39669. }
  39670. else {
  39671. return Array.prototype.slice.call(origin);
  39672. }
  39673. };
  39674. /**
  39675. * Serialize all vertices data into a JSON oject
  39676. * @returns a JSON representation of the current geometry data
  39677. */
  39678. Geometry.prototype.serializeVerticeData = function () {
  39679. var serializationObject = this.serialize();
  39680. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39681. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39682. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39683. serializationObject.positions._updatable = true;
  39684. }
  39685. }
  39686. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39687. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39688. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39689. serializationObject.normals._updatable = true;
  39690. }
  39691. }
  39692. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39693. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39694. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39695. serializationObject.tangets._updatable = true;
  39696. }
  39697. }
  39698. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39699. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39700. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39701. serializationObject.uvs._updatable = true;
  39702. }
  39703. }
  39704. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39705. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39706. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39707. serializationObject.uv2s._updatable = true;
  39708. }
  39709. }
  39710. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39711. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39712. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39713. serializationObject.uv3s._updatable = true;
  39714. }
  39715. }
  39716. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39717. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39718. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39719. serializationObject.uv4s._updatable = true;
  39720. }
  39721. }
  39722. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39723. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39724. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39725. serializationObject.uv5s._updatable = true;
  39726. }
  39727. }
  39728. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39729. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39730. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39731. serializationObject.uv6s._updatable = true;
  39732. }
  39733. }
  39734. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39735. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39736. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39737. serializationObject.colors._updatable = true;
  39738. }
  39739. }
  39740. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39741. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39742. serializationObject.matricesIndices._isExpanded = true;
  39743. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39744. serializationObject.matricesIndices._updatable = true;
  39745. }
  39746. }
  39747. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39748. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39749. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39750. serializationObject.matricesWeights._updatable = true;
  39751. }
  39752. }
  39753. serializationObject.indices = this.toNumberArray(this.getIndices());
  39754. return serializationObject;
  39755. };
  39756. // Statics
  39757. /**
  39758. * Extracts a clone of a mesh geometry
  39759. * @param mesh defines the source mesh
  39760. * @param id defines the unique ID of the new geometry object
  39761. * @returns the new geometry object
  39762. */
  39763. Geometry.ExtractFromMesh = function (mesh, id) {
  39764. var geometry = mesh._geometry;
  39765. if (!geometry) {
  39766. return null;
  39767. }
  39768. return geometry.copy(id);
  39769. };
  39770. /**
  39771. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39772. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39773. * Be aware Math.random() could cause collisions, but:
  39774. * "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"
  39775. * @returns a string containing a new GUID
  39776. */
  39777. Geometry.RandomId = function () {
  39778. return BABYLON.Tools.RandomId();
  39779. };
  39780. /** @hidden */
  39781. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39782. var scene = mesh.getScene();
  39783. // Geometry
  39784. var geometryId = parsedGeometry.geometryId;
  39785. if (geometryId) {
  39786. var geometry = scene.getGeometryByID(geometryId);
  39787. if (geometry) {
  39788. geometry.applyToMesh(mesh);
  39789. }
  39790. }
  39791. else if (parsedGeometry instanceof ArrayBuffer) {
  39792. var binaryInfo = mesh._binaryInfo;
  39793. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39794. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39795. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39796. }
  39797. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39798. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39799. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39800. }
  39801. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39802. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39803. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39804. }
  39805. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39806. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39807. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39808. }
  39809. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39810. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39811. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39812. }
  39813. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39814. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39815. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39816. }
  39817. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39818. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39819. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39820. }
  39821. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39822. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39823. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39824. }
  39825. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39826. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39827. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39828. }
  39829. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39830. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39831. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39832. }
  39833. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39834. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39835. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39836. }
  39837. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39838. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39839. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39840. }
  39841. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39842. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39843. mesh.setIndices(indicesData, null);
  39844. }
  39845. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39846. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39847. mesh.subMeshes = [];
  39848. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39849. var materialIndex = subMeshesData[(i * 5) + 0];
  39850. var verticesStart = subMeshesData[(i * 5) + 1];
  39851. var verticesCount = subMeshesData[(i * 5) + 2];
  39852. var indexStart = subMeshesData[(i * 5) + 3];
  39853. var indexCount = subMeshesData[(i * 5) + 4];
  39854. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39855. }
  39856. }
  39857. }
  39858. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39859. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39860. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39861. if (parsedGeometry.tangents) {
  39862. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39863. }
  39864. if (parsedGeometry.uvs) {
  39865. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39866. }
  39867. if (parsedGeometry.uvs2) {
  39868. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39869. }
  39870. if (parsedGeometry.uvs3) {
  39871. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39872. }
  39873. if (parsedGeometry.uvs4) {
  39874. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39875. }
  39876. if (parsedGeometry.uvs5) {
  39877. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39878. }
  39879. if (parsedGeometry.uvs6) {
  39880. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39881. }
  39882. if (parsedGeometry.colors) {
  39883. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39884. }
  39885. if (parsedGeometry.matricesIndices) {
  39886. if (!parsedGeometry.matricesIndices._isExpanded) {
  39887. var floatIndices = [];
  39888. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39889. var matricesIndex = parsedGeometry.matricesIndices[i];
  39890. floatIndices.push(matricesIndex & 0x000000FF);
  39891. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39892. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39893. floatIndices.push(matricesIndex >> 24);
  39894. }
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39896. }
  39897. else {
  39898. delete parsedGeometry.matricesIndices._isExpanded;
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39900. }
  39901. }
  39902. if (parsedGeometry.matricesIndicesExtra) {
  39903. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39904. var floatIndices = [];
  39905. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39906. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39907. floatIndices.push(matricesIndex & 0x000000FF);
  39908. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39909. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39910. floatIndices.push(matricesIndex >> 24);
  39911. }
  39912. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39913. }
  39914. else {
  39915. delete parsedGeometry.matricesIndices._isExpanded;
  39916. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39917. }
  39918. }
  39919. if (parsedGeometry.matricesWeights) {
  39920. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39921. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39922. }
  39923. if (parsedGeometry.matricesWeightsExtra) {
  39924. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39925. }
  39926. mesh.setIndices(parsedGeometry.indices, null);
  39927. }
  39928. // SubMeshes
  39929. if (parsedGeometry.subMeshes) {
  39930. mesh.subMeshes = [];
  39931. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39932. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39933. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39934. }
  39935. }
  39936. // Flat shading
  39937. if (mesh._shouldGenerateFlatShading) {
  39938. mesh.convertToFlatShadedMesh();
  39939. delete mesh._shouldGenerateFlatShading;
  39940. }
  39941. // Update
  39942. mesh.computeWorldMatrix(true);
  39943. // Octree
  39944. var sceneOctree = scene.selectionOctree;
  39945. if (sceneOctree !== undefined && sceneOctree !== null) {
  39946. sceneOctree.addMesh(mesh);
  39947. }
  39948. };
  39949. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39950. var epsilon = 1e-3;
  39951. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39952. return;
  39953. }
  39954. var noInfluenceBoneIndex = 0.0;
  39955. if (parsedGeometry.skeletonId > -1) {
  39956. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39957. if (!skeleton) {
  39958. return;
  39959. }
  39960. noInfluenceBoneIndex = skeleton.bones.length;
  39961. }
  39962. else {
  39963. return;
  39964. }
  39965. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39966. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39967. var matricesWeights = parsedGeometry.matricesWeights;
  39968. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39969. var influencers = parsedGeometry.numBoneInfluencer;
  39970. var size = matricesWeights.length;
  39971. for (var i = 0; i < size; i += 4) {
  39972. var weight = 0.0;
  39973. var firstZeroWeight = -1;
  39974. for (var j = 0; j < 4; j++) {
  39975. var w = matricesWeights[i + j];
  39976. weight += w;
  39977. if (w < epsilon && firstZeroWeight < 0) {
  39978. firstZeroWeight = j;
  39979. }
  39980. }
  39981. if (matricesWeightsExtra) {
  39982. for (var j = 0; j < 4; j++) {
  39983. var w = matricesWeightsExtra[i + j];
  39984. weight += w;
  39985. if (w < epsilon && firstZeroWeight < 0) {
  39986. firstZeroWeight = j + 4;
  39987. }
  39988. }
  39989. }
  39990. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39991. firstZeroWeight = influencers - 1;
  39992. }
  39993. if (weight > epsilon) {
  39994. var mweight = 1.0 / weight;
  39995. for (var j = 0; j < 4; j++) {
  39996. matricesWeights[i + j] *= mweight;
  39997. }
  39998. if (matricesWeightsExtra) {
  39999. for (var j = 0; j < 4; j++) {
  40000. matricesWeightsExtra[i + j] *= mweight;
  40001. }
  40002. }
  40003. }
  40004. else {
  40005. if (firstZeroWeight >= 4) {
  40006. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40007. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40008. }
  40009. else {
  40010. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40011. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40012. }
  40013. }
  40014. }
  40015. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40016. if (parsedGeometry.matricesWeightsExtra) {
  40017. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40018. }
  40019. };
  40020. /**
  40021. * Create a new geometry from persisted data (Using .babylon file format)
  40022. * @param parsedVertexData defines the persisted data
  40023. * @param scene defines the hosting scene
  40024. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40025. * @returns the new geometry object
  40026. */
  40027. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40028. if (scene.getGeometryByID(parsedVertexData.id)) {
  40029. return null; // null since geometry could be something else than a box...
  40030. }
  40031. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40032. if (BABYLON.Tags) {
  40033. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40034. }
  40035. if (parsedVertexData.delayLoadingFile) {
  40036. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40037. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40038. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40039. geometry._delayInfo = [];
  40040. if (parsedVertexData.hasUVs) {
  40041. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40042. }
  40043. if (parsedVertexData.hasUVs2) {
  40044. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40045. }
  40046. if (parsedVertexData.hasUVs3) {
  40047. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40048. }
  40049. if (parsedVertexData.hasUVs4) {
  40050. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40051. }
  40052. if (parsedVertexData.hasUVs5) {
  40053. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40054. }
  40055. if (parsedVertexData.hasUVs6) {
  40056. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40057. }
  40058. if (parsedVertexData.hasColors) {
  40059. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40060. }
  40061. if (parsedVertexData.hasMatricesIndices) {
  40062. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40063. }
  40064. if (parsedVertexData.hasMatricesWeights) {
  40065. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40066. }
  40067. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40068. }
  40069. else {
  40070. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40071. }
  40072. scene.pushGeometry(geometry, true);
  40073. return geometry;
  40074. };
  40075. return Geometry;
  40076. }());
  40077. BABYLON.Geometry = Geometry;
  40078. // Primitives
  40079. /// Abstract class
  40080. /**
  40081. * Abstract class used to provide common services for all typed geometries
  40082. * @hidden
  40083. */
  40084. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40085. __extends(_PrimitiveGeometry, _super);
  40086. /**
  40087. * Creates a new typed geometry
  40088. * @param id defines the unique ID of the geometry
  40089. * @param scene defines the hosting scene
  40090. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40091. * @param mesh defines the hosting mesh (can be null)
  40092. */
  40093. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40094. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40095. if (mesh === void 0) { mesh = null; }
  40096. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40097. _this._canBeRegenerated = _canBeRegenerated;
  40098. _this._beingRegenerated = true;
  40099. _this.regenerate();
  40100. _this._beingRegenerated = false;
  40101. return _this;
  40102. }
  40103. /**
  40104. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40105. * @returns true if the geometry can be regenerated
  40106. */
  40107. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40108. return this._canBeRegenerated;
  40109. };
  40110. /**
  40111. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40112. */
  40113. _PrimitiveGeometry.prototype.regenerate = function () {
  40114. if (!this._canBeRegenerated) {
  40115. return;
  40116. }
  40117. this._beingRegenerated = true;
  40118. this.setAllVerticesData(this._regenerateVertexData(), false);
  40119. this._beingRegenerated = false;
  40120. };
  40121. /**
  40122. * Clone the geometry
  40123. * @param id defines the unique ID of the new geometry
  40124. * @returns the new geometry
  40125. */
  40126. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40127. return _super.prototype.copy.call(this, id);
  40128. };
  40129. // overrides
  40130. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40131. if (!this._beingRegenerated) {
  40132. return;
  40133. }
  40134. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40135. };
  40136. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40137. if (!this._beingRegenerated) {
  40138. return;
  40139. }
  40140. _super.prototype.setVerticesData.call(this, kind, data, false);
  40141. };
  40142. // to override
  40143. /** @hidden */
  40144. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40145. throw new Error("Abstract method");
  40146. };
  40147. _PrimitiveGeometry.prototype.copy = function (id) {
  40148. throw new Error("Must be overriden in sub-classes.");
  40149. };
  40150. _PrimitiveGeometry.prototype.serialize = function () {
  40151. var serializationObject = _super.prototype.serialize.call(this);
  40152. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40153. return serializationObject;
  40154. };
  40155. return _PrimitiveGeometry;
  40156. }(Geometry));
  40157. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40158. /**
  40159. * Creates a ribbon geometry
  40160. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40161. */
  40162. var RibbonGeometry = /** @class */ (function (_super) {
  40163. __extends(RibbonGeometry, _super);
  40164. /**
  40165. * Creates a ribbon geometry
  40166. * @param id defines the unique ID of the geometry
  40167. * @param scene defines the hosting scene
  40168. * @param pathArray defines the array of paths to use
  40169. * @param closeArray defines if the last path and the first path must be joined
  40170. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40171. * @param offset defines the offset between points
  40172. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40173. * @param mesh defines the hosting mesh (can be null)
  40174. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40175. */
  40176. function RibbonGeometry(id, scene,
  40177. /**
  40178. * Defines the array of paths to use
  40179. */
  40180. pathArray,
  40181. /**
  40182. * Defines if the last and first points of each path in your pathArray must be joined
  40183. */
  40184. closeArray,
  40185. /**
  40186. * Defines if the last and first points of each path in your pathArray must be joined
  40187. */
  40188. closePath,
  40189. /**
  40190. * Defines the offset between points
  40191. */
  40192. offset, canBeRegenerated, mesh,
  40193. /**
  40194. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40195. */
  40196. side) {
  40197. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40198. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40199. _this.pathArray = pathArray;
  40200. _this.closeArray = closeArray;
  40201. _this.closePath = closePath;
  40202. _this.offset = offset;
  40203. _this.side = side;
  40204. return _this;
  40205. }
  40206. /** @hidden */
  40207. RibbonGeometry.prototype._regenerateVertexData = function () {
  40208. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40209. };
  40210. RibbonGeometry.prototype.copy = function (id) {
  40211. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40212. };
  40213. return RibbonGeometry;
  40214. }(_PrimitiveGeometry));
  40215. BABYLON.RibbonGeometry = RibbonGeometry;
  40216. /**
  40217. * Creates a box geometry
  40218. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40219. */
  40220. var BoxGeometry = /** @class */ (function (_super) {
  40221. __extends(BoxGeometry, _super);
  40222. /**
  40223. * Creates a box geometry
  40224. * @param id defines the unique ID of the geometry
  40225. * @param scene defines the hosting scene
  40226. * @param size defines the zise of the box (width, height and depth are the same)
  40227. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40228. * @param mesh defines the hosting mesh (can be null)
  40229. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40230. */
  40231. function BoxGeometry(id, scene,
  40232. /**
  40233. * Defines the zise of the box (width, height and depth are the same)
  40234. */
  40235. size, canBeRegenerated, mesh,
  40236. /**
  40237. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40238. */
  40239. side) {
  40240. if (mesh === void 0) { mesh = null; }
  40241. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40242. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40243. _this.size = size;
  40244. _this.side = side;
  40245. return _this;
  40246. }
  40247. BoxGeometry.prototype._regenerateVertexData = function () {
  40248. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40249. };
  40250. BoxGeometry.prototype.copy = function (id) {
  40251. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40252. };
  40253. BoxGeometry.prototype.serialize = function () {
  40254. var serializationObject = _super.prototype.serialize.call(this);
  40255. serializationObject.size = this.size;
  40256. return serializationObject;
  40257. };
  40258. BoxGeometry.Parse = function (parsedBox, scene) {
  40259. if (scene.getGeometryByID(parsedBox.id)) {
  40260. return null; // null since geometry could be something else than a box...
  40261. }
  40262. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40263. if (BABYLON.Tags) {
  40264. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40265. }
  40266. scene.pushGeometry(box, true);
  40267. return box;
  40268. };
  40269. return BoxGeometry;
  40270. }(_PrimitiveGeometry));
  40271. BABYLON.BoxGeometry = BoxGeometry;
  40272. /**
  40273. * Creates a sphere geometry
  40274. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40275. */
  40276. var SphereGeometry = /** @class */ (function (_super) {
  40277. __extends(SphereGeometry, _super);
  40278. /**
  40279. * Create a new sphere geometry
  40280. * @param id defines the unique ID of the geometry
  40281. * @param scene defines the hosting scene
  40282. * @param segments defines the number of segments to use to create the sphere
  40283. * @param diameter defines the diameter of the sphere
  40284. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40285. * @param mesh defines the hosting mesh (can be null)
  40286. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40287. */
  40288. function SphereGeometry(id, scene,
  40289. /**
  40290. * Defines the number of segments to use to create the sphere
  40291. */
  40292. segments,
  40293. /**
  40294. * Defines the diameter of the sphere
  40295. */
  40296. diameter, canBeRegenerated, mesh,
  40297. /**
  40298. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40299. */
  40300. side) {
  40301. if (mesh === void 0) { mesh = null; }
  40302. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40303. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40304. _this.segments = segments;
  40305. _this.diameter = diameter;
  40306. _this.side = side;
  40307. return _this;
  40308. }
  40309. SphereGeometry.prototype._regenerateVertexData = function () {
  40310. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40311. };
  40312. SphereGeometry.prototype.copy = function (id) {
  40313. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40314. };
  40315. SphereGeometry.prototype.serialize = function () {
  40316. var serializationObject = _super.prototype.serialize.call(this);
  40317. serializationObject.segments = this.segments;
  40318. serializationObject.diameter = this.diameter;
  40319. return serializationObject;
  40320. };
  40321. SphereGeometry.Parse = function (parsedSphere, scene) {
  40322. if (scene.getGeometryByID(parsedSphere.id)) {
  40323. return null; // null since geometry could be something else than a sphere...
  40324. }
  40325. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40326. if (BABYLON.Tags) {
  40327. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40328. }
  40329. scene.pushGeometry(sphere, true);
  40330. return sphere;
  40331. };
  40332. return SphereGeometry;
  40333. }(_PrimitiveGeometry));
  40334. BABYLON.SphereGeometry = SphereGeometry;
  40335. /**
  40336. * Creates a disc geometry
  40337. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40338. */
  40339. var DiscGeometry = /** @class */ (function (_super) {
  40340. __extends(DiscGeometry, _super);
  40341. /**
  40342. * Creates a new disc geometry
  40343. * @param id defines the unique ID of the geometry
  40344. * @param scene defines the hosting scene
  40345. * @param radius defines the radius of the disc
  40346. * @param tessellation defines the tesselation factor to apply to the disc
  40347. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40348. * @param mesh defines the hosting mesh (can be null)
  40349. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40350. */
  40351. function DiscGeometry(id, scene,
  40352. /**
  40353. * Defines the radius of the disc
  40354. */
  40355. radius,
  40356. /**
  40357. * Defines the tesselation factor to apply to the disc
  40358. */
  40359. tessellation, canBeRegenerated, mesh,
  40360. /**
  40361. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40362. */
  40363. side) {
  40364. if (mesh === void 0) { mesh = null; }
  40365. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40366. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40367. _this.radius = radius;
  40368. _this.tessellation = tessellation;
  40369. _this.side = side;
  40370. return _this;
  40371. }
  40372. DiscGeometry.prototype._regenerateVertexData = function () {
  40373. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40374. };
  40375. DiscGeometry.prototype.copy = function (id) {
  40376. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40377. };
  40378. return DiscGeometry;
  40379. }(_PrimitiveGeometry));
  40380. BABYLON.DiscGeometry = DiscGeometry;
  40381. /**
  40382. * Creates a new cylinder geometry
  40383. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40384. */
  40385. var CylinderGeometry = /** @class */ (function (_super) {
  40386. __extends(CylinderGeometry, _super);
  40387. /**
  40388. * Creates a new cylinder geometry
  40389. * @param id defines the unique ID of the geometry
  40390. * @param scene defines the hosting scene
  40391. * @param height defines the height of the cylinder
  40392. * @param diameterTop defines the diameter of the cylinder's top cap
  40393. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40394. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40395. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40396. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40397. * @param mesh defines the hosting mesh (can be null)
  40398. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40399. */
  40400. function CylinderGeometry(id, scene,
  40401. /**
  40402. * Defines the height of the cylinder
  40403. */
  40404. height,
  40405. /**
  40406. * Defines the diameter of the cylinder's top cap
  40407. */
  40408. diameterTop,
  40409. /**
  40410. * Defines the diameter of the cylinder's bottom cap
  40411. */
  40412. diameterBottom,
  40413. /**
  40414. * Defines the tessellation factor to apply to the cylinder
  40415. */
  40416. tessellation,
  40417. /**
  40418. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40419. */
  40420. subdivisions, canBeRegenerated, mesh,
  40421. /**
  40422. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40423. */
  40424. side) {
  40425. if (subdivisions === void 0) { subdivisions = 1; }
  40426. if (mesh === void 0) { mesh = null; }
  40427. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40428. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40429. _this.height = height;
  40430. _this.diameterTop = diameterTop;
  40431. _this.diameterBottom = diameterBottom;
  40432. _this.tessellation = tessellation;
  40433. _this.subdivisions = subdivisions;
  40434. _this.side = side;
  40435. return _this;
  40436. }
  40437. CylinderGeometry.prototype._regenerateVertexData = function () {
  40438. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40439. };
  40440. CylinderGeometry.prototype.copy = function (id) {
  40441. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40442. };
  40443. CylinderGeometry.prototype.serialize = function () {
  40444. var serializationObject = _super.prototype.serialize.call(this);
  40445. serializationObject.height = this.height;
  40446. serializationObject.diameterTop = this.diameterTop;
  40447. serializationObject.diameterBottom = this.diameterBottom;
  40448. serializationObject.tessellation = this.tessellation;
  40449. return serializationObject;
  40450. };
  40451. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40452. if (scene.getGeometryByID(parsedCylinder.id)) {
  40453. return null; // null since geometry could be something else than a cylinder...
  40454. }
  40455. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40456. if (BABYLON.Tags) {
  40457. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40458. }
  40459. scene.pushGeometry(cylinder, true);
  40460. return cylinder;
  40461. };
  40462. return CylinderGeometry;
  40463. }(_PrimitiveGeometry));
  40464. BABYLON.CylinderGeometry = CylinderGeometry;
  40465. /**
  40466. * Creates a new torus geometry
  40467. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40468. */
  40469. var TorusGeometry = /** @class */ (function (_super) {
  40470. __extends(TorusGeometry, _super);
  40471. /**
  40472. * Creates a new torus geometry
  40473. * @param id defines the unique ID of the geometry
  40474. * @param scene defines the hosting scene
  40475. * @param diameter defines the diameter of the torus
  40476. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40477. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40478. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40479. * @param mesh defines the hosting mesh (can be null)
  40480. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40481. */
  40482. function TorusGeometry(id, scene,
  40483. /**
  40484. * Defines the diameter of the torus
  40485. */
  40486. diameter,
  40487. /**
  40488. * Defines the thickness of the torus (ie. internal diameter)
  40489. */
  40490. thickness,
  40491. /**
  40492. * Defines the tesselation factor to apply to the torus
  40493. */
  40494. tessellation, canBeRegenerated, mesh,
  40495. /**
  40496. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40497. */
  40498. side) {
  40499. if (mesh === void 0) { mesh = null; }
  40500. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40501. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40502. _this.diameter = diameter;
  40503. _this.thickness = thickness;
  40504. _this.tessellation = tessellation;
  40505. _this.side = side;
  40506. return _this;
  40507. }
  40508. TorusGeometry.prototype._regenerateVertexData = function () {
  40509. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40510. };
  40511. TorusGeometry.prototype.copy = function (id) {
  40512. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40513. };
  40514. TorusGeometry.prototype.serialize = function () {
  40515. var serializationObject = _super.prototype.serialize.call(this);
  40516. serializationObject.diameter = this.diameter;
  40517. serializationObject.thickness = this.thickness;
  40518. serializationObject.tessellation = this.tessellation;
  40519. return serializationObject;
  40520. };
  40521. TorusGeometry.Parse = function (parsedTorus, scene) {
  40522. if (scene.getGeometryByID(parsedTorus.id)) {
  40523. return null; // null since geometry could be something else than a torus...
  40524. }
  40525. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40526. if (BABYLON.Tags) {
  40527. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40528. }
  40529. scene.pushGeometry(torus, true);
  40530. return torus;
  40531. };
  40532. return TorusGeometry;
  40533. }(_PrimitiveGeometry));
  40534. BABYLON.TorusGeometry = TorusGeometry;
  40535. /**
  40536. * Creates a new ground geometry
  40537. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40538. */
  40539. var GroundGeometry = /** @class */ (function (_super) {
  40540. __extends(GroundGeometry, _super);
  40541. /**
  40542. * Creates a new ground geometry
  40543. * @param id defines the unique ID of the geometry
  40544. * @param scene defines the hosting scene
  40545. * @param width defines the width of the ground
  40546. * @param height defines the height of the ground
  40547. * @param subdivisions defines the subdivisions to apply to the ground
  40548. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40549. * @param mesh defines the hosting mesh (can be null)
  40550. */
  40551. function GroundGeometry(id, scene,
  40552. /**
  40553. * Defines the width of the ground
  40554. */
  40555. width,
  40556. /**
  40557. * Defines the height of the ground
  40558. */
  40559. height,
  40560. /**
  40561. * Defines the subdivisions to apply to the ground
  40562. */
  40563. subdivisions, canBeRegenerated, mesh) {
  40564. if (mesh === void 0) { mesh = null; }
  40565. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40566. _this.width = width;
  40567. _this.height = height;
  40568. _this.subdivisions = subdivisions;
  40569. return _this;
  40570. }
  40571. GroundGeometry.prototype._regenerateVertexData = function () {
  40572. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40573. };
  40574. GroundGeometry.prototype.copy = function (id) {
  40575. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40576. };
  40577. GroundGeometry.prototype.serialize = function () {
  40578. var serializationObject = _super.prototype.serialize.call(this);
  40579. serializationObject.width = this.width;
  40580. serializationObject.height = this.height;
  40581. serializationObject.subdivisions = this.subdivisions;
  40582. return serializationObject;
  40583. };
  40584. GroundGeometry.Parse = function (parsedGround, scene) {
  40585. if (scene.getGeometryByID(parsedGround.id)) {
  40586. return null; // null since geometry could be something else than a ground...
  40587. }
  40588. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40589. if (BABYLON.Tags) {
  40590. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40591. }
  40592. scene.pushGeometry(ground, true);
  40593. return ground;
  40594. };
  40595. return GroundGeometry;
  40596. }(_PrimitiveGeometry));
  40597. BABYLON.GroundGeometry = GroundGeometry;
  40598. /**
  40599. * Creates a tiled ground geometry
  40600. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40601. */
  40602. var TiledGroundGeometry = /** @class */ (function (_super) {
  40603. __extends(TiledGroundGeometry, _super);
  40604. /**
  40605. * Creates a tiled ground geometry
  40606. * @param id defines the unique ID of the geometry
  40607. * @param scene defines the hosting scene
  40608. * @param xmin defines the minimum value on X axis
  40609. * @param zmin defines the minimum value on Z axis
  40610. * @param xmax defines the maximum value on X axis
  40611. * @param zmax defines the maximum value on Z axis
  40612. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40613. * @param precision defines the precision to use when computing the tiles
  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. */
  40617. function TiledGroundGeometry(id, scene,
  40618. /**
  40619. * Defines the minimum value on X axis
  40620. */
  40621. xmin,
  40622. /**
  40623. * Defines the minimum value on Z axis
  40624. */
  40625. zmin,
  40626. /**
  40627. * Defines the maximum value on X axis
  40628. */
  40629. xmax,
  40630. /**
  40631. * Defines the maximum value on Z axis
  40632. */
  40633. zmax,
  40634. /**
  40635. * Defines the subdivisions to apply to the ground
  40636. */
  40637. subdivisions,
  40638. /**
  40639. * Defines the precision to use when computing the tiles
  40640. */
  40641. precision, canBeRegenerated, mesh) {
  40642. if (mesh === void 0) { mesh = null; }
  40643. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40644. _this.xmin = xmin;
  40645. _this.zmin = zmin;
  40646. _this.xmax = xmax;
  40647. _this.zmax = zmax;
  40648. _this.subdivisions = subdivisions;
  40649. _this.precision = precision;
  40650. return _this;
  40651. }
  40652. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40653. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40654. };
  40655. TiledGroundGeometry.prototype.copy = function (id) {
  40656. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40657. };
  40658. return TiledGroundGeometry;
  40659. }(_PrimitiveGeometry));
  40660. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40661. /**
  40662. * Creates a plane geometry
  40663. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40664. */
  40665. var PlaneGeometry = /** @class */ (function (_super) {
  40666. __extends(PlaneGeometry, _super);
  40667. /**
  40668. * Creates a plane geometry
  40669. * @param id defines the unique ID of the geometry
  40670. * @param scene defines the hosting scene
  40671. * @param size defines the size of the plane (width === height)
  40672. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40673. * @param mesh defines the hosting mesh (can be null)
  40674. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40675. */
  40676. function PlaneGeometry(id, scene,
  40677. /**
  40678. * Defines the size of the plane (width === height)
  40679. */
  40680. size, canBeRegenerated, mesh,
  40681. /**
  40682. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40683. */
  40684. side) {
  40685. if (mesh === void 0) { mesh = null; }
  40686. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40687. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40688. _this.size = size;
  40689. _this.side = side;
  40690. return _this;
  40691. }
  40692. PlaneGeometry.prototype._regenerateVertexData = function () {
  40693. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40694. };
  40695. PlaneGeometry.prototype.copy = function (id) {
  40696. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40697. };
  40698. PlaneGeometry.prototype.serialize = function () {
  40699. var serializationObject = _super.prototype.serialize.call(this);
  40700. serializationObject.size = this.size;
  40701. return serializationObject;
  40702. };
  40703. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40704. if (scene.getGeometryByID(parsedPlane.id)) {
  40705. return null; // null since geometry could be something else than a ground...
  40706. }
  40707. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40708. if (BABYLON.Tags) {
  40709. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40710. }
  40711. scene.pushGeometry(plane, true);
  40712. return plane;
  40713. };
  40714. return PlaneGeometry;
  40715. }(_PrimitiveGeometry));
  40716. BABYLON.PlaneGeometry = PlaneGeometry;
  40717. /**
  40718. * Creates a torus knot geometry
  40719. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40720. */
  40721. var TorusKnotGeometry = /** @class */ (function (_super) {
  40722. __extends(TorusKnotGeometry, _super);
  40723. /**
  40724. * Creates a torus knot geometry
  40725. * @param id defines the unique ID of the geometry
  40726. * @param scene defines the hosting scene
  40727. * @param radius defines the radius of the torus knot
  40728. * @param tube defines the thickness of the torus knot tube
  40729. * @param radialSegments defines the number of radial segments
  40730. * @param tubularSegments defines the number of tubular segments
  40731. * @param p defines the first number of windings
  40732. * @param q defines the second number of windings
  40733. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40734. * @param mesh defines the hosting mesh (can be null)
  40735. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40736. */
  40737. function TorusKnotGeometry(id, scene,
  40738. /**
  40739. * Defines the radius of the torus knot
  40740. */
  40741. radius,
  40742. /**
  40743. * Defines the thickness of the torus knot tube
  40744. */
  40745. tube,
  40746. /**
  40747. * Defines the number of radial segments
  40748. */
  40749. radialSegments,
  40750. /**
  40751. * Defines the number of tubular segments
  40752. */
  40753. tubularSegments,
  40754. /**
  40755. * Defines the first number of windings
  40756. */
  40757. p,
  40758. /**
  40759. * Defines the second number of windings
  40760. */
  40761. q, canBeRegenerated, mesh,
  40762. /**
  40763. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40764. */
  40765. side) {
  40766. if (mesh === void 0) { mesh = null; }
  40767. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40768. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40769. _this.radius = radius;
  40770. _this.tube = tube;
  40771. _this.radialSegments = radialSegments;
  40772. _this.tubularSegments = tubularSegments;
  40773. _this.p = p;
  40774. _this.q = q;
  40775. _this.side = side;
  40776. return _this;
  40777. }
  40778. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40779. 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 });
  40780. };
  40781. TorusKnotGeometry.prototype.copy = function (id) {
  40782. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40783. };
  40784. TorusKnotGeometry.prototype.serialize = function () {
  40785. var serializationObject = _super.prototype.serialize.call(this);
  40786. serializationObject.radius = this.radius;
  40787. serializationObject.tube = this.tube;
  40788. serializationObject.radialSegments = this.radialSegments;
  40789. serializationObject.tubularSegments = this.tubularSegments;
  40790. serializationObject.p = this.p;
  40791. serializationObject.q = this.q;
  40792. return serializationObject;
  40793. };
  40794. ;
  40795. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40796. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40797. return null; // null since geometry could be something else than a ground...
  40798. }
  40799. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40800. if (BABYLON.Tags) {
  40801. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40802. }
  40803. scene.pushGeometry(torusKnot, true);
  40804. return torusKnot;
  40805. };
  40806. return TorusKnotGeometry;
  40807. }(_PrimitiveGeometry));
  40808. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40809. //}
  40810. })(BABYLON || (BABYLON = {}));
  40811. //# sourceMappingURL=babylon.geometry.js.map
  40812. var BABYLON;
  40813. (function (BABYLON) {
  40814. /**
  40815. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40816. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40817. */
  40818. var PostProcessManager = /** @class */ (function () {
  40819. /**
  40820. * Creates a new instance PostProcess
  40821. * @param scene The scene that the post process is associated with.
  40822. */
  40823. function PostProcessManager(scene) {
  40824. this._vertexBuffers = {};
  40825. this._scene = scene;
  40826. }
  40827. PostProcessManager.prototype._prepareBuffers = function () {
  40828. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40829. return;
  40830. }
  40831. // VBO
  40832. var vertices = [];
  40833. vertices.push(1, 1);
  40834. vertices.push(-1, 1);
  40835. vertices.push(-1, -1);
  40836. vertices.push(1, -1);
  40837. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40838. this._buildIndexBuffer();
  40839. };
  40840. PostProcessManager.prototype._buildIndexBuffer = function () {
  40841. // Indices
  40842. var indices = [];
  40843. indices.push(0);
  40844. indices.push(1);
  40845. indices.push(2);
  40846. indices.push(0);
  40847. indices.push(2);
  40848. indices.push(3);
  40849. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40850. };
  40851. /**
  40852. * Rebuilds the vertex buffers of the manager.
  40853. */
  40854. PostProcessManager.prototype._rebuild = function () {
  40855. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40856. if (!vb) {
  40857. return;
  40858. }
  40859. vb._rebuild();
  40860. this._buildIndexBuffer();
  40861. };
  40862. // Methods
  40863. /**
  40864. * Prepares a frame to be run through a post process.
  40865. * @param sourceTexture The input texture to the post procesess. (default: null)
  40866. * @param postProcesses An array of post processes to be run. (default: null)
  40867. * @returns True if the post processes were able to be run.
  40868. */
  40869. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40870. if (sourceTexture === void 0) { sourceTexture = null; }
  40871. if (postProcesses === void 0) { postProcesses = null; }
  40872. var camera = this._scene.activeCamera;
  40873. if (!camera) {
  40874. return false;
  40875. }
  40876. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40877. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40878. return false;
  40879. }
  40880. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40881. return true;
  40882. };
  40883. /**
  40884. * Manually render a set of post processes to a texture.
  40885. * @param postProcesses An array of post processes to be run.
  40886. * @param targetTexture The target texture to render to.
  40887. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40888. */
  40889. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40890. if (targetTexture === void 0) { targetTexture = null; }
  40891. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40892. var engine = this._scene.getEngine();
  40893. for (var index = 0; index < postProcesses.length; index++) {
  40894. if (index < postProcesses.length - 1) {
  40895. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40896. }
  40897. else {
  40898. if (targetTexture) {
  40899. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40900. }
  40901. else {
  40902. engine.restoreDefaultFramebuffer();
  40903. }
  40904. }
  40905. var pp = postProcesses[index];
  40906. var effect = pp.apply();
  40907. if (effect) {
  40908. pp.onBeforeRenderObservable.notifyObservers(effect);
  40909. // VBOs
  40910. this._prepareBuffers();
  40911. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40912. // Draw order
  40913. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40914. pp.onAfterRenderObservable.notifyObservers(effect);
  40915. }
  40916. }
  40917. // Restore depth buffer
  40918. engine.setDepthBuffer(true);
  40919. engine.setDepthWrite(true);
  40920. };
  40921. /**
  40922. * Finalize the result of the output of the postprocesses.
  40923. * @param doNotPresent If true the result will not be displayed to the screen.
  40924. * @param targetTexture The target texture to render to.
  40925. * @param faceIndex The index of the face to bind the target texture to.
  40926. * @param postProcesses The array of post processes to render.
  40927. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40928. */
  40929. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40930. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40931. var camera = this._scene.activeCamera;
  40932. if (!camera) {
  40933. return;
  40934. }
  40935. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40936. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40937. return;
  40938. }
  40939. var engine = this._scene.getEngine();
  40940. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40941. var pp = postProcesses[index];
  40942. if (index < len - 1) {
  40943. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40944. }
  40945. else {
  40946. if (targetTexture) {
  40947. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40948. pp._outputTexture = targetTexture;
  40949. }
  40950. else {
  40951. engine.restoreDefaultFramebuffer();
  40952. pp._outputTexture = null;
  40953. }
  40954. }
  40955. if (doNotPresent) {
  40956. break;
  40957. }
  40958. var effect = pp.apply();
  40959. if (effect) {
  40960. pp.onBeforeRenderObservable.notifyObservers(effect);
  40961. // VBOs
  40962. this._prepareBuffers();
  40963. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40964. // Draw order
  40965. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40966. pp.onAfterRenderObservable.notifyObservers(effect);
  40967. }
  40968. }
  40969. // Restore states
  40970. engine.setDepthBuffer(true);
  40971. engine.setDepthWrite(true);
  40972. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40973. };
  40974. /**
  40975. * Disposes of the post process manager.
  40976. */
  40977. PostProcessManager.prototype.dispose = function () {
  40978. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40979. if (buffer) {
  40980. buffer.dispose();
  40981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40982. }
  40983. if (this._indexBuffer) {
  40984. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40985. this._indexBuffer = null;
  40986. }
  40987. };
  40988. return PostProcessManager;
  40989. }());
  40990. BABYLON.PostProcessManager = PostProcessManager;
  40991. })(BABYLON || (BABYLON = {}));
  40992. //# sourceMappingURL=babylon.postProcessManager.js.map
  40993. var BABYLON;
  40994. (function (BABYLON) {
  40995. /**
  40996. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40997. */
  40998. var PerformanceMonitor = /** @class */ (function () {
  40999. /**
  41000. * constructor
  41001. * @param frameSampleSize The number of samples required to saturate the sliding window
  41002. */
  41003. function PerformanceMonitor(frameSampleSize) {
  41004. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41005. this._enabled = true;
  41006. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41007. }
  41008. /**
  41009. * Samples current frame
  41010. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41011. */
  41012. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41013. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41014. if (!this._enabled)
  41015. return;
  41016. if (this._lastFrameTimeMs != null) {
  41017. var dt = timeMs - this._lastFrameTimeMs;
  41018. this._rollingFrameTime.add(dt);
  41019. }
  41020. this._lastFrameTimeMs = timeMs;
  41021. };
  41022. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41023. /**
  41024. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41025. * @return Average frame time in milliseconds
  41026. */
  41027. get: function () {
  41028. return this._rollingFrameTime.average;
  41029. },
  41030. enumerable: true,
  41031. configurable: true
  41032. });
  41033. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41034. /**
  41035. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41036. * @return Frame time variance in milliseconds squared
  41037. */
  41038. get: function () {
  41039. return this._rollingFrameTime.variance;
  41040. },
  41041. enumerable: true,
  41042. configurable: true
  41043. });
  41044. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41045. /**
  41046. * Returns the frame time of the most recent frame
  41047. * @return Frame time in milliseconds
  41048. */
  41049. get: function () {
  41050. return this._rollingFrameTime.history(0);
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41056. /**
  41057. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41058. * @return Framerate in frames per second
  41059. */
  41060. get: function () {
  41061. return 1000.0 / this._rollingFrameTime.average;
  41062. },
  41063. enumerable: true,
  41064. configurable: true
  41065. });
  41066. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41067. /**
  41068. * Returns the average framerate in frames per second using the most recent frame time
  41069. * @return Framerate in frames per second
  41070. */
  41071. get: function () {
  41072. var history = this._rollingFrameTime.history(0);
  41073. if (history === 0) {
  41074. return 0;
  41075. }
  41076. return 1000.0 / history;
  41077. },
  41078. enumerable: true,
  41079. configurable: true
  41080. });
  41081. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41082. /**
  41083. * Returns true if enough samples have been taken to completely fill the sliding window
  41084. * @return true if saturated
  41085. */
  41086. get: function () {
  41087. return this._rollingFrameTime.isSaturated();
  41088. },
  41089. enumerable: true,
  41090. configurable: true
  41091. });
  41092. /**
  41093. * Enables contributions to the sliding window sample set
  41094. */
  41095. PerformanceMonitor.prototype.enable = function () {
  41096. this._enabled = true;
  41097. };
  41098. /**
  41099. * Disables contributions to the sliding window sample set
  41100. * Samples will not be interpolated over the disabled period
  41101. */
  41102. PerformanceMonitor.prototype.disable = function () {
  41103. this._enabled = false;
  41104. //clear last sample to avoid interpolating over the disabled period when next enabled
  41105. this._lastFrameTimeMs = null;
  41106. };
  41107. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41108. /**
  41109. * Returns true if sampling is enabled
  41110. * @return true if enabled
  41111. */
  41112. get: function () {
  41113. return this._enabled;
  41114. },
  41115. enumerable: true,
  41116. configurable: true
  41117. });
  41118. /**
  41119. * Resets performance monitor
  41120. */
  41121. PerformanceMonitor.prototype.reset = function () {
  41122. //clear last sample to avoid interpolating over the disabled period when next enabled
  41123. this._lastFrameTimeMs = null;
  41124. //wipe record
  41125. this._rollingFrameTime.reset();
  41126. };
  41127. return PerformanceMonitor;
  41128. }());
  41129. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41130. /**
  41131. * RollingAverage
  41132. *
  41133. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41134. */
  41135. var RollingAverage = /** @class */ (function () {
  41136. /**
  41137. * constructor
  41138. * @param length The number of samples required to saturate the sliding window
  41139. */
  41140. function RollingAverage(length) {
  41141. this._samples = new Array(length);
  41142. this.reset();
  41143. }
  41144. /**
  41145. * Adds a sample to the sample set
  41146. * @param v The sample value
  41147. */
  41148. RollingAverage.prototype.add = function (v) {
  41149. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41150. var delta;
  41151. //we need to check if we've already wrapped round
  41152. if (this.isSaturated()) {
  41153. //remove bottom of stack from mean
  41154. var bottomValue = this._samples[this._pos];
  41155. delta = bottomValue - this.average;
  41156. this.average -= delta / (this._sampleCount - 1);
  41157. this._m2 -= delta * (bottomValue - this.average);
  41158. }
  41159. else {
  41160. this._sampleCount++;
  41161. }
  41162. //add new value to mean
  41163. delta = v - this.average;
  41164. this.average += delta / (this._sampleCount);
  41165. this._m2 += delta * (v - this.average);
  41166. //set the new variance
  41167. this.variance = this._m2 / (this._sampleCount - 1);
  41168. this._samples[this._pos] = v;
  41169. this._pos++;
  41170. this._pos %= this._samples.length; //positive wrap around
  41171. };
  41172. /**
  41173. * Returns previously added values or null if outside of history or outside the sliding window domain
  41174. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41175. * @return Value previously recorded with add() or null if outside of range
  41176. */
  41177. RollingAverage.prototype.history = function (i) {
  41178. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41179. return 0;
  41180. }
  41181. var i0 = this._wrapPosition(this._pos - 1.0);
  41182. return this._samples[this._wrapPosition(i0 - i)];
  41183. };
  41184. /**
  41185. * Returns true if enough samples have been taken to completely fill the sliding window
  41186. * @return true if sample-set saturated
  41187. */
  41188. RollingAverage.prototype.isSaturated = function () {
  41189. return this._sampleCount >= this._samples.length;
  41190. };
  41191. /**
  41192. * Resets the rolling average (equivalent to 0 samples taken so far)
  41193. */
  41194. RollingAverage.prototype.reset = function () {
  41195. this.average = 0;
  41196. this.variance = 0;
  41197. this._sampleCount = 0;
  41198. this._pos = 0;
  41199. this._m2 = 0;
  41200. };
  41201. /**
  41202. * Wraps a value around the sample range boundaries
  41203. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41204. * @return Wrapped position in sample range
  41205. */
  41206. RollingAverage.prototype._wrapPosition = function (i) {
  41207. var max = this._samples.length;
  41208. return ((i % max) + max) % max;
  41209. };
  41210. return RollingAverage;
  41211. }());
  41212. BABYLON.RollingAverage = RollingAverage;
  41213. })(BABYLON || (BABYLON = {}));
  41214. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41215. var BABYLON;
  41216. (function (BABYLON) {
  41217. /**
  41218. * This groups together the common properties used for image processing either in direct forward pass
  41219. * or through post processing effect depending on the use of the image processing pipeline in your scene
  41220. * or not.
  41221. */
  41222. var ImageProcessingConfiguration = /** @class */ (function () {
  41223. function ImageProcessingConfiguration() {
  41224. /**
  41225. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41226. */
  41227. this.colorCurves = new BABYLON.ColorCurves();
  41228. this._colorCurvesEnabled = false;
  41229. this._colorGradingEnabled = false;
  41230. this._colorGradingWithGreenDepth = true;
  41231. this._colorGradingBGR = true;
  41232. this._exposure = 1.0;
  41233. this._toneMappingEnabled = false;
  41234. this._contrast = 1.0;
  41235. /**
  41236. * Vignette stretch size.
  41237. */
  41238. this.vignetteStretch = 0;
  41239. /**
  41240. * Vignette centre X Offset.
  41241. */
  41242. this.vignetteCentreX = 0;
  41243. /**
  41244. * Vignette centre Y Offset.
  41245. */
  41246. this.vignetteCentreY = 0;
  41247. /**
  41248. * Vignette weight or intensity of the vignette effect.
  41249. */
  41250. this.vignetteWeight = 1.5;
  41251. /**
  41252. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41253. * if vignetteEnabled is set to true.
  41254. */
  41255. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41256. /**
  41257. * Camera field of view used by the Vignette effect.
  41258. */
  41259. this.vignetteCameraFov = 0.5;
  41260. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41261. this._vignetteEnabled = false;
  41262. this._applyByPostProcess = false;
  41263. this._isEnabled = true;
  41264. /**
  41265. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41266. */
  41267. this.onUpdateParameters = new BABYLON.Observable();
  41268. }
  41269. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41270. /**
  41271. * Gets wether the color curves effect is enabled.
  41272. */
  41273. get: function () {
  41274. return this._colorCurvesEnabled;
  41275. },
  41276. /**
  41277. * Sets wether the color curves effect is enabled.
  41278. */
  41279. set: function (value) {
  41280. if (this._colorCurvesEnabled === value) {
  41281. return;
  41282. }
  41283. this._colorCurvesEnabled = value;
  41284. this._updateParameters();
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41290. /**
  41291. * Gets wether the color grading effect is enabled.
  41292. */
  41293. get: function () {
  41294. return this._colorGradingEnabled;
  41295. },
  41296. /**
  41297. * Sets wether the color grading effect is enabled.
  41298. */
  41299. set: function (value) {
  41300. if (this._colorGradingEnabled === value) {
  41301. return;
  41302. }
  41303. this._colorGradingEnabled = value;
  41304. this._updateParameters();
  41305. },
  41306. enumerable: true,
  41307. configurable: true
  41308. });
  41309. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41310. /**
  41311. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41312. */
  41313. get: function () {
  41314. return this._colorGradingWithGreenDepth;
  41315. },
  41316. /**
  41317. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41318. */
  41319. set: function (value) {
  41320. if (this._colorGradingWithGreenDepth === value) {
  41321. return;
  41322. }
  41323. this._colorGradingWithGreenDepth = value;
  41324. this._updateParameters();
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41330. /**
  41331. * Gets wether the color grading texture contains BGR values.
  41332. */
  41333. get: function () {
  41334. return this._colorGradingBGR;
  41335. },
  41336. /**
  41337. * Sets wether the color grading texture contains BGR values.
  41338. */
  41339. set: function (value) {
  41340. if (this._colorGradingBGR === value) {
  41341. return;
  41342. }
  41343. this._colorGradingBGR = value;
  41344. this._updateParameters();
  41345. },
  41346. enumerable: true,
  41347. configurable: true
  41348. });
  41349. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41350. /**
  41351. * Gets the Exposure used in the effect.
  41352. */
  41353. get: function () {
  41354. return this._exposure;
  41355. },
  41356. /**
  41357. * Sets the Exposure used in the effect.
  41358. */
  41359. set: function (value) {
  41360. if (this._exposure === value) {
  41361. return;
  41362. }
  41363. this._exposure = value;
  41364. this._updateParameters();
  41365. },
  41366. enumerable: true,
  41367. configurable: true
  41368. });
  41369. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41370. /**
  41371. * Gets wether the tone mapping effect is enabled.
  41372. */
  41373. get: function () {
  41374. return this._toneMappingEnabled;
  41375. },
  41376. /**
  41377. * Sets wether the tone mapping effect is enabled.
  41378. */
  41379. set: function (value) {
  41380. if (this._toneMappingEnabled === value) {
  41381. return;
  41382. }
  41383. this._toneMappingEnabled = value;
  41384. this._updateParameters();
  41385. },
  41386. enumerable: true,
  41387. configurable: true
  41388. });
  41389. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41390. /**
  41391. * Gets the contrast used in the effect.
  41392. */
  41393. get: function () {
  41394. return this._contrast;
  41395. },
  41396. /**
  41397. * Sets the contrast used in the effect.
  41398. */
  41399. set: function (value) {
  41400. if (this._contrast === value) {
  41401. return;
  41402. }
  41403. this._contrast = value;
  41404. this._updateParameters();
  41405. },
  41406. enumerable: true,
  41407. configurable: true
  41408. });
  41409. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41410. /**
  41411. * Gets the vignette blend mode allowing different kind of effect.
  41412. */
  41413. get: function () {
  41414. return this._vignetteBlendMode;
  41415. },
  41416. /**
  41417. * Sets the vignette blend mode allowing different kind of effect.
  41418. */
  41419. set: function (value) {
  41420. if (this._vignetteBlendMode === value) {
  41421. return;
  41422. }
  41423. this._vignetteBlendMode = value;
  41424. this._updateParameters();
  41425. },
  41426. enumerable: true,
  41427. configurable: true
  41428. });
  41429. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41430. /**
  41431. * Gets wether the vignette effect is enabled.
  41432. */
  41433. get: function () {
  41434. return this._vignetteEnabled;
  41435. },
  41436. /**
  41437. * Sets wether the vignette effect is enabled.
  41438. */
  41439. set: function (value) {
  41440. if (this._vignetteEnabled === value) {
  41441. return;
  41442. }
  41443. this._vignetteEnabled = value;
  41444. this._updateParameters();
  41445. },
  41446. enumerable: true,
  41447. configurable: true
  41448. });
  41449. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41450. /**
  41451. * Gets wether the image processing is applied through a post process or not.
  41452. */
  41453. get: function () {
  41454. return this._applyByPostProcess;
  41455. },
  41456. /**
  41457. * Sets wether the image processing is applied through a post process or not.
  41458. */
  41459. set: function (value) {
  41460. if (this._applyByPostProcess === value) {
  41461. return;
  41462. }
  41463. this._applyByPostProcess = value;
  41464. this._updateParameters();
  41465. },
  41466. enumerable: true,
  41467. configurable: true
  41468. });
  41469. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41470. /**
  41471. * Gets wether the image processing is enabled or not.
  41472. */
  41473. get: function () {
  41474. return this._isEnabled;
  41475. },
  41476. /**
  41477. * Sets wether the image processing is enabled or not.
  41478. */
  41479. set: function (value) {
  41480. if (this._isEnabled === value) {
  41481. return;
  41482. }
  41483. this._isEnabled = value;
  41484. this._updateParameters();
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. /**
  41490. * Method called each time the image processing information changes requires to recompile the effect.
  41491. */
  41492. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41493. this.onUpdateParameters.notifyObservers(this);
  41494. };
  41495. ImageProcessingConfiguration.prototype.getClassName = function () {
  41496. return "ImageProcessingConfiguration";
  41497. };
  41498. /**
  41499. * Prepare the list of uniforms associated with the Image Processing effects.
  41500. * @param uniformsList The list of uniforms used in the effect
  41501. * @param defines the list of defines currently in use
  41502. */
  41503. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41504. if (defines.EXPOSURE) {
  41505. uniforms.push("exposureLinear");
  41506. }
  41507. if (defines.CONTRAST) {
  41508. uniforms.push("contrast");
  41509. }
  41510. if (defines.COLORGRADING) {
  41511. uniforms.push("colorTransformSettings");
  41512. }
  41513. if (defines.VIGNETTE) {
  41514. uniforms.push("vInverseScreenSize");
  41515. uniforms.push("vignetteSettings1");
  41516. uniforms.push("vignetteSettings2");
  41517. }
  41518. if (defines.COLORCURVES) {
  41519. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41520. }
  41521. };
  41522. /**
  41523. * Prepare the list of samplers associated with the Image Processing effects.
  41524. * @param uniformsList The list of uniforms used in the effect
  41525. * @param defines the list of defines currently in use
  41526. */
  41527. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41528. if (defines.COLORGRADING) {
  41529. samplersList.push("txColorTransform");
  41530. }
  41531. };
  41532. /**
  41533. * Prepare the list of defines associated to the shader.
  41534. * @param defines the list of defines to complete
  41535. */
  41536. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41537. if (forPostProcess === void 0) { forPostProcess = false; }
  41538. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41539. defines.VIGNETTE = false;
  41540. defines.TONEMAPPING = false;
  41541. defines.CONTRAST = false;
  41542. defines.EXPOSURE = false;
  41543. defines.COLORCURVES = false;
  41544. defines.COLORGRADING = false;
  41545. defines.COLORGRADING3D = false;
  41546. defines.IMAGEPROCESSING = false;
  41547. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41548. return;
  41549. }
  41550. defines.VIGNETTE = this.vignetteEnabled;
  41551. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41552. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41553. defines.TONEMAPPING = this.toneMappingEnabled;
  41554. defines.CONTRAST = (this.contrast !== 1.0);
  41555. defines.EXPOSURE = (this.exposure !== 1.0);
  41556. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41557. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41558. if (defines.COLORGRADING) {
  41559. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41560. }
  41561. else {
  41562. defines.COLORGRADING3D = false;
  41563. }
  41564. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41565. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41566. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41567. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41568. };
  41569. /**
  41570. * Returns true if all the image processing information are ready.
  41571. */
  41572. ImageProcessingConfiguration.prototype.isReady = function () {
  41573. // Color Grading texure can not be none blocking.
  41574. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41575. };
  41576. /**
  41577. * Binds the image processing to the shader.
  41578. * @param effect The effect to bind to
  41579. */
  41580. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41581. if (aspectRatio === void 0) { aspectRatio = 1; }
  41582. // Color Curves
  41583. if (this._colorCurvesEnabled && this.colorCurves) {
  41584. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41585. }
  41586. // Vignette
  41587. if (this._vignetteEnabled) {
  41588. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41589. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41590. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41591. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41592. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41593. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41594. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41595. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41596. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41597. var vignettePower = -2.0 * this.vignetteWeight;
  41598. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41599. }
  41600. // Exposure
  41601. effect.setFloat("exposureLinear", this.exposure);
  41602. // Contrast
  41603. effect.setFloat("contrast", this.contrast);
  41604. // Color transform settings
  41605. if (this.colorGradingTexture) {
  41606. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41607. var textureSize = this.colorGradingTexture.getSize().height;
  41608. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41609. 0.5 / textureSize, // textureOffset
  41610. textureSize, // textureSize
  41611. this.colorGradingTexture.level // weight
  41612. );
  41613. }
  41614. };
  41615. /**
  41616. * Clones the current image processing instance.
  41617. * @return The cloned image processing
  41618. */
  41619. ImageProcessingConfiguration.prototype.clone = function () {
  41620. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41621. };
  41622. /**
  41623. * Serializes the current image processing instance to a json representation.
  41624. * @return a JSON representation
  41625. */
  41626. ImageProcessingConfiguration.prototype.serialize = function () {
  41627. return BABYLON.SerializationHelper.Serialize(this);
  41628. };
  41629. /**
  41630. * Parses the image processing from a json representation.
  41631. * @param source the JSON source to parse
  41632. * @return The parsed image processing
  41633. */
  41634. ImageProcessingConfiguration.Parse = function (source) {
  41635. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41636. };
  41637. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41638. /**
  41639. * Used to apply the vignette as a mix with the pixel color.
  41640. */
  41641. get: function () {
  41642. return this._VIGNETTEMODE_MULTIPLY;
  41643. },
  41644. enumerable: true,
  41645. configurable: true
  41646. });
  41647. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41648. /**
  41649. * Used to apply the vignette as a replacement of the pixel color.
  41650. */
  41651. get: function () {
  41652. return this._VIGNETTEMODE_OPAQUE;
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. // Static constants associated to the image processing.
  41658. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41659. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41660. __decorate([
  41661. BABYLON.serializeAsColorCurves()
  41662. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41663. __decorate([
  41664. BABYLON.serialize()
  41665. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41666. __decorate([
  41667. BABYLON.serializeAsTexture()
  41668. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41669. __decorate([
  41670. BABYLON.serialize()
  41671. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41672. __decorate([
  41673. BABYLON.serialize()
  41674. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41675. __decorate([
  41676. BABYLON.serialize()
  41677. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41678. __decorate([
  41679. BABYLON.serialize()
  41680. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41681. __decorate([
  41682. BABYLON.serialize()
  41683. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41684. __decorate([
  41685. BABYLON.serialize()
  41686. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41687. __decorate([
  41688. BABYLON.serialize()
  41689. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41690. __decorate([
  41691. BABYLON.serialize()
  41692. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41693. __decorate([
  41694. BABYLON.serialize()
  41695. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41696. __decorate([
  41697. BABYLON.serialize()
  41698. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41699. __decorate([
  41700. BABYLON.serializeAsColor4()
  41701. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41702. __decorate([
  41703. BABYLON.serialize()
  41704. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41705. __decorate([
  41706. BABYLON.serialize()
  41707. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41708. __decorate([
  41709. BABYLON.serialize()
  41710. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41711. __decorate([
  41712. BABYLON.serialize()
  41713. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41714. __decorate([
  41715. BABYLON.serialize()
  41716. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41717. return ImageProcessingConfiguration;
  41718. }());
  41719. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41720. })(BABYLON || (BABYLON = {}));
  41721. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41722. var BABYLON;
  41723. (function (BABYLON) {
  41724. /**
  41725. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41726. * It can help converting any input color in a desired output one. This can then be used to create effects
  41727. * from sepia, black and white to sixties or futuristic rendering...
  41728. *
  41729. * The only supported format is currently 3dl.
  41730. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41731. */
  41732. var ColorGradingTexture = /** @class */ (function (_super) {
  41733. __extends(ColorGradingTexture, _super);
  41734. /**
  41735. * Instantiates a ColorGradingTexture from the following parameters.
  41736. *
  41737. * @param url The location of the color gradind data (currently only supporting 3dl)
  41738. * @param scene The scene the texture will be used in
  41739. */
  41740. function ColorGradingTexture(url, scene) {
  41741. var _this = _super.call(this, scene) || this;
  41742. if (!url) {
  41743. return _this;
  41744. }
  41745. _this._engine = scene.getEngine();
  41746. _this._textureMatrix = BABYLON.Matrix.Identity();
  41747. _this.name = url;
  41748. _this.url = url;
  41749. _this.hasAlpha = false;
  41750. _this.isCube = false;
  41751. _this.is3D = _this._engine.webGLVersion > 1;
  41752. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41753. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41754. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41755. _this.anisotropicFilteringLevel = 1;
  41756. _this._texture = _this._getFromCache(url, true);
  41757. if (!_this._texture) {
  41758. if (!scene.useDelayedTextureLoading) {
  41759. _this.loadTexture();
  41760. }
  41761. else {
  41762. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41763. }
  41764. }
  41765. return _this;
  41766. }
  41767. /**
  41768. * Returns the texture matrix used in most of the material.
  41769. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41770. */
  41771. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41772. return this._textureMatrix;
  41773. };
  41774. /**
  41775. * Occurs when the file being loaded is a .3dl LUT file.
  41776. */
  41777. ColorGradingTexture.prototype.load3dlTexture = function () {
  41778. var engine = this._engine;
  41779. var texture;
  41780. if (engine.webGLVersion === 1) {
  41781. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41782. }
  41783. else {
  41784. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41785. }
  41786. this._texture = texture;
  41787. var callback = function (text) {
  41788. if (typeof text !== "string") {
  41789. return;
  41790. }
  41791. var data = null;
  41792. var tempData = null;
  41793. var line;
  41794. var lines = text.split('\n');
  41795. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41796. var maxColor = 0;
  41797. for (var i = 0; i < lines.length; i++) {
  41798. line = lines[i];
  41799. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41800. continue;
  41801. if (line.indexOf('#') === 0)
  41802. continue;
  41803. var words = line.split(" ");
  41804. if (size === 0) {
  41805. // Number of space + one
  41806. size = words.length;
  41807. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41808. tempData = new Float32Array(size * size * size * 4);
  41809. continue;
  41810. }
  41811. if (size != 0) {
  41812. var r = Math.max(parseInt(words[0]), 0);
  41813. var g = Math.max(parseInt(words[1]), 0);
  41814. var b = Math.max(parseInt(words[2]), 0);
  41815. maxColor = Math.max(r, maxColor);
  41816. maxColor = Math.max(g, maxColor);
  41817. maxColor = Math.max(b, maxColor);
  41818. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41819. if (tempData) {
  41820. tempData[pixelStorageIndex + 0] = r;
  41821. tempData[pixelStorageIndex + 1] = g;
  41822. tempData[pixelStorageIndex + 2] = b;
  41823. }
  41824. pixelIndexSlice++;
  41825. if (pixelIndexSlice % size == 0) {
  41826. pixelIndexH++;
  41827. pixelIndexSlice = 0;
  41828. if (pixelIndexH % size == 0) {
  41829. pixelIndexW++;
  41830. pixelIndexH = 0;
  41831. }
  41832. }
  41833. }
  41834. }
  41835. if (tempData && data) {
  41836. for (var i = 0; i < tempData.length; i++) {
  41837. if (i > 0 && (i + 1) % 4 === 0) {
  41838. data[i] = 255;
  41839. }
  41840. else {
  41841. var value = tempData[i];
  41842. data[i] = (value / maxColor * 255);
  41843. }
  41844. }
  41845. }
  41846. if (texture.is3D) {
  41847. texture.updateSize(size, size, size);
  41848. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41849. }
  41850. else {
  41851. texture.updateSize(size * size, size);
  41852. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41853. }
  41854. };
  41855. var scene = this.getScene();
  41856. if (scene) {
  41857. scene._loadFile(this.url, callback);
  41858. }
  41859. else {
  41860. this._engine._loadFile(this.url, callback);
  41861. }
  41862. return this._texture;
  41863. };
  41864. /**
  41865. * Starts the loading process of the texture.
  41866. */
  41867. ColorGradingTexture.prototype.loadTexture = function () {
  41868. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41869. this.load3dlTexture();
  41870. }
  41871. };
  41872. /**
  41873. * Clones the color gradind texture.
  41874. */
  41875. ColorGradingTexture.prototype.clone = function () {
  41876. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41877. // Base texture
  41878. newTexture.level = this.level;
  41879. return newTexture;
  41880. };
  41881. /**
  41882. * Called during delayed load for textures.
  41883. */
  41884. ColorGradingTexture.prototype.delayLoad = function () {
  41885. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41886. return;
  41887. }
  41888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41889. this._texture = this._getFromCache(this.url, true);
  41890. if (!this._texture) {
  41891. this.loadTexture();
  41892. }
  41893. };
  41894. /**
  41895. * Parses a color grading texture serialized by Babylon.
  41896. * @param parsedTexture The texture information being parsedTexture
  41897. * @param scene The scene to load the texture in
  41898. * @param rootUrl The root url of the data assets to load
  41899. * @return A color gradind texture
  41900. */
  41901. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41902. var texture = null;
  41903. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41904. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41905. texture.name = parsedTexture.name;
  41906. texture.level = parsedTexture.level;
  41907. }
  41908. return texture;
  41909. };
  41910. /**
  41911. * Serializes the LUT texture to json format.
  41912. */
  41913. ColorGradingTexture.prototype.serialize = function () {
  41914. if (!this.name) {
  41915. return null;
  41916. }
  41917. var serializationObject = {};
  41918. serializationObject.name = this.name;
  41919. serializationObject.level = this.level;
  41920. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41921. return serializationObject;
  41922. };
  41923. /**
  41924. * Empty line regex stored for GC.
  41925. */
  41926. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41927. return ColorGradingTexture;
  41928. }(BABYLON.BaseTexture));
  41929. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41930. })(BABYLON || (BABYLON = {}));
  41931. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41932. var BABYLON;
  41933. (function (BABYLON) {
  41934. /**
  41935. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41936. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41937. * 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;
  41938. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41939. */
  41940. var ColorCurves = /** @class */ (function () {
  41941. function ColorCurves() {
  41942. this._dirty = true;
  41943. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41944. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41945. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41946. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41947. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41948. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41949. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41950. this._globalHue = 30;
  41951. this._globalDensity = 0;
  41952. this._globalSaturation = 0;
  41953. this._globalExposure = 0;
  41954. this._highlightsHue = 30;
  41955. this._highlightsDensity = 0;
  41956. this._highlightsSaturation = 0;
  41957. this._highlightsExposure = 0;
  41958. this._midtonesHue = 30;
  41959. this._midtonesDensity = 0;
  41960. this._midtonesSaturation = 0;
  41961. this._midtonesExposure = 0;
  41962. this._shadowsHue = 30;
  41963. this._shadowsDensity = 0;
  41964. this._shadowsSaturation = 0;
  41965. this._shadowsExposure = 0;
  41966. }
  41967. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41968. /**
  41969. * Gets the global Hue value.
  41970. * 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).
  41971. */
  41972. get: function () {
  41973. return this._globalHue;
  41974. },
  41975. /**
  41976. * Sets the global Hue value.
  41977. * 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).
  41978. */
  41979. set: function (value) {
  41980. this._globalHue = value;
  41981. this._dirty = true;
  41982. },
  41983. enumerable: true,
  41984. configurable: true
  41985. });
  41986. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41987. /**
  41988. * Gets the global Density value.
  41989. * 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.
  41990. * Values less than zero provide a filter of opposite hue.
  41991. */
  41992. get: function () {
  41993. return this._globalDensity;
  41994. },
  41995. /**
  41996. * Sets the global Density value.
  41997. * 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.
  41998. * Values less than zero provide a filter of opposite hue.
  41999. */
  42000. set: function (value) {
  42001. this._globalDensity = value;
  42002. this._dirty = true;
  42003. },
  42004. enumerable: true,
  42005. configurable: true
  42006. });
  42007. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  42008. /**
  42009. * Gets the global Saturation value.
  42010. * 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.
  42011. */
  42012. get: function () {
  42013. return this._globalSaturation;
  42014. },
  42015. /**
  42016. * Sets the global Saturation value.
  42017. * 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.
  42018. */
  42019. set: function (value) {
  42020. this._globalSaturation = value;
  42021. this._dirty = true;
  42022. },
  42023. enumerable: true,
  42024. configurable: true
  42025. });
  42026. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  42027. /**
  42028. * Gets the global Exposure value.
  42029. * 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.
  42030. */
  42031. get: function () {
  42032. return this._globalExposure;
  42033. },
  42034. /**
  42035. * Sets the global Exposure value.
  42036. * 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.
  42037. */
  42038. set: function (value) {
  42039. this._globalExposure = value;
  42040. this._dirty = true;
  42041. },
  42042. enumerable: true,
  42043. configurable: true
  42044. });
  42045. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  42046. /**
  42047. * Gets the highlights Hue value.
  42048. * 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).
  42049. */
  42050. get: function () {
  42051. return this._highlightsHue;
  42052. },
  42053. /**
  42054. * Sets the highlights Hue value.
  42055. * 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).
  42056. */
  42057. set: function (value) {
  42058. this._highlightsHue = value;
  42059. this._dirty = true;
  42060. },
  42061. enumerable: true,
  42062. configurable: true
  42063. });
  42064. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  42065. /**
  42066. * Gets the highlights Density value.
  42067. * 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.
  42068. * Values less than zero provide a filter of opposite hue.
  42069. */
  42070. get: function () {
  42071. return this._highlightsDensity;
  42072. },
  42073. /**
  42074. * Sets the highlights Density value.
  42075. * 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.
  42076. * Values less than zero provide a filter of opposite hue.
  42077. */
  42078. set: function (value) {
  42079. this._highlightsDensity = value;
  42080. this._dirty = true;
  42081. },
  42082. enumerable: true,
  42083. configurable: true
  42084. });
  42085. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  42086. /**
  42087. * Gets the highlights Saturation value.
  42088. * 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.
  42089. */
  42090. get: function () {
  42091. return this._highlightsSaturation;
  42092. },
  42093. /**
  42094. * Sets the highlights Saturation value.
  42095. * 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.
  42096. */
  42097. set: function (value) {
  42098. this._highlightsSaturation = value;
  42099. this._dirty = true;
  42100. },
  42101. enumerable: true,
  42102. configurable: true
  42103. });
  42104. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  42105. /**
  42106. * Gets the highlights Exposure value.
  42107. * 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.
  42108. */
  42109. get: function () {
  42110. return this._highlightsExposure;
  42111. },
  42112. /**
  42113. * Sets the highlights Exposure value.
  42114. * 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.
  42115. */
  42116. set: function (value) {
  42117. this._highlightsExposure = value;
  42118. this._dirty = true;
  42119. },
  42120. enumerable: true,
  42121. configurable: true
  42122. });
  42123. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  42124. /**
  42125. * Gets the midtones Hue value.
  42126. * 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).
  42127. */
  42128. get: function () {
  42129. return this._midtonesHue;
  42130. },
  42131. /**
  42132. * Sets the midtones Hue value.
  42133. * 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).
  42134. */
  42135. set: function (value) {
  42136. this._midtonesHue = value;
  42137. this._dirty = true;
  42138. },
  42139. enumerable: true,
  42140. configurable: true
  42141. });
  42142. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  42143. /**
  42144. * Gets the midtones Density value.
  42145. * 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.
  42146. * Values less than zero provide a filter of opposite hue.
  42147. */
  42148. get: function () {
  42149. return this._midtonesDensity;
  42150. },
  42151. /**
  42152. * Sets the midtones Density value.
  42153. * 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.
  42154. * Values less than zero provide a filter of opposite hue.
  42155. */
  42156. set: function (value) {
  42157. this._midtonesDensity = value;
  42158. this._dirty = true;
  42159. },
  42160. enumerable: true,
  42161. configurable: true
  42162. });
  42163. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  42164. /**
  42165. * Gets the midtones Saturation value.
  42166. * 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.
  42167. */
  42168. get: function () {
  42169. return this._midtonesSaturation;
  42170. },
  42171. /**
  42172. * Sets the midtones Saturation value.
  42173. * 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.
  42174. */
  42175. set: function (value) {
  42176. this._midtonesSaturation = value;
  42177. this._dirty = true;
  42178. },
  42179. enumerable: true,
  42180. configurable: true
  42181. });
  42182. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  42183. /**
  42184. * Gets the midtones Exposure value.
  42185. * 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.
  42186. */
  42187. get: function () {
  42188. return this._midtonesExposure;
  42189. },
  42190. /**
  42191. * Sets the midtones Exposure value.
  42192. * 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.
  42193. */
  42194. set: function (value) {
  42195. this._midtonesExposure = value;
  42196. this._dirty = true;
  42197. },
  42198. enumerable: true,
  42199. configurable: true
  42200. });
  42201. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  42202. /**
  42203. * Gets the shadows Hue value.
  42204. * 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).
  42205. */
  42206. get: function () {
  42207. return this._shadowsHue;
  42208. },
  42209. /**
  42210. * Sets the shadows Hue value.
  42211. * 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).
  42212. */
  42213. set: function (value) {
  42214. this._shadowsHue = value;
  42215. this._dirty = true;
  42216. },
  42217. enumerable: true,
  42218. configurable: true
  42219. });
  42220. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  42221. /**
  42222. * Gets the shadows Density value.
  42223. * 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.
  42224. * Values less than zero provide a filter of opposite hue.
  42225. */
  42226. get: function () {
  42227. return this._shadowsDensity;
  42228. },
  42229. /**
  42230. * Sets the shadows Density value.
  42231. * 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.
  42232. * Values less than zero provide a filter of opposite hue.
  42233. */
  42234. set: function (value) {
  42235. this._shadowsDensity = value;
  42236. this._dirty = true;
  42237. },
  42238. enumerable: true,
  42239. configurable: true
  42240. });
  42241. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42242. /**
  42243. * Gets the shadows Saturation value.
  42244. * 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.
  42245. */
  42246. get: function () {
  42247. return this._shadowsSaturation;
  42248. },
  42249. /**
  42250. * Sets the shadows Saturation value.
  42251. * 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.
  42252. */
  42253. set: function (value) {
  42254. this._shadowsSaturation = value;
  42255. this._dirty = true;
  42256. },
  42257. enumerable: true,
  42258. configurable: true
  42259. });
  42260. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42261. /**
  42262. * Gets the shadows Exposure value.
  42263. * 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.
  42264. */
  42265. get: function () {
  42266. return this._shadowsExposure;
  42267. },
  42268. /**
  42269. * Sets the shadows Exposure value.
  42270. * 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.
  42271. */
  42272. set: function (value) {
  42273. this._shadowsExposure = value;
  42274. this._dirty = true;
  42275. },
  42276. enumerable: true,
  42277. configurable: true
  42278. });
  42279. ColorCurves.prototype.getClassName = function () {
  42280. return "ColorCurves";
  42281. };
  42282. /**
  42283. * Binds the color curves to the shader.
  42284. * @param colorCurves The color curve to bind
  42285. * @param effect The effect to bind to
  42286. */
  42287. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42288. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42289. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42290. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42291. if (colorCurves._dirty) {
  42292. colorCurves._dirty = false;
  42293. // Fill in global info.
  42294. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42295. // Compute highlights info.
  42296. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42297. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42298. // Compute midtones info.
  42299. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42300. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42301. // Compute shadows info.
  42302. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42303. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42304. // Compute deltas (neutral is midtones).
  42305. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42306. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42307. }
  42308. if (effect) {
  42309. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42310. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42311. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42312. }
  42313. };
  42314. /**
  42315. * Prepare the list of uniforms associated with the ColorCurves effects.
  42316. * @param uniformsList The list of uniforms used in the effect
  42317. */
  42318. ColorCurves.PrepareUniforms = function (uniformsList) {
  42319. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42320. };
  42321. /**
  42322. * Returns color grading data based on a hue, density, saturation and exposure value.
  42323. * @param filterHue The hue of the color filter.
  42324. * @param filterDensity The density of the color filter.
  42325. * @param saturation The saturation.
  42326. * @param exposure The exposure.
  42327. * @param result The result data container.
  42328. */
  42329. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42330. if (hue == null) {
  42331. return;
  42332. }
  42333. hue = ColorCurves.clamp(hue, 0, 360);
  42334. density = ColorCurves.clamp(density, -100, 100);
  42335. saturation = ColorCurves.clamp(saturation, -100, 100);
  42336. exposure = ColorCurves.clamp(exposure, -100, 100);
  42337. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42338. // so that the maximum filter density is only 50% control. This provides fine control
  42339. // for small values and reasonable range.
  42340. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42341. density *= 0.5;
  42342. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42343. if (density < 0) {
  42344. density *= -1;
  42345. hue = (hue + 180) % 360;
  42346. }
  42347. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42348. result.scaleToRef(2, result);
  42349. result.a = 1 + 0.01 * saturation;
  42350. };
  42351. /**
  42352. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42353. * @param value The input slider value in range [-100,100].
  42354. * @returns Adjusted value.
  42355. */
  42356. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42357. value /= 100;
  42358. var x = Math.abs(value);
  42359. x = Math.pow(x, 2);
  42360. if (value < 0) {
  42361. x *= -1;
  42362. }
  42363. x *= 100;
  42364. return x;
  42365. };
  42366. /**
  42367. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42368. * @param hue The hue (H) input.
  42369. * @param saturation The saturation (S) input.
  42370. * @param brightness The brightness (B) input.
  42371. * @result An RGBA color represented as Vector4.
  42372. */
  42373. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42374. var h = ColorCurves.clamp(hue, 0, 360);
  42375. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42376. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42377. if (s === 0) {
  42378. result.r = v;
  42379. result.g = v;
  42380. result.b = v;
  42381. }
  42382. else {
  42383. // sector 0 to 5
  42384. h /= 60;
  42385. var i = Math.floor(h);
  42386. // fractional part of h
  42387. var f = h - i;
  42388. var p = v * (1 - s);
  42389. var q = v * (1 - s * f);
  42390. var t = v * (1 - s * (1 - f));
  42391. switch (i) {
  42392. case 0:
  42393. result.r = v;
  42394. result.g = t;
  42395. result.b = p;
  42396. break;
  42397. case 1:
  42398. result.r = q;
  42399. result.g = v;
  42400. result.b = p;
  42401. break;
  42402. case 2:
  42403. result.r = p;
  42404. result.g = v;
  42405. result.b = t;
  42406. break;
  42407. case 3:
  42408. result.r = p;
  42409. result.g = q;
  42410. result.b = v;
  42411. break;
  42412. case 4:
  42413. result.r = t;
  42414. result.g = p;
  42415. result.b = v;
  42416. break;
  42417. default: // case 5:
  42418. result.r = v;
  42419. result.g = p;
  42420. result.b = q;
  42421. break;
  42422. }
  42423. }
  42424. result.a = 1;
  42425. };
  42426. /**
  42427. * Returns a value clamped between min and max
  42428. * @param value The value to clamp
  42429. * @param min The minimum of value
  42430. * @param max The maximum of value
  42431. * @returns The clamped value.
  42432. */
  42433. ColorCurves.clamp = function (value, min, max) {
  42434. return Math.min(Math.max(value, min), max);
  42435. };
  42436. /**
  42437. * Clones the current color curve instance.
  42438. * @return The cloned curves
  42439. */
  42440. ColorCurves.prototype.clone = function () {
  42441. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42442. };
  42443. /**
  42444. * Serializes the current color curve instance to a json representation.
  42445. * @return a JSON representation
  42446. */
  42447. ColorCurves.prototype.serialize = function () {
  42448. return BABYLON.SerializationHelper.Serialize(this);
  42449. };
  42450. /**
  42451. * Parses the color curve from a json representation.
  42452. * @param source the JSON source to parse
  42453. * @return The parsed curves
  42454. */
  42455. ColorCurves.Parse = function (source) {
  42456. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42457. };
  42458. __decorate([
  42459. BABYLON.serialize()
  42460. ], ColorCurves.prototype, "_globalHue", void 0);
  42461. __decorate([
  42462. BABYLON.serialize()
  42463. ], ColorCurves.prototype, "_globalDensity", void 0);
  42464. __decorate([
  42465. BABYLON.serialize()
  42466. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42467. __decorate([
  42468. BABYLON.serialize()
  42469. ], ColorCurves.prototype, "_globalExposure", void 0);
  42470. __decorate([
  42471. BABYLON.serialize()
  42472. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42473. __decorate([
  42474. BABYLON.serialize()
  42475. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42476. __decorate([
  42477. BABYLON.serialize()
  42478. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42479. __decorate([
  42480. BABYLON.serialize()
  42481. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42482. __decorate([
  42483. BABYLON.serialize()
  42484. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42485. __decorate([
  42486. BABYLON.serialize()
  42487. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42488. __decorate([
  42489. BABYLON.serialize()
  42490. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42491. __decorate([
  42492. BABYLON.serialize()
  42493. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42494. return ColorCurves;
  42495. }());
  42496. BABYLON.ColorCurves = ColorCurves;
  42497. })(BABYLON || (BABYLON = {}));
  42498. //# sourceMappingURL=babylon.colorCurves.js.map
  42499. //# sourceMappingURL=babylon.behavior.js.map
  42500. var BABYLON;
  42501. (function (BABYLON) {
  42502. /**
  42503. * "Static Class" containing the most commonly used helper while dealing with material for
  42504. * rendering purpose.
  42505. *
  42506. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42507. *
  42508. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42509. */
  42510. var MaterialHelper = /** @class */ (function () {
  42511. function MaterialHelper() {
  42512. }
  42513. /**
  42514. * Bind the current view position to an effect.
  42515. * @param effect The effect to be bound
  42516. * @param scene The scene the eyes position is used from
  42517. */
  42518. MaterialHelper.BindEyePosition = function (effect, scene) {
  42519. if (scene._forcedViewPosition) {
  42520. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42521. return;
  42522. }
  42523. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42524. };
  42525. /**
  42526. * Helps preparing the defines values about the UVs in used in the effect.
  42527. * UVs are shared as much as we can accross chanels in the shaders.
  42528. * @param texture The texture we are preparing the UVs for
  42529. * @param defines The defines to update
  42530. * @param key The chanel key "diffuse", "specular"... used in the shader
  42531. */
  42532. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42533. defines._needUVs = true;
  42534. defines[key] = true;
  42535. if (texture.getTextureMatrix().isIdentity(true)) {
  42536. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42537. if (texture.coordinatesIndex === 0) {
  42538. defines["MAINUV1"] = true;
  42539. }
  42540. else {
  42541. defines["MAINUV2"] = true;
  42542. }
  42543. }
  42544. else {
  42545. defines[key + "DIRECTUV"] = 0;
  42546. }
  42547. };
  42548. /**
  42549. * Binds a texture matrix value to its corrsponding uniform
  42550. * @param texture The texture to bind the matrix for
  42551. * @param uniformBuffer The uniform buffer receivin the data
  42552. * @param key The chanel key "diffuse", "specular"... used in the shader
  42553. */
  42554. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42555. var matrix = texture.getTextureMatrix();
  42556. if (!matrix.isIdentity(true)) {
  42557. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42558. }
  42559. };
  42560. /**
  42561. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42562. * @param mesh defines the current mesh
  42563. * @param scene defines the current scene
  42564. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42565. * @param pointsCloud defines if point cloud rendering has to be turned on
  42566. * @param fogEnabled defines if fog has to be turned on
  42567. * @param alphaTest defines if alpha testing has to be turned on
  42568. * @param defines defines the current list of defines
  42569. */
  42570. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42571. if (defines._areMiscDirty) {
  42572. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42573. defines["POINTSIZE"] = pointsCloud;
  42574. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42575. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42576. defines["ALPHATEST"] = alphaTest;
  42577. }
  42578. };
  42579. /**
  42580. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42581. * @param scene defines the current scene
  42582. * @param engine defines the current engine
  42583. * @param defines specifies the list of active defines
  42584. * @param useInstances defines if instances have to be turned on
  42585. * @param useClipPlane defines if clip plane have to be turned on
  42586. */
  42587. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42588. if (useClipPlane === void 0) { useClipPlane = null; }
  42589. var changed = false;
  42590. if (useClipPlane == null) {
  42591. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42592. }
  42593. if (defines["CLIPPLANE"] !== useClipPlane) {
  42594. defines["CLIPPLANE"] = useClipPlane;
  42595. changed = true;
  42596. }
  42597. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42598. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42599. changed = true;
  42600. }
  42601. if (defines["INSTANCES"] !== useInstances) {
  42602. defines["INSTANCES"] = useInstances;
  42603. changed = true;
  42604. }
  42605. if (changed) {
  42606. defines.markAsUnprocessed();
  42607. }
  42608. };
  42609. /**
  42610. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42611. * @param mesh The mesh containing the geometry data we will draw
  42612. * @param defines The defines to update
  42613. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42614. * @param useBones Precise whether bones should be used or not (override mesh info)
  42615. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42616. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42617. * @returns false if defines are considered not dirty and have not been checked
  42618. */
  42619. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42620. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42621. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42622. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42623. return false;
  42624. }
  42625. defines._normals = defines._needNormals;
  42626. defines._uvs = defines._needUVs;
  42627. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42628. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42629. defines["TANGENT"] = true;
  42630. }
  42631. if (defines._needUVs) {
  42632. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42633. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42634. }
  42635. else {
  42636. defines["UV1"] = false;
  42637. defines["UV2"] = false;
  42638. }
  42639. if (useVertexColor) {
  42640. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42641. defines["VERTEXCOLOR"] = hasVertexColors;
  42642. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42643. }
  42644. if (useBones) {
  42645. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42646. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42647. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42648. }
  42649. else {
  42650. defines["NUM_BONE_INFLUENCERS"] = 0;
  42651. defines["BonesPerMesh"] = 0;
  42652. }
  42653. }
  42654. if (useMorphTargets) {
  42655. var manager = mesh.morphTargetManager;
  42656. if (manager) {
  42657. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42658. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42659. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42660. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42661. }
  42662. else {
  42663. defines["MORPHTARGETS_TANGENT"] = false;
  42664. defines["MORPHTARGETS_NORMAL"] = false;
  42665. defines["MORPHTARGETS"] = false;
  42666. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42667. }
  42668. }
  42669. return true;
  42670. };
  42671. /**
  42672. * Prepares the defines related to the light information passed in parameter
  42673. * @param scene The scene we are intending to draw
  42674. * @param mesh The mesh the effect is compiling for
  42675. * @param defines The defines to update
  42676. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42677. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42678. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42679. * @returns true if normals will be required for the rest of the effect
  42680. */
  42681. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42682. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42683. if (disableLighting === void 0) { disableLighting = false; }
  42684. if (!defines._areLightsDirty) {
  42685. return defines._needNormals;
  42686. }
  42687. var lightIndex = 0;
  42688. var needNormals = false;
  42689. var needRebuild = false;
  42690. var lightmapMode = false;
  42691. var shadowEnabled = false;
  42692. var specularEnabled = false;
  42693. if (scene.lightsEnabled && !disableLighting) {
  42694. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42695. var light = _a[_i];
  42696. needNormals = true;
  42697. if (defines["LIGHT" + lightIndex] === undefined) {
  42698. needRebuild = true;
  42699. }
  42700. defines["LIGHT" + lightIndex] = true;
  42701. defines["SPOTLIGHT" + lightIndex] = false;
  42702. defines["HEMILIGHT" + lightIndex] = false;
  42703. defines["POINTLIGHT" + lightIndex] = false;
  42704. defines["DIRLIGHT" + lightIndex] = false;
  42705. var type;
  42706. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42707. type = "SPOTLIGHT" + lightIndex;
  42708. var spotLight = light;
  42709. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42710. }
  42711. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42712. type = "HEMILIGHT" + lightIndex;
  42713. }
  42714. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42715. type = "POINTLIGHT" + lightIndex;
  42716. }
  42717. else {
  42718. type = "DIRLIGHT" + lightIndex;
  42719. }
  42720. defines[type] = true;
  42721. // Specular
  42722. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42723. specularEnabled = true;
  42724. }
  42725. // Shadows
  42726. defines["SHADOW" + lightIndex] = false;
  42727. defines["SHADOWPCF" + lightIndex] = false;
  42728. defines["SHADOWPCSS" + lightIndex] = false;
  42729. defines["SHADOWPOISSON" + lightIndex] = false;
  42730. defines["SHADOWESM" + lightIndex] = false;
  42731. defines["SHADOWCUBE" + lightIndex] = false;
  42732. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42733. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42734. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42735. var shadowGenerator = light.getShadowGenerator();
  42736. if (shadowGenerator) {
  42737. shadowEnabled = true;
  42738. shadowGenerator.prepareDefines(defines, lightIndex);
  42739. }
  42740. }
  42741. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42742. lightmapMode = true;
  42743. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42744. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42745. }
  42746. else {
  42747. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42748. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42749. }
  42750. lightIndex++;
  42751. if (lightIndex === maxSimultaneousLights)
  42752. break;
  42753. }
  42754. }
  42755. defines["SPECULARTERM"] = specularEnabled;
  42756. defines["SHADOWS"] = shadowEnabled;
  42757. // Resetting all other lights if any
  42758. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42759. if (defines["LIGHT" + index] !== undefined) {
  42760. defines["LIGHT" + index] = false;
  42761. defines["HEMILIGHT" + lightIndex] = false;
  42762. defines["POINTLIGHT" + lightIndex] = false;
  42763. defines["DIRLIGHT" + lightIndex] = false;
  42764. defines["SPOTLIGHT" + lightIndex] = false;
  42765. defines["SHADOW" + lightIndex] = false;
  42766. }
  42767. }
  42768. var caps = scene.getEngine().getCaps();
  42769. if (defines["SHADOWFLOAT"] === undefined) {
  42770. needRebuild = true;
  42771. }
  42772. defines["SHADOWFLOAT"] = shadowEnabled &&
  42773. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42774. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42775. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42776. if (needRebuild) {
  42777. defines.rebuild();
  42778. }
  42779. return needNormals;
  42780. };
  42781. /**
  42782. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42783. * that won t be acctive due to defines being turned off.
  42784. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42785. * @param samplersList The samplers list
  42786. * @param defines The defines helping in the list generation
  42787. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42788. */
  42789. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42790. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42791. var uniformsList;
  42792. var uniformBuffersList = null;
  42793. if (uniformsListOrOptions.uniformsNames) {
  42794. var options = uniformsListOrOptions;
  42795. uniformsList = options.uniformsNames;
  42796. uniformBuffersList = options.uniformBuffersNames;
  42797. samplersList = options.samplers;
  42798. defines = options.defines;
  42799. maxSimultaneousLights = options.maxSimultaneousLights;
  42800. }
  42801. else {
  42802. uniformsList = uniformsListOrOptions;
  42803. if (!samplersList) {
  42804. samplersList = [];
  42805. }
  42806. }
  42807. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42808. if (!defines["LIGHT" + lightIndex]) {
  42809. break;
  42810. }
  42811. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42812. if (uniformBuffersList) {
  42813. uniformBuffersList.push("Light" + lightIndex);
  42814. }
  42815. samplersList.push("shadowSampler" + lightIndex);
  42816. samplersList.push("depthSampler" + lightIndex);
  42817. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42818. samplersList.push("projectionLightSampler" + lightIndex);
  42819. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42820. }
  42821. }
  42822. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42823. uniformsList.push("morphTargetInfluences");
  42824. }
  42825. };
  42826. /**
  42827. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42828. * @param defines The defines to update while falling back
  42829. * @param fallbacks The authorized effect fallbacks
  42830. * @param maxSimultaneousLights The maximum number of lights allowed
  42831. * @param rank the current rank of the Effect
  42832. * @returns The newly affected rank
  42833. */
  42834. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42835. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42836. if (rank === void 0) { rank = 0; }
  42837. var lightFallbackRank = 0;
  42838. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42839. if (!defines["LIGHT" + lightIndex]) {
  42840. break;
  42841. }
  42842. if (lightIndex > 0) {
  42843. lightFallbackRank = rank + lightIndex;
  42844. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42845. }
  42846. if (!defines["SHADOWS"]) {
  42847. if (defines["SHADOW" + lightIndex]) {
  42848. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42849. }
  42850. if (defines["SHADOWPCF" + lightIndex]) {
  42851. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42852. }
  42853. if (defines["SHADOWPCSS" + lightIndex]) {
  42854. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42855. }
  42856. if (defines["SHADOWPOISSON" + lightIndex]) {
  42857. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42858. }
  42859. if (defines["SHADOWESM" + lightIndex]) {
  42860. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42861. }
  42862. }
  42863. }
  42864. return lightFallbackRank++;
  42865. };
  42866. /**
  42867. * Prepares the list of attributes required for morph targets according to the effect defines.
  42868. * @param attribs The current list of supported attribs
  42869. * @param mesh The mesh to prepare the morph targets attributes for
  42870. * @param defines The current Defines of the effect
  42871. */
  42872. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42873. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42874. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42875. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42876. var manager = mesh.morphTargetManager;
  42877. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42878. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42879. for (var index = 0; index < influencers; index++) {
  42880. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42881. if (normal) {
  42882. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42883. }
  42884. if (tangent) {
  42885. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42886. }
  42887. if (attribs.length > maxAttributesCount) {
  42888. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42889. }
  42890. }
  42891. }
  42892. };
  42893. /**
  42894. * Prepares the list of attributes required for bones according to the effect defines.
  42895. * @param attribs The current list of supported attribs
  42896. * @param mesh The mesh to prepare the bones attributes for
  42897. * @param defines The current Defines of the effect
  42898. * @param fallbacks The current efffect fallback strategy
  42899. */
  42900. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42901. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42902. fallbacks.addCPUSkinningFallback(0, mesh);
  42903. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42904. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42905. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42906. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42907. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42908. }
  42909. }
  42910. };
  42911. /**
  42912. * Prepares the list of attributes required for instances according to the effect defines.
  42913. * @param attribs The current list of supported attribs
  42914. * @param defines The current Defines of the effect
  42915. */
  42916. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42917. if (defines["INSTANCES"]) {
  42918. attribs.push("world0");
  42919. attribs.push("world1");
  42920. attribs.push("world2");
  42921. attribs.push("world3");
  42922. }
  42923. };
  42924. /**
  42925. * Binds the light shadow information to the effect for the given mesh.
  42926. * @param light The light containing the generator
  42927. * @param scene The scene the lights belongs to
  42928. * @param mesh The mesh we are binding the information to render
  42929. * @param lightIndex The light index in the effect used to render the mesh
  42930. * @param effect The effect we are binding the data to
  42931. */
  42932. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42933. if (light.shadowEnabled && mesh.receiveShadows) {
  42934. var shadowGenerator = light.getShadowGenerator();
  42935. if (shadowGenerator) {
  42936. shadowGenerator.bindShadowLight(lightIndex, effect);
  42937. }
  42938. }
  42939. };
  42940. /**
  42941. * Binds the light information to the effect.
  42942. * @param light The light containing the generator
  42943. * @param effect The effect we are binding the data to
  42944. * @param lightIndex The light index in the effect used to render
  42945. */
  42946. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42947. light.transferToEffect(effect, lightIndex + "");
  42948. };
  42949. /**
  42950. * Binds the lights information from the scene to the effect for the given mesh.
  42951. * @param scene The scene the lights belongs to
  42952. * @param mesh The mesh we are binding the information to render
  42953. * @param effect The effect we are binding the data to
  42954. * @param defines The generated defines for the effect
  42955. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42956. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42957. */
  42958. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42959. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42960. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42961. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42962. for (var i = 0; i < len; i++) {
  42963. var light = mesh._lightSources[i];
  42964. var iAsString = i.toString();
  42965. var scaledIntensity = light.getScaledIntensity();
  42966. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42967. MaterialHelper.BindLightProperties(light, effect, i);
  42968. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42969. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42970. if (defines["SPECULARTERM"]) {
  42971. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42972. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42973. }
  42974. // Shadows
  42975. if (scene.shadowsEnabled) {
  42976. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42977. }
  42978. light._uniformBuffer.update();
  42979. }
  42980. };
  42981. /**
  42982. * Binds the fog information from the scene to the effect for the given mesh.
  42983. * @param scene The scene the lights belongs to
  42984. * @param mesh The mesh we are binding the information to render
  42985. * @param effect The effect we are binding the data to
  42986. */
  42987. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42988. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42989. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42990. effect.setColor3("vFogColor", scene.fogColor);
  42991. }
  42992. };
  42993. /**
  42994. * Binds the bones information from the mesh to the effect.
  42995. * @param mesh The mesh we are binding the information to render
  42996. * @param effect The effect we are binding the data to
  42997. */
  42998. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42999. if (!effect || !mesh) {
  43000. return;
  43001. }
  43002. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  43003. mesh.computeBonesUsingShaders = false;
  43004. }
  43005. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  43006. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  43007. if (matrices) {
  43008. effect.setMatrices("mBones", matrices);
  43009. }
  43010. }
  43011. };
  43012. /**
  43013. * Binds the morph targets information from the mesh to the effect.
  43014. * @param abstractMesh The mesh we are binding the information to render
  43015. * @param effect The effect we are binding the data to
  43016. */
  43017. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  43018. var manager = abstractMesh.morphTargetManager;
  43019. if (!abstractMesh || !manager) {
  43020. return;
  43021. }
  43022. effect.setFloatArray("morphTargetInfluences", manager.influences);
  43023. };
  43024. /**
  43025. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  43026. * @param defines The generated defines used in the effect
  43027. * @param effect The effect we are binding the data to
  43028. * @param scene The scene we are willing to render with logarithmic scale for
  43029. */
  43030. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  43031. if (defines["LOGARITHMICDEPTH"]) {
  43032. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  43033. }
  43034. };
  43035. /**
  43036. * Binds the clip plane information from the scene to the effect.
  43037. * @param scene The scene the clip plane information are extracted from
  43038. * @param effect The effect we are binding the data to
  43039. */
  43040. MaterialHelper.BindClipPlane = function (effect, scene) {
  43041. if (scene.clipPlane) {
  43042. var clipPlane = scene.clipPlane;
  43043. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  43044. }
  43045. };
  43046. return MaterialHelper;
  43047. }());
  43048. BABYLON.MaterialHelper = MaterialHelper;
  43049. })(BABYLON || (BABYLON = {}));
  43050. //# sourceMappingURL=babylon.materialHelper.js.map
  43051. var BABYLON;
  43052. (function (BABYLON) {
  43053. var PushMaterial = /** @class */ (function (_super) {
  43054. __extends(PushMaterial, _super);
  43055. function PushMaterial(name, scene) {
  43056. var _this = _super.call(this, name, scene) || this;
  43057. _this._normalMatrix = new BABYLON.Matrix();
  43058. _this.storeEffectOnSubMeshes = true;
  43059. return _this;
  43060. }
  43061. PushMaterial.prototype.getEffect = function () {
  43062. return this._activeEffect;
  43063. };
  43064. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  43065. if (!mesh) {
  43066. return false;
  43067. }
  43068. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  43069. return true;
  43070. }
  43071. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  43072. };
  43073. /**
  43074. * Binds the given world matrix to the active effect
  43075. *
  43076. * @param world the matrix to bind
  43077. */
  43078. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  43079. this._activeEffect.setMatrix("world", world);
  43080. };
  43081. /**
  43082. * Binds the given normal matrix to the active effect
  43083. *
  43084. * @param normalMatrix the matrix to bind
  43085. */
  43086. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  43087. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  43088. };
  43089. PushMaterial.prototype.bind = function (world, mesh) {
  43090. if (!mesh) {
  43091. return;
  43092. }
  43093. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  43094. };
  43095. PushMaterial.prototype._afterBind = function (mesh, effect) {
  43096. if (effect === void 0) { effect = null; }
  43097. _super.prototype._afterBind.call(this, mesh);
  43098. this.getScene()._cachedEffect = effect;
  43099. };
  43100. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  43101. if (visibility === void 0) { visibility = 1; }
  43102. return scene.isCachedMaterialInvalid(this, effect, visibility);
  43103. };
  43104. return PushMaterial;
  43105. }(BABYLON.Material));
  43106. BABYLON.PushMaterial = PushMaterial;
  43107. })(BABYLON || (BABYLON = {}));
  43108. //# sourceMappingURL=babylon.pushMaterial.js.map
  43109. var BABYLON;
  43110. (function (BABYLON) {
  43111. /** @hidden */
  43112. var StandardMaterialDefines = /** @class */ (function (_super) {
  43113. __extends(StandardMaterialDefines, _super);
  43114. function StandardMaterialDefines() {
  43115. var _this = _super.call(this) || this;
  43116. _this.MAINUV1 = false;
  43117. _this.MAINUV2 = false;
  43118. _this.DIFFUSE = false;
  43119. _this.DIFFUSEDIRECTUV = 0;
  43120. _this.AMBIENT = false;
  43121. _this.AMBIENTDIRECTUV = 0;
  43122. _this.OPACITY = false;
  43123. _this.OPACITYDIRECTUV = 0;
  43124. _this.OPACITYRGB = false;
  43125. _this.REFLECTION = false;
  43126. _this.EMISSIVE = false;
  43127. _this.EMISSIVEDIRECTUV = 0;
  43128. _this.SPECULAR = false;
  43129. _this.SPECULARDIRECTUV = 0;
  43130. _this.BUMP = false;
  43131. _this.BUMPDIRECTUV = 0;
  43132. _this.PARALLAX = false;
  43133. _this.PARALLAXOCCLUSION = false;
  43134. _this.SPECULAROVERALPHA = false;
  43135. _this.CLIPPLANE = false;
  43136. _this.ALPHATEST = false;
  43137. _this.DEPTHPREPASS = false;
  43138. _this.ALPHAFROMDIFFUSE = false;
  43139. _this.POINTSIZE = false;
  43140. _this.FOG = false;
  43141. _this.SPECULARTERM = false;
  43142. _this.DIFFUSEFRESNEL = false;
  43143. _this.OPACITYFRESNEL = false;
  43144. _this.REFLECTIONFRESNEL = false;
  43145. _this.REFRACTIONFRESNEL = false;
  43146. _this.EMISSIVEFRESNEL = false;
  43147. _this.FRESNEL = false;
  43148. _this.NORMAL = false;
  43149. _this.UV1 = false;
  43150. _this.UV2 = false;
  43151. _this.VERTEXCOLOR = false;
  43152. _this.VERTEXALPHA = false;
  43153. _this.NUM_BONE_INFLUENCERS = 0;
  43154. _this.BonesPerMesh = 0;
  43155. _this.INSTANCES = false;
  43156. _this.GLOSSINESS = false;
  43157. _this.ROUGHNESS = false;
  43158. _this.EMISSIVEASILLUMINATION = false;
  43159. _this.LINKEMISSIVEWITHDIFFUSE = false;
  43160. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  43161. _this.LIGHTMAP = false;
  43162. _this.LIGHTMAPDIRECTUV = 0;
  43163. _this.OBJECTSPACE_NORMALMAP = false;
  43164. _this.USELIGHTMAPASSHADOWMAP = false;
  43165. _this.REFLECTIONMAP_3D = false;
  43166. _this.REFLECTIONMAP_SPHERICAL = false;
  43167. _this.REFLECTIONMAP_PLANAR = false;
  43168. _this.REFLECTIONMAP_CUBIC = false;
  43169. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43170. _this.REFLECTIONMAP_PROJECTION = false;
  43171. _this.REFLECTIONMAP_SKYBOX = false;
  43172. _this.REFLECTIONMAP_EXPLICIT = false;
  43173. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43174. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43175. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43176. _this.INVERTCUBICMAP = false;
  43177. _this.LOGARITHMICDEPTH = false;
  43178. _this.REFRACTION = false;
  43179. _this.REFRACTIONMAP_3D = false;
  43180. _this.REFLECTIONOVERALPHA = false;
  43181. _this.TWOSIDEDLIGHTING = false;
  43182. _this.SHADOWFLOAT = false;
  43183. _this.MORPHTARGETS = false;
  43184. _this.MORPHTARGETS_NORMAL = false;
  43185. _this.MORPHTARGETS_TANGENT = false;
  43186. _this.NUM_MORPH_INFLUENCERS = 0;
  43187. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  43188. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  43189. _this.IMAGEPROCESSING = false;
  43190. _this.VIGNETTE = false;
  43191. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43192. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43193. _this.TONEMAPPING = false;
  43194. _this.CONTRAST = false;
  43195. _this.COLORCURVES = false;
  43196. _this.COLORGRADING = false;
  43197. _this.COLORGRADING3D = false;
  43198. _this.SAMPLER3DGREENDEPTH = false;
  43199. _this.SAMPLER3DBGRMAP = false;
  43200. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43201. /**
  43202. * If the reflection texture on this material is in linear color space
  43203. * @hidden
  43204. */
  43205. _this.IS_REFLECTION_LINEAR = false;
  43206. /**
  43207. * If the refraction texture on this material is in linear color space
  43208. * @hidden
  43209. */
  43210. _this.IS_REFRACTION_LINEAR = false;
  43211. _this.EXPOSURE = false;
  43212. _this.rebuild();
  43213. return _this;
  43214. }
  43215. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  43216. var modes = [
  43217. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  43218. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  43219. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  43220. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  43221. ];
  43222. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  43223. var mode = modes_1[_i];
  43224. this[mode] = (mode === modeToEnable);
  43225. }
  43226. };
  43227. return StandardMaterialDefines;
  43228. }(BABYLON.MaterialDefines));
  43229. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43230. var StandardMaterial = /** @class */ (function (_super) {
  43231. __extends(StandardMaterial, _super);
  43232. function StandardMaterial(name, scene) {
  43233. var _this = _super.call(this, name, scene) || this;
  43234. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43235. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43236. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43237. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43238. _this.specularPower = 64;
  43239. _this._useAlphaFromDiffuseTexture = false;
  43240. _this._useEmissiveAsIllumination = false;
  43241. _this._linkEmissiveWithDiffuse = false;
  43242. _this._useSpecularOverAlpha = false;
  43243. _this._useReflectionOverAlpha = false;
  43244. _this._disableLighting = false;
  43245. _this._useObjectSpaceNormalMap = false;
  43246. _this._useParallax = false;
  43247. _this._useParallaxOcclusion = false;
  43248. _this.parallaxScaleBias = 0.05;
  43249. _this._roughness = 0;
  43250. _this.indexOfRefraction = 0.98;
  43251. _this.invertRefractionY = true;
  43252. /**
  43253. * Defines the alpha limits in alpha test mode
  43254. */
  43255. _this.alphaCutOff = 0.4;
  43256. _this._useLightmapAsShadowmap = false;
  43257. _this._useReflectionFresnelFromSpecular = false;
  43258. _this._useGlossinessFromSpecularMapAlpha = false;
  43259. _this._maxSimultaneousLights = 4;
  43260. /**
  43261. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43262. */
  43263. _this._invertNormalMapX = false;
  43264. /**
  43265. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43266. */
  43267. _this._invertNormalMapY = false;
  43268. /**
  43269. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43270. */
  43271. _this._twoSidedLighting = false;
  43272. _this._renderTargets = new BABYLON.SmartArray(16);
  43273. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43274. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43275. // Setup the default processing configuration to the scene.
  43276. _this._attachImageProcessingConfiguration(null);
  43277. _this.getRenderTargetTextures = function () {
  43278. _this._renderTargets.reset();
  43279. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43280. _this._renderTargets.push(_this._reflectionTexture);
  43281. }
  43282. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43283. _this._renderTargets.push(_this._refractionTexture);
  43284. }
  43285. return _this._renderTargets;
  43286. };
  43287. return _this;
  43288. }
  43289. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43290. /**
  43291. * Gets the image processing configuration used either in this material.
  43292. */
  43293. get: function () {
  43294. return this._imageProcessingConfiguration;
  43295. },
  43296. /**
  43297. * Sets the Default image processing configuration used either in the this material.
  43298. *
  43299. * If sets to null, the scene one is in use.
  43300. */
  43301. set: function (value) {
  43302. this._attachImageProcessingConfiguration(value);
  43303. // Ensure the effect will be rebuilt.
  43304. this._markAllSubMeshesAsTexturesDirty();
  43305. },
  43306. enumerable: true,
  43307. configurable: true
  43308. });
  43309. /**
  43310. * Attaches a new image processing configuration to the Standard Material.
  43311. * @param configuration
  43312. */
  43313. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43314. var _this = this;
  43315. if (configuration === this._imageProcessingConfiguration) {
  43316. return;
  43317. }
  43318. // Detaches observer.
  43319. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43320. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43321. }
  43322. // Pick the scene configuration if needed.
  43323. if (!configuration) {
  43324. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43325. }
  43326. else {
  43327. this._imageProcessingConfiguration = configuration;
  43328. }
  43329. // Attaches observer.
  43330. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43331. _this._markAllSubMeshesAsImageProcessingDirty();
  43332. });
  43333. };
  43334. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43335. /**
  43336. * Gets wether the color curves effect is enabled.
  43337. */
  43338. get: function () {
  43339. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43340. },
  43341. /**
  43342. * Sets wether the color curves effect is enabled.
  43343. */
  43344. set: function (value) {
  43345. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43346. },
  43347. enumerable: true,
  43348. configurable: true
  43349. });
  43350. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43351. /**
  43352. * Gets wether the color grading effect is enabled.
  43353. */
  43354. get: function () {
  43355. return this.imageProcessingConfiguration.colorGradingEnabled;
  43356. },
  43357. /**
  43358. * Gets wether the color grading effect is enabled.
  43359. */
  43360. set: function (value) {
  43361. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43362. },
  43363. enumerable: true,
  43364. configurable: true
  43365. });
  43366. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43367. /**
  43368. * Gets wether tonemapping is enabled or not.
  43369. */
  43370. get: function () {
  43371. return this._imageProcessingConfiguration.toneMappingEnabled;
  43372. },
  43373. /**
  43374. * Sets wether tonemapping is enabled or not
  43375. */
  43376. set: function (value) {
  43377. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43378. },
  43379. enumerable: true,
  43380. configurable: true
  43381. });
  43382. ;
  43383. ;
  43384. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43385. /**
  43386. * The camera exposure used on this material.
  43387. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43388. * This corresponds to a photographic exposure.
  43389. */
  43390. get: function () {
  43391. return this._imageProcessingConfiguration.exposure;
  43392. },
  43393. /**
  43394. * The camera exposure used on this material.
  43395. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43396. * This corresponds to a photographic exposure.
  43397. */
  43398. set: function (value) {
  43399. this._imageProcessingConfiguration.exposure = value;
  43400. },
  43401. enumerable: true,
  43402. configurable: true
  43403. });
  43404. ;
  43405. ;
  43406. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43407. /**
  43408. * Gets The camera contrast used on this material.
  43409. */
  43410. get: function () {
  43411. return this._imageProcessingConfiguration.contrast;
  43412. },
  43413. /**
  43414. * Sets The camera contrast used on this material.
  43415. */
  43416. set: function (value) {
  43417. this._imageProcessingConfiguration.contrast = value;
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43423. /**
  43424. * Gets the Color Grading 2D Lookup Texture.
  43425. */
  43426. get: function () {
  43427. return this._imageProcessingConfiguration.colorGradingTexture;
  43428. },
  43429. /**
  43430. * Sets the Color Grading 2D Lookup Texture.
  43431. */
  43432. set: function (value) {
  43433. this._imageProcessingConfiguration.colorGradingTexture = value;
  43434. },
  43435. enumerable: true,
  43436. configurable: true
  43437. });
  43438. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43439. /**
  43440. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43441. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43442. * 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;
  43443. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43444. */
  43445. get: function () {
  43446. return this._imageProcessingConfiguration.colorCurves;
  43447. },
  43448. /**
  43449. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43450. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43451. * 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;
  43452. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43453. */
  43454. set: function (value) {
  43455. this._imageProcessingConfiguration.colorCurves = value;
  43456. },
  43457. enumerable: true,
  43458. configurable: true
  43459. });
  43460. StandardMaterial.prototype.getClassName = function () {
  43461. return "StandardMaterial";
  43462. };
  43463. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43464. get: function () {
  43465. return this._useLogarithmicDepth;
  43466. },
  43467. set: function (value) {
  43468. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43469. this._markAllSubMeshesAsMiscDirty();
  43470. },
  43471. enumerable: true,
  43472. configurable: true
  43473. });
  43474. StandardMaterial.prototype.needAlphaBlending = function () {
  43475. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43476. };
  43477. StandardMaterial.prototype.needAlphaTesting = function () {
  43478. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43479. };
  43480. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43481. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43482. };
  43483. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43484. return this._diffuseTexture;
  43485. };
  43486. /**
  43487. * Child classes can use it to update shaders
  43488. */
  43489. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43490. if (useInstances === void 0) { useInstances = false; }
  43491. if (subMesh.effect && this.isFrozen) {
  43492. if (this._wasPreviouslyReady && subMesh.effect) {
  43493. return true;
  43494. }
  43495. }
  43496. if (!subMesh._materialDefines) {
  43497. subMesh._materialDefines = new StandardMaterialDefines();
  43498. }
  43499. var scene = this.getScene();
  43500. var defines = subMesh._materialDefines;
  43501. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43502. if (defines._renderId === scene.getRenderId()) {
  43503. return true;
  43504. }
  43505. }
  43506. var engine = scene.getEngine();
  43507. // Lights
  43508. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43509. // Textures
  43510. if (defines._areTexturesDirty) {
  43511. defines._needUVs = false;
  43512. defines.MAINUV1 = false;
  43513. defines.MAINUV2 = false;
  43514. if (scene.texturesEnabled) {
  43515. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43516. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43517. return false;
  43518. }
  43519. else {
  43520. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43521. }
  43522. }
  43523. else {
  43524. defines.DIFFUSE = false;
  43525. }
  43526. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43527. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43528. return false;
  43529. }
  43530. else {
  43531. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43532. }
  43533. }
  43534. else {
  43535. defines.AMBIENT = false;
  43536. }
  43537. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43538. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43539. return false;
  43540. }
  43541. else {
  43542. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43543. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43544. }
  43545. }
  43546. else {
  43547. defines.OPACITY = false;
  43548. }
  43549. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43550. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43551. return false;
  43552. }
  43553. else {
  43554. defines._needNormals = true;
  43555. defines.REFLECTION = true;
  43556. defines.ROUGHNESS = (this._roughness > 0);
  43557. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43558. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43559. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43560. switch (this._reflectionTexture.coordinatesMode) {
  43561. case BABYLON.Texture.EXPLICIT_MODE:
  43562. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43563. break;
  43564. case BABYLON.Texture.PLANAR_MODE:
  43565. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43566. break;
  43567. case BABYLON.Texture.PROJECTION_MODE:
  43568. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43569. break;
  43570. case BABYLON.Texture.SKYBOX_MODE:
  43571. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43572. break;
  43573. case BABYLON.Texture.SPHERICAL_MODE:
  43574. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43575. break;
  43576. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43577. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43578. break;
  43579. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43580. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43581. break;
  43582. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43583. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43584. break;
  43585. case BABYLON.Texture.CUBIC_MODE:
  43586. case BABYLON.Texture.INVCUBIC_MODE:
  43587. default:
  43588. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43589. break;
  43590. }
  43591. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43592. }
  43593. }
  43594. else {
  43595. defines.REFLECTION = false;
  43596. }
  43597. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43598. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43599. return false;
  43600. }
  43601. else {
  43602. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43603. }
  43604. }
  43605. else {
  43606. defines.EMISSIVE = false;
  43607. }
  43608. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43609. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43610. return false;
  43611. }
  43612. else {
  43613. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43614. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43615. }
  43616. }
  43617. else {
  43618. defines.LIGHTMAP = false;
  43619. }
  43620. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43621. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43622. return false;
  43623. }
  43624. else {
  43625. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43626. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43627. }
  43628. }
  43629. else {
  43630. defines.SPECULAR = false;
  43631. }
  43632. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43633. // Bump texure can not be not blocking.
  43634. if (!this._bumpTexture.isReady()) {
  43635. return false;
  43636. }
  43637. else {
  43638. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43639. defines.PARALLAX = this._useParallax;
  43640. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43641. }
  43642. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43643. }
  43644. else {
  43645. defines.BUMP = false;
  43646. }
  43647. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43648. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43649. return false;
  43650. }
  43651. else {
  43652. defines._needUVs = true;
  43653. defines.REFRACTION = true;
  43654. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43655. }
  43656. }
  43657. else {
  43658. defines.REFRACTION = false;
  43659. }
  43660. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43661. }
  43662. else {
  43663. defines.DIFFUSE = false;
  43664. defines.AMBIENT = false;
  43665. defines.OPACITY = false;
  43666. defines.REFLECTION = false;
  43667. defines.EMISSIVE = false;
  43668. defines.LIGHTMAP = false;
  43669. defines.BUMP = false;
  43670. defines.REFRACTION = false;
  43671. }
  43672. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43673. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43674. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43675. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43676. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43677. }
  43678. if (defines._areImageProcessingDirty) {
  43679. if (!this._imageProcessingConfiguration.isReady()) {
  43680. return false;
  43681. }
  43682. this._imageProcessingConfiguration.prepareDefines(defines);
  43683. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43684. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43685. }
  43686. if (defines._areFresnelDirty) {
  43687. if (StandardMaterial.FresnelEnabled) {
  43688. // Fresnel
  43689. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43690. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43691. this._reflectionFresnelParameters) {
  43692. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43693. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43694. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43695. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43696. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43697. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43698. defines._needNormals = true;
  43699. defines.FRESNEL = true;
  43700. }
  43701. }
  43702. else {
  43703. defines.FRESNEL = false;
  43704. }
  43705. }
  43706. // Misc.
  43707. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43708. // Attribs
  43709. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43710. // Values that need to be evaluated on every frame
  43711. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43712. // Get correct effect
  43713. if (defines.isDirty) {
  43714. defines.markAsProcessed();
  43715. scene.resetCachedMaterial();
  43716. // Fallbacks
  43717. var fallbacks = new BABYLON.EffectFallbacks();
  43718. if (defines.REFLECTION) {
  43719. fallbacks.addFallback(0, "REFLECTION");
  43720. }
  43721. if (defines.SPECULAR) {
  43722. fallbacks.addFallback(0, "SPECULAR");
  43723. }
  43724. if (defines.BUMP) {
  43725. fallbacks.addFallback(0, "BUMP");
  43726. }
  43727. if (defines.PARALLAX) {
  43728. fallbacks.addFallback(1, "PARALLAX");
  43729. }
  43730. if (defines.PARALLAXOCCLUSION) {
  43731. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43732. }
  43733. if (defines.SPECULAROVERALPHA) {
  43734. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43735. }
  43736. if (defines.FOG) {
  43737. fallbacks.addFallback(1, "FOG");
  43738. }
  43739. if (defines.POINTSIZE) {
  43740. fallbacks.addFallback(0, "POINTSIZE");
  43741. }
  43742. if (defines.LOGARITHMICDEPTH) {
  43743. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43744. }
  43745. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43746. if (defines.SPECULARTERM) {
  43747. fallbacks.addFallback(0, "SPECULARTERM");
  43748. }
  43749. if (defines.DIFFUSEFRESNEL) {
  43750. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43751. }
  43752. if (defines.OPACITYFRESNEL) {
  43753. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43754. }
  43755. if (defines.REFLECTIONFRESNEL) {
  43756. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43757. }
  43758. if (defines.EMISSIVEFRESNEL) {
  43759. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43760. }
  43761. if (defines.FRESNEL) {
  43762. fallbacks.addFallback(4, "FRESNEL");
  43763. }
  43764. //Attributes
  43765. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43766. if (defines.NORMAL) {
  43767. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43768. }
  43769. if (defines.UV1) {
  43770. attribs.push(BABYLON.VertexBuffer.UVKind);
  43771. }
  43772. if (defines.UV2) {
  43773. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43774. }
  43775. if (defines.VERTEXCOLOR) {
  43776. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43777. }
  43778. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43779. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43780. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43781. var shaderName = "default";
  43782. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43783. "vFogInfos", "vFogColor", "pointSize",
  43784. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43785. "mBones",
  43786. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43787. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43788. "vReflectionPosition", "vReflectionSize",
  43789. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43790. ];
  43791. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43792. var uniformBuffers = ["Material", "Scene"];
  43793. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43794. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43795. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43796. uniformsNames: uniforms,
  43797. uniformBuffersNames: uniformBuffers,
  43798. samplers: samplers,
  43799. defines: defines,
  43800. maxSimultaneousLights: this._maxSimultaneousLights
  43801. });
  43802. if (this.customShaderNameResolve) {
  43803. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43804. }
  43805. var join = defines.toString();
  43806. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43807. attributes: attribs,
  43808. uniformsNames: uniforms,
  43809. uniformBuffersNames: uniformBuffers,
  43810. samplers: samplers,
  43811. defines: join,
  43812. fallbacks: fallbacks,
  43813. onCompiled: this.onCompiled,
  43814. onError: this.onError,
  43815. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43816. }, engine), defines);
  43817. this.buildUniformLayout();
  43818. }
  43819. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43820. return false;
  43821. }
  43822. defines._renderId = scene.getRenderId();
  43823. this._wasPreviouslyReady = true;
  43824. return true;
  43825. };
  43826. StandardMaterial.prototype.buildUniformLayout = function () {
  43827. // Order is important !
  43828. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43829. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43830. this._uniformBuffer.addUniform("opacityParts", 4);
  43831. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43832. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43833. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43834. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43835. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43836. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43837. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43838. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43839. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43840. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43841. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43842. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43843. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43844. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43845. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43846. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43847. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43848. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43849. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43850. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43851. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43852. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43853. this._uniformBuffer.addUniform("specularMatrix", 16);
  43854. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43855. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43856. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43857. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43858. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43859. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43860. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43861. this._uniformBuffer.addUniform("pointSize", 1);
  43862. this._uniformBuffer.create();
  43863. };
  43864. StandardMaterial.prototype.unbind = function () {
  43865. if (this._activeEffect) {
  43866. var needFlag = false;
  43867. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43868. this._activeEffect.setTexture("reflection2DSampler", null);
  43869. needFlag = true;
  43870. }
  43871. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43872. this._activeEffect.setTexture("refraction2DSampler", null);
  43873. needFlag = true;
  43874. }
  43875. if (needFlag) {
  43876. this._markAllSubMeshesAsTexturesDirty();
  43877. }
  43878. }
  43879. _super.prototype.unbind.call(this);
  43880. };
  43881. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43882. var scene = this.getScene();
  43883. var defines = subMesh._materialDefines;
  43884. if (!defines) {
  43885. return;
  43886. }
  43887. var effect = subMesh.effect;
  43888. if (!effect) {
  43889. return;
  43890. }
  43891. this._activeEffect = effect;
  43892. // Matrices
  43893. this.bindOnlyWorldMatrix(world);
  43894. // Normal Matrix
  43895. if (defines.OBJECTSPACE_NORMALMAP) {
  43896. world.toNormalMatrix(this._normalMatrix);
  43897. this.bindOnlyNormalMatrix(this._normalMatrix);
  43898. }
  43899. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43900. // Bones
  43901. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43902. if (mustRebind) {
  43903. this._uniformBuffer.bindToEffect(effect, "Material");
  43904. this.bindViewProjection(effect);
  43905. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43906. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43907. // Fresnel
  43908. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43909. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43910. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43911. }
  43912. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43913. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43914. }
  43915. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43916. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43917. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43918. }
  43919. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43920. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43921. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43922. }
  43923. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43924. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43925. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43926. }
  43927. }
  43928. // Textures
  43929. if (scene.texturesEnabled) {
  43930. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43931. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43932. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43933. if (this._diffuseTexture.hasAlpha) {
  43934. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43935. }
  43936. }
  43937. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43938. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43939. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43940. }
  43941. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43942. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43943. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43944. }
  43945. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43946. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43947. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43948. if (this._reflectionTexture.boundingBoxSize) {
  43949. var cubeTexture = this._reflectionTexture;
  43950. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43951. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43952. }
  43953. }
  43954. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43955. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43956. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43957. }
  43958. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43959. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43960. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43961. }
  43962. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43963. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43964. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43965. }
  43966. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43967. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43968. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43969. if (scene._mirroredCameraPosition) {
  43970. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43971. }
  43972. else {
  43973. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43974. }
  43975. }
  43976. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43977. var depth = 1.0;
  43978. if (!this._refractionTexture.isCube) {
  43979. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43980. if (this._refractionTexture.depth) {
  43981. depth = this._refractionTexture.depth;
  43982. }
  43983. }
  43984. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43985. }
  43986. }
  43987. // Point size
  43988. if (this.pointsCloud) {
  43989. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43990. }
  43991. if (defines.SPECULARTERM) {
  43992. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43993. }
  43994. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43995. // Diffuse
  43996. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43997. }
  43998. // Textures
  43999. if (scene.texturesEnabled) {
  44000. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  44001. effect.setTexture("diffuseSampler", this._diffuseTexture);
  44002. }
  44003. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  44004. effect.setTexture("ambientSampler", this._ambientTexture);
  44005. }
  44006. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  44007. effect.setTexture("opacitySampler", this._opacityTexture);
  44008. }
  44009. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  44010. if (this._reflectionTexture.isCube) {
  44011. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  44012. }
  44013. else {
  44014. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  44015. }
  44016. }
  44017. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  44018. effect.setTexture("emissiveSampler", this._emissiveTexture);
  44019. }
  44020. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  44021. effect.setTexture("lightmapSampler", this._lightmapTexture);
  44022. }
  44023. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  44024. effect.setTexture("specularSampler", this._specularTexture);
  44025. }
  44026. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  44027. effect.setTexture("bumpSampler", this._bumpTexture);
  44028. }
  44029. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  44030. var depth = 1.0;
  44031. if (this._refractionTexture.isCube) {
  44032. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  44033. }
  44034. else {
  44035. effect.setTexture("refraction2DSampler", this._refractionTexture);
  44036. }
  44037. }
  44038. }
  44039. // Clip plane
  44040. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  44041. // Colors
  44042. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44043. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  44044. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44045. }
  44046. if (mustRebind || !this.isFrozen) {
  44047. // Lights
  44048. if (scene.lightsEnabled && !this._disableLighting) {
  44049. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  44050. }
  44051. // View
  44052. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  44053. this.bindView(effect);
  44054. }
  44055. // Fog
  44056. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  44057. // Morph targets
  44058. if (defines.NUM_MORPH_INFLUENCERS) {
  44059. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  44060. }
  44061. // Log. depth
  44062. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  44063. // image processing
  44064. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  44065. this._imageProcessingConfiguration.bind(this._activeEffect);
  44066. }
  44067. }
  44068. this._uniformBuffer.update();
  44069. this._afterBind(mesh, this._activeEffect);
  44070. };
  44071. StandardMaterial.prototype.getAnimatables = function () {
  44072. var results = [];
  44073. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  44074. results.push(this._diffuseTexture);
  44075. }
  44076. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44077. results.push(this._ambientTexture);
  44078. }
  44079. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44080. results.push(this._opacityTexture);
  44081. }
  44082. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44083. results.push(this._reflectionTexture);
  44084. }
  44085. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44086. results.push(this._emissiveTexture);
  44087. }
  44088. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  44089. results.push(this._specularTexture);
  44090. }
  44091. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44092. results.push(this._bumpTexture);
  44093. }
  44094. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44095. results.push(this._lightmapTexture);
  44096. }
  44097. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44098. results.push(this._refractionTexture);
  44099. }
  44100. return results;
  44101. };
  44102. StandardMaterial.prototype.getActiveTextures = function () {
  44103. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44104. if (this._diffuseTexture) {
  44105. activeTextures.push(this._diffuseTexture);
  44106. }
  44107. if (this._ambientTexture) {
  44108. activeTextures.push(this._ambientTexture);
  44109. }
  44110. if (this._opacityTexture) {
  44111. activeTextures.push(this._opacityTexture);
  44112. }
  44113. if (this._reflectionTexture) {
  44114. activeTextures.push(this._reflectionTexture);
  44115. }
  44116. if (this._emissiveTexture) {
  44117. activeTextures.push(this._emissiveTexture);
  44118. }
  44119. if (this._specularTexture) {
  44120. activeTextures.push(this._specularTexture);
  44121. }
  44122. if (this._bumpTexture) {
  44123. activeTextures.push(this._bumpTexture);
  44124. }
  44125. if (this._lightmapTexture) {
  44126. activeTextures.push(this._lightmapTexture);
  44127. }
  44128. if (this._refractionTexture) {
  44129. activeTextures.push(this._refractionTexture);
  44130. }
  44131. return activeTextures;
  44132. };
  44133. StandardMaterial.prototype.hasTexture = function (texture) {
  44134. if (_super.prototype.hasTexture.call(this, texture)) {
  44135. return true;
  44136. }
  44137. if (this._diffuseTexture === texture) {
  44138. return true;
  44139. }
  44140. if (this._ambientTexture === texture) {
  44141. return true;
  44142. }
  44143. if (this._opacityTexture === texture) {
  44144. return true;
  44145. }
  44146. if (this._reflectionTexture === texture) {
  44147. return true;
  44148. }
  44149. if (this._emissiveTexture === texture) {
  44150. return true;
  44151. }
  44152. if (this._specularTexture === texture) {
  44153. return true;
  44154. }
  44155. if (this._bumpTexture === texture) {
  44156. return true;
  44157. }
  44158. if (this._lightmapTexture === texture) {
  44159. return true;
  44160. }
  44161. if (this._refractionTexture === texture) {
  44162. return true;
  44163. }
  44164. return false;
  44165. };
  44166. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44167. if (forceDisposeTextures) {
  44168. if (this._diffuseTexture) {
  44169. this._diffuseTexture.dispose();
  44170. }
  44171. if (this._ambientTexture) {
  44172. this._ambientTexture.dispose();
  44173. }
  44174. if (this._opacityTexture) {
  44175. this._opacityTexture.dispose();
  44176. }
  44177. if (this._reflectionTexture) {
  44178. this._reflectionTexture.dispose();
  44179. }
  44180. if (this._emissiveTexture) {
  44181. this._emissiveTexture.dispose();
  44182. }
  44183. if (this._specularTexture) {
  44184. this._specularTexture.dispose();
  44185. }
  44186. if (this._bumpTexture) {
  44187. this._bumpTexture.dispose();
  44188. }
  44189. if (this._lightmapTexture) {
  44190. this._lightmapTexture.dispose();
  44191. }
  44192. if (this._refractionTexture) {
  44193. this._refractionTexture.dispose();
  44194. }
  44195. }
  44196. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44197. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44198. }
  44199. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44200. };
  44201. StandardMaterial.prototype.clone = function (name) {
  44202. var _this = this;
  44203. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44204. result.name = name;
  44205. result.id = name;
  44206. return result;
  44207. };
  44208. StandardMaterial.prototype.serialize = function () {
  44209. return BABYLON.SerializationHelper.Serialize(this);
  44210. };
  44211. // Statics
  44212. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44213. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44214. };
  44215. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44216. get: function () {
  44217. return StandardMaterial._DiffuseTextureEnabled;
  44218. },
  44219. set: function (value) {
  44220. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44221. return;
  44222. }
  44223. StandardMaterial._DiffuseTextureEnabled = value;
  44224. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44225. },
  44226. enumerable: true,
  44227. configurable: true
  44228. });
  44229. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44230. get: function () {
  44231. return StandardMaterial._AmbientTextureEnabled;
  44232. },
  44233. set: function (value) {
  44234. if (StandardMaterial._AmbientTextureEnabled === value) {
  44235. return;
  44236. }
  44237. StandardMaterial._AmbientTextureEnabled = value;
  44238. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44239. },
  44240. enumerable: true,
  44241. configurable: true
  44242. });
  44243. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44244. get: function () {
  44245. return StandardMaterial._OpacityTextureEnabled;
  44246. },
  44247. set: function (value) {
  44248. if (StandardMaterial._OpacityTextureEnabled === value) {
  44249. return;
  44250. }
  44251. StandardMaterial._OpacityTextureEnabled = value;
  44252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44253. },
  44254. enumerable: true,
  44255. configurable: true
  44256. });
  44257. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44258. get: function () {
  44259. return StandardMaterial._ReflectionTextureEnabled;
  44260. },
  44261. set: function (value) {
  44262. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44263. return;
  44264. }
  44265. StandardMaterial._ReflectionTextureEnabled = value;
  44266. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44272. get: function () {
  44273. return StandardMaterial._EmissiveTextureEnabled;
  44274. },
  44275. set: function (value) {
  44276. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44277. return;
  44278. }
  44279. StandardMaterial._EmissiveTextureEnabled = value;
  44280. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44281. },
  44282. enumerable: true,
  44283. configurable: true
  44284. });
  44285. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44286. get: function () {
  44287. return StandardMaterial._SpecularTextureEnabled;
  44288. },
  44289. set: function (value) {
  44290. if (StandardMaterial._SpecularTextureEnabled === value) {
  44291. return;
  44292. }
  44293. StandardMaterial._SpecularTextureEnabled = value;
  44294. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44295. },
  44296. enumerable: true,
  44297. configurable: true
  44298. });
  44299. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44300. get: function () {
  44301. return StandardMaterial._BumpTextureEnabled;
  44302. },
  44303. set: function (value) {
  44304. if (StandardMaterial._BumpTextureEnabled === value) {
  44305. return;
  44306. }
  44307. StandardMaterial._BumpTextureEnabled = value;
  44308. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44309. },
  44310. enumerable: true,
  44311. configurable: true
  44312. });
  44313. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44314. get: function () {
  44315. return StandardMaterial._LightmapTextureEnabled;
  44316. },
  44317. set: function (value) {
  44318. if (StandardMaterial._LightmapTextureEnabled === value) {
  44319. return;
  44320. }
  44321. StandardMaterial._LightmapTextureEnabled = value;
  44322. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44323. },
  44324. enumerable: true,
  44325. configurable: true
  44326. });
  44327. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44328. get: function () {
  44329. return StandardMaterial._RefractionTextureEnabled;
  44330. },
  44331. set: function (value) {
  44332. if (StandardMaterial._RefractionTextureEnabled === value) {
  44333. return;
  44334. }
  44335. StandardMaterial._RefractionTextureEnabled = value;
  44336. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44337. },
  44338. enumerable: true,
  44339. configurable: true
  44340. });
  44341. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44342. get: function () {
  44343. return StandardMaterial._ColorGradingTextureEnabled;
  44344. },
  44345. set: function (value) {
  44346. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44347. return;
  44348. }
  44349. StandardMaterial._ColorGradingTextureEnabled = value;
  44350. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44351. },
  44352. enumerable: true,
  44353. configurable: true
  44354. });
  44355. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44356. get: function () {
  44357. return StandardMaterial._FresnelEnabled;
  44358. },
  44359. set: function (value) {
  44360. if (StandardMaterial._FresnelEnabled === value) {
  44361. return;
  44362. }
  44363. StandardMaterial._FresnelEnabled = value;
  44364. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44365. },
  44366. enumerable: true,
  44367. configurable: true
  44368. });
  44369. // Flags used to enable or disable a type of texture for all Standard Materials
  44370. StandardMaterial._DiffuseTextureEnabled = true;
  44371. StandardMaterial._AmbientTextureEnabled = true;
  44372. StandardMaterial._OpacityTextureEnabled = true;
  44373. StandardMaterial._ReflectionTextureEnabled = true;
  44374. StandardMaterial._EmissiveTextureEnabled = true;
  44375. StandardMaterial._SpecularTextureEnabled = true;
  44376. StandardMaterial._BumpTextureEnabled = true;
  44377. StandardMaterial._LightmapTextureEnabled = true;
  44378. StandardMaterial._RefractionTextureEnabled = true;
  44379. StandardMaterial._ColorGradingTextureEnabled = true;
  44380. StandardMaterial._FresnelEnabled = true;
  44381. __decorate([
  44382. BABYLON.serializeAsTexture("diffuseTexture")
  44383. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44384. __decorate([
  44385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44386. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44387. __decorate([
  44388. BABYLON.serializeAsTexture("ambientTexture")
  44389. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44390. __decorate([
  44391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44392. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44393. __decorate([
  44394. BABYLON.serializeAsTexture("opacityTexture")
  44395. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44396. __decorate([
  44397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44398. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44399. __decorate([
  44400. BABYLON.serializeAsTexture("reflectionTexture")
  44401. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44402. __decorate([
  44403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44404. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44405. __decorate([
  44406. BABYLON.serializeAsTexture("emissiveTexture")
  44407. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44408. __decorate([
  44409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44410. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44411. __decorate([
  44412. BABYLON.serializeAsTexture("specularTexture")
  44413. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44414. __decorate([
  44415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44416. ], StandardMaterial.prototype, "specularTexture", void 0);
  44417. __decorate([
  44418. BABYLON.serializeAsTexture("bumpTexture")
  44419. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44420. __decorate([
  44421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44422. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44423. __decorate([
  44424. BABYLON.serializeAsTexture("lightmapTexture")
  44425. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44426. __decorate([
  44427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44428. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44429. __decorate([
  44430. BABYLON.serializeAsTexture("refractionTexture")
  44431. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44432. __decorate([
  44433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44434. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44435. __decorate([
  44436. BABYLON.serializeAsColor3("ambient")
  44437. ], StandardMaterial.prototype, "ambientColor", void 0);
  44438. __decorate([
  44439. BABYLON.serializeAsColor3("diffuse")
  44440. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44441. __decorate([
  44442. BABYLON.serializeAsColor3("specular")
  44443. ], StandardMaterial.prototype, "specularColor", void 0);
  44444. __decorate([
  44445. BABYLON.serializeAsColor3("emissive")
  44446. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44447. __decorate([
  44448. BABYLON.serialize()
  44449. ], StandardMaterial.prototype, "specularPower", void 0);
  44450. __decorate([
  44451. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44452. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44453. __decorate([
  44454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44455. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44456. __decorate([
  44457. BABYLON.serialize("useEmissiveAsIllumination")
  44458. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44459. __decorate([
  44460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44461. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44462. __decorate([
  44463. BABYLON.serialize("linkEmissiveWithDiffuse")
  44464. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44465. __decorate([
  44466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44467. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44468. __decorate([
  44469. BABYLON.serialize("useSpecularOverAlpha")
  44470. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44471. __decorate([
  44472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44473. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44474. __decorate([
  44475. BABYLON.serialize("useReflectionOverAlpha")
  44476. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44477. __decorate([
  44478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44479. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44480. __decorate([
  44481. BABYLON.serialize("disableLighting")
  44482. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44483. __decorate([
  44484. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44485. ], StandardMaterial.prototype, "disableLighting", void 0);
  44486. __decorate([
  44487. BABYLON.serialize("useObjectSpaceNormalMap")
  44488. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44489. __decorate([
  44490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44491. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44492. __decorate([
  44493. BABYLON.serialize("useParallax")
  44494. ], StandardMaterial.prototype, "_useParallax", void 0);
  44495. __decorate([
  44496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44497. ], StandardMaterial.prototype, "useParallax", void 0);
  44498. __decorate([
  44499. BABYLON.serialize("useParallaxOcclusion")
  44500. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44501. __decorate([
  44502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44503. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44504. __decorate([
  44505. BABYLON.serialize()
  44506. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44507. __decorate([
  44508. BABYLON.serialize("roughness")
  44509. ], StandardMaterial.prototype, "_roughness", void 0);
  44510. __decorate([
  44511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44512. ], StandardMaterial.prototype, "roughness", void 0);
  44513. __decorate([
  44514. BABYLON.serialize()
  44515. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44516. __decorate([
  44517. BABYLON.serialize()
  44518. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44519. __decorate([
  44520. BABYLON.serialize()
  44521. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44522. __decorate([
  44523. BABYLON.serialize("useLightmapAsShadowmap")
  44524. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44525. __decorate([
  44526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44527. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44528. __decorate([
  44529. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44530. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44531. __decorate([
  44532. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44533. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44534. __decorate([
  44535. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44536. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44537. __decorate([
  44538. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44539. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44540. __decorate([
  44541. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44542. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44543. __decorate([
  44544. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44545. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44546. __decorate([
  44547. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44548. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44549. __decorate([
  44550. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44551. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44552. __decorate([
  44553. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44554. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44555. __decorate([
  44556. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44557. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44558. __decorate([
  44559. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44560. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44561. __decorate([
  44562. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44563. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44564. __decorate([
  44565. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44566. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44567. __decorate([
  44568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44569. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44570. __decorate([
  44571. BABYLON.serialize("maxSimultaneousLights")
  44572. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44573. __decorate([
  44574. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44575. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44576. __decorate([
  44577. BABYLON.serialize("invertNormalMapX")
  44578. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44579. __decorate([
  44580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44581. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44582. __decorate([
  44583. BABYLON.serialize("invertNormalMapY")
  44584. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44585. __decorate([
  44586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44587. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44588. __decorate([
  44589. BABYLON.serialize("twoSidedLighting")
  44590. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44591. __decorate([
  44592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44593. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44594. __decorate([
  44595. BABYLON.serialize()
  44596. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44597. return StandardMaterial;
  44598. }(BABYLON.PushMaterial));
  44599. BABYLON.StandardMaterial = StandardMaterial;
  44600. })(BABYLON || (BABYLON = {}));
  44601. //# sourceMappingURL=babylon.standardMaterial.js.map
  44602. var BABYLON;
  44603. (function (BABYLON) {
  44604. /**
  44605. * Manages the defines for the PBR Material.
  44606. * @hiddenChildren
  44607. */
  44608. var PBRMaterialDefines = /** @class */ (function (_super) {
  44609. __extends(PBRMaterialDefines, _super);
  44610. /**
  44611. * Initializes the PBR Material defines.
  44612. */
  44613. function PBRMaterialDefines() {
  44614. var _this = _super.call(this) || this;
  44615. _this.PBR = true;
  44616. _this.MAINUV1 = false;
  44617. _this.MAINUV2 = false;
  44618. _this.UV1 = false;
  44619. _this.UV2 = false;
  44620. _this.ALBEDO = false;
  44621. _this.ALBEDODIRECTUV = 0;
  44622. _this.VERTEXCOLOR = false;
  44623. _this.AMBIENT = false;
  44624. _this.AMBIENTDIRECTUV = 0;
  44625. _this.AMBIENTINGRAYSCALE = false;
  44626. _this.OPACITY = false;
  44627. _this.VERTEXALPHA = false;
  44628. _this.OPACITYDIRECTUV = 0;
  44629. _this.OPACITYRGB = false;
  44630. _this.ALPHATEST = false;
  44631. _this.DEPTHPREPASS = false;
  44632. _this.ALPHABLEND = false;
  44633. _this.ALPHAFROMALBEDO = false;
  44634. _this.ALPHATESTVALUE = "0.5";
  44635. _this.SPECULAROVERALPHA = false;
  44636. _this.RADIANCEOVERALPHA = false;
  44637. _this.ALPHAFRESNEL = false;
  44638. _this.LINEARALPHAFRESNEL = false;
  44639. _this.PREMULTIPLYALPHA = false;
  44640. _this.EMISSIVE = false;
  44641. _this.EMISSIVEDIRECTUV = 0;
  44642. _this.REFLECTIVITY = false;
  44643. _this.REFLECTIVITYDIRECTUV = 0;
  44644. _this.SPECULARTERM = false;
  44645. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44646. _this.MICROSURFACEAUTOMATIC = false;
  44647. _this.LODBASEDMICROSFURACE = false;
  44648. _this.MICROSURFACEMAP = false;
  44649. _this.MICROSURFACEMAPDIRECTUV = 0;
  44650. _this.METALLICWORKFLOW = false;
  44651. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44652. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44653. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44654. _this.AOSTOREINMETALMAPRED = false;
  44655. _this.ENVIRONMENTBRDF = false;
  44656. _this.NORMAL = false;
  44657. _this.TANGENT = false;
  44658. _this.BUMP = false;
  44659. _this.BUMPDIRECTUV = 0;
  44660. _this.OBJECTSPACE_NORMALMAP = false;
  44661. _this.PARALLAX = false;
  44662. _this.PARALLAXOCCLUSION = false;
  44663. _this.NORMALXYSCALE = true;
  44664. _this.LIGHTMAP = false;
  44665. _this.LIGHTMAPDIRECTUV = 0;
  44666. _this.USELIGHTMAPASSHADOWMAP = false;
  44667. _this.GAMMALIGHTMAP = false;
  44668. _this.REFLECTION = false;
  44669. _this.REFLECTIONMAP_3D = false;
  44670. _this.REFLECTIONMAP_SPHERICAL = false;
  44671. _this.REFLECTIONMAP_PLANAR = false;
  44672. _this.REFLECTIONMAP_CUBIC = false;
  44673. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44674. _this.REFLECTIONMAP_PROJECTION = false;
  44675. _this.REFLECTIONMAP_SKYBOX = false;
  44676. _this.REFLECTIONMAP_EXPLICIT = false;
  44677. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44678. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44679. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44680. _this.INVERTCUBICMAP = false;
  44681. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44682. _this.USESPHERICALINVERTEX = false;
  44683. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44684. _this.LODINREFLECTIONALPHA = false;
  44685. _this.GAMMAREFLECTION = false;
  44686. _this.RADIANCEOCCLUSION = false;
  44687. _this.HORIZONOCCLUSION = false;
  44688. _this.REFRACTION = false;
  44689. _this.REFRACTIONMAP_3D = false;
  44690. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44691. _this.LODINREFRACTIONALPHA = false;
  44692. _this.GAMMAREFRACTION = false;
  44693. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44694. _this.INSTANCES = false;
  44695. _this.NUM_BONE_INFLUENCERS = 0;
  44696. _this.BonesPerMesh = 0;
  44697. _this.NONUNIFORMSCALING = false;
  44698. _this.MORPHTARGETS = false;
  44699. _this.MORPHTARGETS_NORMAL = false;
  44700. _this.MORPHTARGETS_TANGENT = false;
  44701. _this.NUM_MORPH_INFLUENCERS = 0;
  44702. _this.IMAGEPROCESSING = false;
  44703. _this.VIGNETTE = false;
  44704. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44705. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44706. _this.TONEMAPPING = false;
  44707. _this.CONTRAST = false;
  44708. _this.COLORCURVES = false;
  44709. _this.COLORGRADING = false;
  44710. _this.COLORGRADING3D = false;
  44711. _this.SAMPLER3DGREENDEPTH = false;
  44712. _this.SAMPLER3DBGRMAP = false;
  44713. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44714. _this.EXPOSURE = false;
  44715. _this.USEPHYSICALLIGHTFALLOFF = false;
  44716. _this.TWOSIDEDLIGHTING = false;
  44717. _this.SHADOWFLOAT = false;
  44718. _this.CLIPPLANE = false;
  44719. _this.POINTSIZE = false;
  44720. _this.FOG = false;
  44721. _this.LOGARITHMICDEPTH = false;
  44722. _this.FORCENORMALFORWARD = false;
  44723. _this.SPECULARAA = false;
  44724. _this.UNLIT = false;
  44725. _this.rebuild();
  44726. return _this;
  44727. }
  44728. /**
  44729. * Resets the PBR Material defines.
  44730. */
  44731. PBRMaterialDefines.prototype.reset = function () {
  44732. _super.prototype.reset.call(this);
  44733. this.ALPHATESTVALUE = "0.5";
  44734. this.PBR = true;
  44735. };
  44736. return PBRMaterialDefines;
  44737. }(BABYLON.MaterialDefines));
  44738. /**
  44739. * The Physically based material base class of BJS.
  44740. *
  44741. * This offers the main features of a standard PBR material.
  44742. * For more information, please refer to the documentation :
  44743. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44744. */
  44745. var PBRBaseMaterial = /** @class */ (function (_super) {
  44746. __extends(PBRBaseMaterial, _super);
  44747. /**
  44748. * Instantiates a new PBRMaterial instance.
  44749. *
  44750. * @param name The material name
  44751. * @param scene The scene the material will be use in.
  44752. */
  44753. function PBRBaseMaterial(name, scene) {
  44754. var _this = _super.call(this, name, scene) || this;
  44755. /**
  44756. * Intensity of the direct lights e.g. the four lights available in your scene.
  44757. * This impacts both the direct diffuse and specular highlights.
  44758. */
  44759. _this._directIntensity = 1.0;
  44760. /**
  44761. * Intensity of the emissive part of the material.
  44762. * This helps controlling the emissive effect without modifying the emissive color.
  44763. */
  44764. _this._emissiveIntensity = 1.0;
  44765. /**
  44766. * Intensity of the environment e.g. how much the environment will light the object
  44767. * either through harmonics for rough material or through the refelction for shiny ones.
  44768. */
  44769. _this._environmentIntensity = 1.0;
  44770. /**
  44771. * This is a special control allowing the reduction of the specular highlights coming from the
  44772. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44773. */
  44774. _this._specularIntensity = 1.0;
  44775. /**
  44776. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44777. */
  44778. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44779. /**
  44780. * Debug Control allowing disabling the bump map on this material.
  44781. */
  44782. _this._disableBumpMap = false;
  44783. /**
  44784. * AKA Occlusion Texture Intensity in other nomenclature.
  44785. */
  44786. _this._ambientTextureStrength = 1.0;
  44787. /**
  44788. * The color of a material in ambient lighting.
  44789. */
  44790. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44791. /**
  44792. * AKA Diffuse Color in other nomenclature.
  44793. */
  44794. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44795. /**
  44796. * AKA Specular Color in other nomenclature.
  44797. */
  44798. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44799. /**
  44800. * The color applied when light is reflected from a material.
  44801. */
  44802. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44803. /**
  44804. * The color applied when light is emitted from a material.
  44805. */
  44806. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44807. /**
  44808. * AKA Glossiness in other nomenclature.
  44809. */
  44810. _this._microSurface = 0.9;
  44811. /**
  44812. * source material index of refraction (IOR)' / 'destination material IOR.
  44813. */
  44814. _this._indexOfRefraction = 0.66;
  44815. /**
  44816. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44817. */
  44818. _this._invertRefractionY = false;
  44819. /**
  44820. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44821. * Materials half opaque for instance using refraction could benefit from this control.
  44822. */
  44823. _this._linkRefractionWithTransparency = false;
  44824. /**
  44825. * Specifies that the material will use the light map as a show map.
  44826. */
  44827. _this._useLightmapAsShadowmap = false;
  44828. /**
  44829. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44830. * makes the reflect vector face the model (under horizon).
  44831. */
  44832. _this._useHorizonOcclusion = true;
  44833. /**
  44834. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44835. * too much the area relying on ambient texture to define their ambient occlusion.
  44836. */
  44837. _this._useRadianceOcclusion = true;
  44838. /**
  44839. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44840. */
  44841. _this._useAlphaFromAlbedoTexture = false;
  44842. /**
  44843. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44844. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44845. */
  44846. _this._useSpecularOverAlpha = true;
  44847. /**
  44848. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44849. */
  44850. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44851. /**
  44852. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44853. */
  44854. _this._useRoughnessFromMetallicTextureAlpha = true;
  44855. /**
  44856. * Specifies if the metallic texture contains the roughness information in its green channel.
  44857. */
  44858. _this._useRoughnessFromMetallicTextureGreen = false;
  44859. /**
  44860. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44861. */
  44862. _this._useMetallnessFromMetallicTextureBlue = false;
  44863. /**
  44864. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44865. */
  44866. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44867. /**
  44868. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44869. */
  44870. _this._useAmbientInGrayScale = false;
  44871. /**
  44872. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44873. * The material will try to infer what glossiness each pixel should be.
  44874. */
  44875. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44876. /**
  44877. * BJS is using an harcoded light falloff based on a manually sets up range.
  44878. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44879. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44880. */
  44881. _this._usePhysicalLightFalloff = true;
  44882. /**
  44883. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44884. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44885. */
  44886. _this._useRadianceOverAlpha = true;
  44887. /**
  44888. * Allows using an object space normal map (instead of tangent space).
  44889. */
  44890. _this._useObjectSpaceNormalMap = false;
  44891. /**
  44892. * Allows using the bump map in parallax mode.
  44893. */
  44894. _this._useParallax = false;
  44895. /**
  44896. * Allows using the bump map in parallax occlusion mode.
  44897. */
  44898. _this._useParallaxOcclusion = false;
  44899. /**
  44900. * Controls the scale bias of the parallax mode.
  44901. */
  44902. _this._parallaxScaleBias = 0.05;
  44903. /**
  44904. * If sets to true, disables all the lights affecting the material.
  44905. */
  44906. _this._disableLighting = false;
  44907. /**
  44908. * Number of Simultaneous lights allowed on the material.
  44909. */
  44910. _this._maxSimultaneousLights = 4;
  44911. /**
  44912. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44913. */
  44914. _this._invertNormalMapX = false;
  44915. /**
  44916. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44917. */
  44918. _this._invertNormalMapY = false;
  44919. /**
  44920. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44921. */
  44922. _this._twoSidedLighting = false;
  44923. /**
  44924. * Defines the alpha limits in alpha test mode.
  44925. */
  44926. _this._alphaCutOff = 0.4;
  44927. /**
  44928. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44929. */
  44930. _this._forceAlphaTest = false;
  44931. /**
  44932. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44933. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44934. */
  44935. _this._useAlphaFresnel = false;
  44936. /**
  44937. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44938. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44939. */
  44940. _this._useLinearAlphaFresnel = false;
  44941. /**
  44942. * The transparency mode of the material.
  44943. */
  44944. _this._transparencyMode = null;
  44945. /**
  44946. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44947. * from cos thetav and roughness:
  44948. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44949. */
  44950. _this._environmentBRDFTexture = null;
  44951. /**
  44952. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44953. */
  44954. _this._forceIrradianceInFragment = false;
  44955. /**
  44956. * Force normal to face away from face.
  44957. */
  44958. _this._forceNormalForward = false;
  44959. /**
  44960. * Enables specular anti aliasing in the PBR shader.
  44961. * It will both interacts on the Geometry for analytical and IBL lighting.
  44962. * It also prefilter the roughness map based on the bump values.
  44963. */
  44964. _this._enableSpecularAntiAliasing = false;
  44965. /**
  44966. * Stores the available render targets.
  44967. */
  44968. _this._renderTargets = new BABYLON.SmartArray(16);
  44969. /**
  44970. * Sets the global ambient color for the material used in lighting calculations.
  44971. */
  44972. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44973. /**
  44974. * If set to true, no lighting calculations will be applied.
  44975. */
  44976. _this._unlit = false;
  44977. // Setup the default processing configuration to the scene.
  44978. _this._attachImageProcessingConfiguration(null);
  44979. _this.getRenderTargetTextures = function () {
  44980. _this._renderTargets.reset();
  44981. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44982. _this._renderTargets.push(_this._reflectionTexture);
  44983. }
  44984. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44985. _this._renderTargets.push(_this._refractionTexture);
  44986. }
  44987. return _this._renderTargets;
  44988. };
  44989. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44990. return _this;
  44991. }
  44992. /**
  44993. * Attaches a new image processing configuration to the PBR Material.
  44994. * @param configuration
  44995. */
  44996. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44997. var _this = this;
  44998. if (configuration === this._imageProcessingConfiguration) {
  44999. return;
  45000. }
  45001. // Detaches observer.
  45002. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45003. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45004. }
  45005. // Pick the scene configuration if needed.
  45006. if (!configuration) {
  45007. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45008. }
  45009. else {
  45010. this._imageProcessingConfiguration = configuration;
  45011. }
  45012. // Attaches observer.
  45013. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45014. _this._markAllSubMeshesAsImageProcessingDirty();
  45015. });
  45016. };
  45017. /**
  45018. * Gets the name of the material class.
  45019. */
  45020. PBRBaseMaterial.prototype.getClassName = function () {
  45021. return "PBRBaseMaterial";
  45022. };
  45023. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45024. /**
  45025. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45026. */
  45027. get: function () {
  45028. return this._useLogarithmicDepth;
  45029. },
  45030. /**
  45031. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45032. */
  45033. set: function (value) {
  45034. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45035. },
  45036. enumerable: true,
  45037. configurable: true
  45038. });
  45039. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45040. /**
  45041. * Gets the current transparency mode.
  45042. */
  45043. get: function () {
  45044. return this._transparencyMode;
  45045. },
  45046. /**
  45047. * Sets the transparency mode of the material.
  45048. *
  45049. * | Value | Type | Description |
  45050. * | ----- | ----------------------------------- | ----------- |
  45051. * | 0 | OPAQUE | |
  45052. * | 1 | ALPHATEST | |
  45053. * | 2 | ALPHABLEND | |
  45054. * | 3 | ALPHATESTANDBLEND | |
  45055. *
  45056. */
  45057. set: function (value) {
  45058. if (this._transparencyMode === value) {
  45059. return;
  45060. }
  45061. this._transparencyMode = value;
  45062. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45063. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45064. },
  45065. enumerable: true,
  45066. configurable: true
  45067. });
  45068. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45069. /**
  45070. * Returns true if alpha blending should be disabled.
  45071. */
  45072. get: function () {
  45073. return (this._linkRefractionWithTransparency ||
  45074. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45075. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45076. },
  45077. enumerable: true,
  45078. configurable: true
  45079. });
  45080. /**
  45081. * Specifies whether or not this material should be rendered in alpha blend mode.
  45082. */
  45083. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45084. if (this._disableAlphaBlending) {
  45085. return false;
  45086. }
  45087. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45088. };
  45089. /**
  45090. * Specifies if the mesh will require alpha blending.
  45091. * @param mesh - BJS mesh.
  45092. */
  45093. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45094. if (this._disableAlphaBlending) {
  45095. return false;
  45096. }
  45097. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45098. };
  45099. /**
  45100. * Specifies whether or not this material should be rendered in alpha test mode.
  45101. */
  45102. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45103. if (this._forceAlphaTest) {
  45104. return true;
  45105. }
  45106. if (this._linkRefractionWithTransparency) {
  45107. return false;
  45108. }
  45109. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45110. };
  45111. /**
  45112. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45113. */
  45114. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45115. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45116. };
  45117. /**
  45118. * Gets the texture used for the alpha test.
  45119. */
  45120. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45121. return this._albedoTexture;
  45122. };
  45123. /**
  45124. * Specifies that the submesh is ready to be used.
  45125. * @param mesh - BJS mesh.
  45126. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45127. * @param useInstances - Specifies that instances should be used.
  45128. * @returns - boolean indicating that the submesh is ready or not.
  45129. */
  45130. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45131. if (subMesh.effect && this.isFrozen) {
  45132. if (this._wasPreviouslyReady) {
  45133. return true;
  45134. }
  45135. }
  45136. if (!subMesh._materialDefines) {
  45137. subMesh._materialDefines = new PBRMaterialDefines();
  45138. }
  45139. var defines = subMesh._materialDefines;
  45140. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45141. if (defines._renderId === this.getScene().getRenderId()) {
  45142. return true;
  45143. }
  45144. }
  45145. var scene = this.getScene();
  45146. var engine = scene.getEngine();
  45147. if (defines._areTexturesDirty) {
  45148. if (scene.texturesEnabled) {
  45149. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45150. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45151. return false;
  45152. }
  45153. }
  45154. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45155. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45156. return false;
  45157. }
  45158. }
  45159. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45160. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45161. return false;
  45162. }
  45163. }
  45164. var reflectionTexture = this._getReflectionTexture();
  45165. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45166. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45167. return false;
  45168. }
  45169. }
  45170. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45171. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45172. return false;
  45173. }
  45174. }
  45175. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45176. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45177. return false;
  45178. }
  45179. }
  45180. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45181. if (this._metallicTexture) {
  45182. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45183. return false;
  45184. }
  45185. }
  45186. else if (this._reflectivityTexture) {
  45187. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45188. return false;
  45189. }
  45190. }
  45191. if (this._microSurfaceTexture) {
  45192. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45193. return false;
  45194. }
  45195. }
  45196. }
  45197. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45198. // Bump texture cannot be not blocking.
  45199. if (!this._bumpTexture.isReady()) {
  45200. return false;
  45201. }
  45202. }
  45203. var refractionTexture = this._getRefractionTexture();
  45204. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45205. if (!refractionTexture.isReadyOrNotBlocking()) {
  45206. return false;
  45207. }
  45208. }
  45209. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45210. // This is blocking.
  45211. if (!this._environmentBRDFTexture.isReady()) {
  45212. return false;
  45213. }
  45214. }
  45215. }
  45216. }
  45217. if (defines._areImageProcessingDirty) {
  45218. if (!this._imageProcessingConfiguration.isReady()) {
  45219. return false;
  45220. }
  45221. }
  45222. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45223. mesh.createNormals(true);
  45224. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45225. }
  45226. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45227. if (effect) {
  45228. scene.resetCachedMaterial();
  45229. subMesh.setEffect(effect, defines);
  45230. this.buildUniformLayout();
  45231. }
  45232. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45233. return false;
  45234. }
  45235. defines._renderId = scene.getRenderId();
  45236. this._wasPreviouslyReady = true;
  45237. return true;
  45238. };
  45239. /**
  45240. * Specifies if the material uses metallic roughness workflow.
  45241. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45242. */
  45243. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45244. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45245. return true;
  45246. }
  45247. return false;
  45248. };
  45249. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45250. if (onCompiled === void 0) { onCompiled = null; }
  45251. if (onError === void 0) { onError = null; }
  45252. if (useInstances === void 0) { useInstances = null; }
  45253. if (useClipPlane === void 0) { useClipPlane = null; }
  45254. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45255. if (!defines.isDirty) {
  45256. return null;
  45257. }
  45258. defines.markAsProcessed();
  45259. var scene = this.getScene();
  45260. var engine = scene.getEngine();
  45261. // Fallbacks
  45262. var fallbacks = new BABYLON.EffectFallbacks();
  45263. var fallbackRank = 0;
  45264. if (defines.USESPHERICALINVERTEX) {
  45265. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45266. }
  45267. if (defines.FOG) {
  45268. fallbacks.addFallback(fallbackRank, "FOG");
  45269. }
  45270. if (defines.SPECULARAA) {
  45271. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45272. }
  45273. if (defines.POINTSIZE) {
  45274. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45275. }
  45276. if (defines.LOGARITHMICDEPTH) {
  45277. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45278. }
  45279. if (defines.PARALLAX) {
  45280. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45281. }
  45282. if (defines.PARALLAXOCCLUSION) {
  45283. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45284. }
  45285. if (defines.ENVIRONMENTBRDF) {
  45286. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45287. }
  45288. if (defines.TANGENT) {
  45289. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45290. }
  45291. if (defines.BUMP) {
  45292. fallbacks.addFallback(fallbackRank++, "BUMP");
  45293. }
  45294. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45295. if (defines.SPECULARTERM) {
  45296. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45297. }
  45298. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45299. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45300. }
  45301. if (defines.LIGHTMAP) {
  45302. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45303. }
  45304. if (defines.NORMAL) {
  45305. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45306. }
  45307. if (defines.AMBIENT) {
  45308. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45309. }
  45310. if (defines.EMISSIVE) {
  45311. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45312. }
  45313. if (defines.VERTEXCOLOR) {
  45314. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45315. }
  45316. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45317. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45318. }
  45319. if (defines.MORPHTARGETS) {
  45320. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45321. }
  45322. //Attributes
  45323. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45324. if (defines.NORMAL) {
  45325. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45326. }
  45327. if (defines.TANGENT) {
  45328. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45329. }
  45330. if (defines.UV1) {
  45331. attribs.push(BABYLON.VertexBuffer.UVKind);
  45332. }
  45333. if (defines.UV2) {
  45334. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45335. }
  45336. if (defines.VERTEXCOLOR) {
  45337. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45338. }
  45339. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45340. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45341. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45342. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45343. "vFogInfos", "vFogColor", "pointSize",
  45344. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45345. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45346. "mBones",
  45347. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45348. "vLightingIntensity",
  45349. "logarithmicDepthConstant",
  45350. "vSphericalX", "vSphericalY", "vSphericalZ",
  45351. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45352. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45353. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45354. "vTangentSpaceParams"
  45355. ];
  45356. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45357. "bumpSampler", "lightmapSampler", "opacitySampler",
  45358. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45359. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45360. "microSurfaceSampler", "environmentBrdfSampler"];
  45361. var uniformBuffers = ["Material", "Scene"];
  45362. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45364. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45365. uniformsNames: uniforms,
  45366. uniformBuffersNames: uniformBuffers,
  45367. samplers: samplers,
  45368. defines: defines,
  45369. maxSimultaneousLights: this._maxSimultaneousLights
  45370. });
  45371. var join = defines.toString();
  45372. return engine.createEffect("pbr", {
  45373. attributes: attribs,
  45374. uniformsNames: uniforms,
  45375. uniformBuffersNames: uniformBuffers,
  45376. samplers: samplers,
  45377. defines: join,
  45378. fallbacks: fallbacks,
  45379. onCompiled: onCompiled,
  45380. onError: onError,
  45381. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45382. }, engine);
  45383. };
  45384. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45385. if (useInstances === void 0) { useInstances = null; }
  45386. if (useClipPlane === void 0) { useClipPlane = null; }
  45387. var scene = this.getScene();
  45388. var engine = scene.getEngine();
  45389. // Lights
  45390. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45391. defines._needNormals = true;
  45392. // Textures
  45393. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45394. if (defines._areTexturesDirty) {
  45395. defines._needUVs = false;
  45396. if (scene.texturesEnabled) {
  45397. if (scene.getEngine().getCaps().textureLOD) {
  45398. defines.LODBASEDMICROSFURACE = true;
  45399. }
  45400. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45402. }
  45403. else {
  45404. defines.ALBEDO = false;
  45405. }
  45406. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45408. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45409. }
  45410. else {
  45411. defines.AMBIENT = false;
  45412. }
  45413. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45414. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45415. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45416. }
  45417. else {
  45418. defines.OPACITY = false;
  45419. }
  45420. var reflectionTexture = this._getReflectionTexture();
  45421. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45422. defines.REFLECTION = true;
  45423. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45424. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45425. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45426. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45427. defines.INVERTCUBICMAP = true;
  45428. }
  45429. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45430. switch (reflectionTexture.coordinatesMode) {
  45431. case BABYLON.Texture.EXPLICIT_MODE:
  45432. defines.REFLECTIONMAP_EXPLICIT = true;
  45433. break;
  45434. case BABYLON.Texture.PLANAR_MODE:
  45435. defines.REFLECTIONMAP_PLANAR = true;
  45436. break;
  45437. case BABYLON.Texture.PROJECTION_MODE:
  45438. defines.REFLECTIONMAP_PROJECTION = true;
  45439. break;
  45440. case BABYLON.Texture.SKYBOX_MODE:
  45441. defines.REFLECTIONMAP_SKYBOX = true;
  45442. break;
  45443. case BABYLON.Texture.SPHERICAL_MODE:
  45444. defines.REFLECTIONMAP_SPHERICAL = true;
  45445. break;
  45446. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45447. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45448. break;
  45449. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45450. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45451. break;
  45452. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45453. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45454. break;
  45455. case BABYLON.Texture.CUBIC_MODE:
  45456. case BABYLON.Texture.INVCUBIC_MODE:
  45457. default:
  45458. defines.REFLECTIONMAP_CUBIC = true;
  45459. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45460. break;
  45461. }
  45462. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45463. if (reflectionTexture.sphericalPolynomial) {
  45464. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45465. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45466. defines.USESPHERICALINVERTEX = false;
  45467. }
  45468. else {
  45469. defines.USESPHERICALINVERTEX = true;
  45470. }
  45471. }
  45472. }
  45473. }
  45474. else {
  45475. defines.REFLECTION = false;
  45476. defines.REFLECTIONMAP_3D = false;
  45477. defines.REFLECTIONMAP_SPHERICAL = false;
  45478. defines.REFLECTIONMAP_PLANAR = false;
  45479. defines.REFLECTIONMAP_CUBIC = false;
  45480. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45481. defines.REFLECTIONMAP_PROJECTION = false;
  45482. defines.REFLECTIONMAP_SKYBOX = false;
  45483. defines.REFLECTIONMAP_EXPLICIT = false;
  45484. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45485. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45486. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45487. defines.INVERTCUBICMAP = false;
  45488. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45489. defines.USESPHERICALINVERTEX = false;
  45490. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45491. defines.LODINREFLECTIONALPHA = false;
  45492. defines.GAMMAREFLECTION = false;
  45493. }
  45494. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45495. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45496. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45497. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45498. }
  45499. else {
  45500. defines.LIGHTMAP = false;
  45501. }
  45502. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45503. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45504. }
  45505. else {
  45506. defines.EMISSIVE = false;
  45507. }
  45508. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45509. if (this._metallicTexture) {
  45510. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45511. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45512. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45513. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45514. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45515. }
  45516. else if (this._reflectivityTexture) {
  45517. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45518. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45519. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45520. }
  45521. else {
  45522. defines.REFLECTIVITY = false;
  45523. }
  45524. if (this._microSurfaceTexture) {
  45525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45526. }
  45527. else {
  45528. defines.MICROSURFACEMAP = false;
  45529. }
  45530. }
  45531. else {
  45532. defines.REFLECTIVITY = false;
  45533. defines.MICROSURFACEMAP = false;
  45534. }
  45535. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45537. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45538. defines.PARALLAX = true;
  45539. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45540. }
  45541. else {
  45542. defines.PARALLAX = false;
  45543. }
  45544. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45545. }
  45546. else {
  45547. defines.BUMP = false;
  45548. }
  45549. var refractionTexture = this._getRefractionTexture();
  45550. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45551. defines.REFRACTION = true;
  45552. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45553. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45554. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45555. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45556. if (this._linkRefractionWithTransparency) {
  45557. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45558. }
  45559. }
  45560. else {
  45561. defines.REFRACTION = false;
  45562. }
  45563. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45564. defines.ENVIRONMENTBRDF = true;
  45565. }
  45566. else {
  45567. defines.ENVIRONMENTBRDF = false;
  45568. }
  45569. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45570. defines.ALPHAFROMALBEDO = true;
  45571. }
  45572. else {
  45573. defines.ALPHAFROMALBEDO = false;
  45574. }
  45575. }
  45576. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45577. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45578. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45579. if (!this.backFaceCulling && this._twoSidedLighting) {
  45580. defines.TWOSIDEDLIGHTING = true;
  45581. }
  45582. else {
  45583. defines.TWOSIDEDLIGHTING = false;
  45584. }
  45585. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45586. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45587. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45588. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45589. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45590. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45591. }
  45592. if (defines._areImageProcessingDirty) {
  45593. this._imageProcessingConfiguration.prepareDefines(defines);
  45594. }
  45595. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45596. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45597. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45598. // Misc.
  45599. if (defines._areMiscDirty) {
  45600. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45601. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45602. }
  45603. // Values that need to be evaluated on every frame
  45604. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45605. // Attribs
  45606. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45607. };
  45608. /**
  45609. * Force shader compilation
  45610. */
  45611. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45612. var _this = this;
  45613. var localOptions = __assign({ clipPlane: false }, options);
  45614. var defines = new PBRMaterialDefines();
  45615. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45616. if (effect.isReady()) {
  45617. if (onCompiled) {
  45618. onCompiled(this);
  45619. }
  45620. }
  45621. else {
  45622. effect.onCompileObservable.add(function () {
  45623. if (onCompiled) {
  45624. onCompiled(_this);
  45625. }
  45626. });
  45627. }
  45628. };
  45629. /**
  45630. * Initializes the uniform buffer layout for the shader.
  45631. */
  45632. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45633. // Order is important !
  45634. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45635. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45636. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45637. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45638. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45639. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45640. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45641. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45642. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45643. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45644. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45645. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45646. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45647. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45648. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45649. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45650. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45651. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45652. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45653. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45654. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45655. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45656. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45657. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45658. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45659. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45660. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45661. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45662. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45663. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45664. this._uniformBuffer.addUniform("pointSize", 1);
  45665. this._uniformBuffer.create();
  45666. };
  45667. /**
  45668. * Unbinds the textures.
  45669. */
  45670. PBRBaseMaterial.prototype.unbind = function () {
  45671. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45672. this._uniformBuffer.setTexture("reflectionSampler", null);
  45673. }
  45674. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45675. this._uniformBuffer.setTexture("refractionSampler", null);
  45676. }
  45677. _super.prototype.unbind.call(this);
  45678. };
  45679. /**
  45680. * Binds the submesh data.
  45681. * @param world - The world matrix.
  45682. * @param mesh - The BJS mesh.
  45683. * @param subMesh - A submesh of the BJS mesh.
  45684. */
  45685. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45686. var scene = this.getScene();
  45687. var defines = subMesh._materialDefines;
  45688. if (!defines) {
  45689. return;
  45690. }
  45691. var effect = subMesh.effect;
  45692. if (!effect) {
  45693. return;
  45694. }
  45695. this._activeEffect = effect;
  45696. // Matrices
  45697. this.bindOnlyWorldMatrix(world);
  45698. // Normal Matrix
  45699. if (defines.OBJECTSPACE_NORMALMAP) {
  45700. world.toNormalMatrix(this._normalMatrix);
  45701. this.bindOnlyNormalMatrix(this._normalMatrix);
  45702. }
  45703. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45704. // Bones
  45705. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45706. var reflectionTexture = null;
  45707. if (mustRebind) {
  45708. this._uniformBuffer.bindToEffect(effect, "Material");
  45709. this.bindViewProjection(effect);
  45710. reflectionTexture = this._getReflectionTexture();
  45711. var refractionTexture = this._getRefractionTexture();
  45712. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45713. // Texture uniforms
  45714. if (scene.texturesEnabled) {
  45715. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45716. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45717. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45718. }
  45719. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45720. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45721. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45722. }
  45723. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45724. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45725. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45726. }
  45727. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45728. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45729. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45730. if (reflectionTexture.boundingBoxSize) {
  45731. var cubeTexture = reflectionTexture;
  45732. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45733. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45734. }
  45735. var polynomials = reflectionTexture.sphericalPolynomial;
  45736. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45737. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45738. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45739. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45740. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45741. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45742. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45743. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45744. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45745. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45746. }
  45747. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45748. }
  45749. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45750. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45751. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45752. }
  45753. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45754. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45755. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45756. }
  45757. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45758. if (this._metallicTexture) {
  45759. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45760. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45761. }
  45762. else if (this._reflectivityTexture) {
  45763. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45764. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45765. }
  45766. if (this._microSurfaceTexture) {
  45767. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45768. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45769. }
  45770. }
  45771. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45772. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45773. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45774. if (scene._mirroredCameraPosition) {
  45775. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45776. }
  45777. else {
  45778. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45779. }
  45780. }
  45781. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45782. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45783. var depth = 1.0;
  45784. if (!refractionTexture.isCube) {
  45785. if (refractionTexture.depth) {
  45786. depth = refractionTexture.depth;
  45787. }
  45788. }
  45789. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45790. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45791. }
  45792. }
  45793. // Point size
  45794. if (this.pointsCloud) {
  45795. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45796. }
  45797. // Colors
  45798. if (defines.METALLICWORKFLOW) {
  45799. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45800. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45801. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45802. }
  45803. else {
  45804. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45805. }
  45806. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45807. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45808. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45809. // Misc
  45810. this._lightingInfos.x = this._directIntensity;
  45811. this._lightingInfos.y = this._emissiveIntensity;
  45812. this._lightingInfos.z = this._environmentIntensity;
  45813. this._lightingInfos.w = this._specularIntensity;
  45814. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45815. }
  45816. // Textures
  45817. if (scene.texturesEnabled) {
  45818. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45819. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45820. }
  45821. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45822. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45823. }
  45824. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45825. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45826. }
  45827. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45828. if (defines.LODBASEDMICROSFURACE) {
  45829. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45830. }
  45831. else {
  45832. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45833. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45834. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45835. }
  45836. }
  45837. if (defines.ENVIRONMENTBRDF) {
  45838. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45839. }
  45840. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45841. if (defines.LODBASEDMICROSFURACE) {
  45842. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45843. }
  45844. else {
  45845. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45846. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45847. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45848. }
  45849. }
  45850. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45851. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45852. }
  45853. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45854. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45855. }
  45856. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45857. if (this._metallicTexture) {
  45858. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45859. }
  45860. else if (this._reflectivityTexture) {
  45861. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45862. }
  45863. if (this._microSurfaceTexture) {
  45864. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45865. }
  45866. }
  45867. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45868. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45869. }
  45870. }
  45871. // Clip plane
  45872. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45873. // Colors
  45874. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45875. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45876. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45877. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45878. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45879. }
  45880. if (mustRebind || !this.isFrozen) {
  45881. // Lights
  45882. if (scene.lightsEnabled && !this._disableLighting) {
  45883. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45884. }
  45885. // View
  45886. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45887. this.bindView(effect);
  45888. }
  45889. // Fog
  45890. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45891. // Morph targets
  45892. if (defines.NUM_MORPH_INFLUENCERS) {
  45893. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45894. }
  45895. // image processing
  45896. this._imageProcessingConfiguration.bind(this._activeEffect);
  45897. // Log. depth
  45898. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45899. }
  45900. this._uniformBuffer.update();
  45901. this._afterBind(mesh, this._activeEffect);
  45902. };
  45903. /**
  45904. * Returns the animatable textures.
  45905. * @returns - Array of animatable textures.
  45906. */
  45907. PBRBaseMaterial.prototype.getAnimatables = function () {
  45908. var results = [];
  45909. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45910. results.push(this._albedoTexture);
  45911. }
  45912. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45913. results.push(this._ambientTexture);
  45914. }
  45915. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45916. results.push(this._opacityTexture);
  45917. }
  45918. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45919. results.push(this._reflectionTexture);
  45920. }
  45921. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45922. results.push(this._emissiveTexture);
  45923. }
  45924. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45925. results.push(this._metallicTexture);
  45926. }
  45927. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45928. results.push(this._reflectivityTexture);
  45929. }
  45930. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45931. results.push(this._bumpTexture);
  45932. }
  45933. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45934. results.push(this._lightmapTexture);
  45935. }
  45936. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45937. results.push(this._refractionTexture);
  45938. }
  45939. return results;
  45940. };
  45941. /**
  45942. * Returns the texture used for reflections.
  45943. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45944. */
  45945. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45946. if (this._reflectionTexture) {
  45947. return this._reflectionTexture;
  45948. }
  45949. return this.getScene().environmentTexture;
  45950. };
  45951. /**
  45952. * Returns the texture used for refraction or null if none is used.
  45953. * @returns - Refection texture if present. If no refraction texture and refraction
  45954. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45955. */
  45956. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45957. if (this._refractionTexture) {
  45958. return this._refractionTexture;
  45959. }
  45960. if (this._linkRefractionWithTransparency) {
  45961. return this.getScene().environmentTexture;
  45962. }
  45963. return null;
  45964. };
  45965. /**
  45966. * Disposes the resources of the material.
  45967. * @param forceDisposeEffect - Forces the disposal of effects.
  45968. * @param forceDisposeTextures - Forces the disposal of all textures.
  45969. */
  45970. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45971. if (forceDisposeTextures) {
  45972. if (this._albedoTexture) {
  45973. this._albedoTexture.dispose();
  45974. }
  45975. if (this._ambientTexture) {
  45976. this._ambientTexture.dispose();
  45977. }
  45978. if (this._opacityTexture) {
  45979. this._opacityTexture.dispose();
  45980. }
  45981. if (this._reflectionTexture) {
  45982. this._reflectionTexture.dispose();
  45983. }
  45984. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45985. this._environmentBRDFTexture.dispose();
  45986. }
  45987. if (this._emissiveTexture) {
  45988. this._emissiveTexture.dispose();
  45989. }
  45990. if (this._metallicTexture) {
  45991. this._metallicTexture.dispose();
  45992. }
  45993. if (this._reflectivityTexture) {
  45994. this._reflectivityTexture.dispose();
  45995. }
  45996. if (this._bumpTexture) {
  45997. this._bumpTexture.dispose();
  45998. }
  45999. if (this._lightmapTexture) {
  46000. this._lightmapTexture.dispose();
  46001. }
  46002. if (this._refractionTexture) {
  46003. this._refractionTexture.dispose();
  46004. }
  46005. }
  46006. this._renderTargets.dispose();
  46007. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46008. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46009. }
  46010. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46011. };
  46012. /**
  46013. * Stores the reflectivity values based on metallic roughness workflow.
  46014. */
  46015. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46016. __decorate([
  46017. BABYLON.serializeAsImageProcessingConfiguration()
  46018. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46019. __decorate([
  46020. BABYLON.serialize()
  46021. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46022. __decorate([
  46023. BABYLON.serialize()
  46024. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46025. return PBRBaseMaterial;
  46026. }(BABYLON.PushMaterial));
  46027. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46028. })(BABYLON || (BABYLON = {}));
  46029. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46030. var BABYLON;
  46031. (function (BABYLON) {
  46032. /**
  46033. * The Physically based simple base material of BJS.
  46034. *
  46035. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46036. * It is used as the base class for both the specGloss and metalRough conventions.
  46037. */
  46038. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46039. __extends(PBRBaseSimpleMaterial, _super);
  46040. /**
  46041. * Instantiates a new PBRMaterial instance.
  46042. *
  46043. * @param name The material name
  46044. * @param scene The scene the material will be use in.
  46045. */
  46046. function PBRBaseSimpleMaterial(name, scene) {
  46047. var _this = _super.call(this, name, scene) || this;
  46048. /**
  46049. * Number of Simultaneous lights allowed on the material.
  46050. */
  46051. _this.maxSimultaneousLights = 4;
  46052. /**
  46053. * If sets to true, disables all the lights affecting the material.
  46054. */
  46055. _this.disableLighting = false;
  46056. /**
  46057. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46058. */
  46059. _this.invertNormalMapX = false;
  46060. /**
  46061. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46062. */
  46063. _this.invertNormalMapY = false;
  46064. /**
  46065. * Emissivie color used to self-illuminate the model.
  46066. */
  46067. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46068. /**
  46069. * Occlusion Channel Strenght.
  46070. */
  46071. _this.occlusionStrength = 1.0;
  46072. _this.useLightmapAsShadowmap = false;
  46073. _this._useAlphaFromAlbedoTexture = true;
  46074. _this._useAmbientInGrayScale = true;
  46075. return _this;
  46076. }
  46077. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46078. /**
  46079. * Gets the current double sided mode.
  46080. */
  46081. get: function () {
  46082. return this._twoSidedLighting;
  46083. },
  46084. /**
  46085. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46086. */
  46087. set: function (value) {
  46088. if (this._twoSidedLighting === value) {
  46089. return;
  46090. }
  46091. this._twoSidedLighting = value;
  46092. this.backFaceCulling = !value;
  46093. this._markAllSubMeshesAsTexturesDirty();
  46094. },
  46095. enumerable: true,
  46096. configurable: true
  46097. });
  46098. /**
  46099. * Return the active textures of the material.
  46100. */
  46101. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46102. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46103. if (this.environmentTexture) {
  46104. activeTextures.push(this.environmentTexture);
  46105. }
  46106. if (this.normalTexture) {
  46107. activeTextures.push(this.normalTexture);
  46108. }
  46109. if (this.emissiveTexture) {
  46110. activeTextures.push(this.emissiveTexture);
  46111. }
  46112. if (this.occlusionTexture) {
  46113. activeTextures.push(this.occlusionTexture);
  46114. }
  46115. if (this.lightmapTexture) {
  46116. activeTextures.push(this.lightmapTexture);
  46117. }
  46118. return activeTextures;
  46119. };
  46120. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46121. if (_super.prototype.hasTexture.call(this, texture)) {
  46122. return true;
  46123. }
  46124. if (this.lightmapTexture === texture) {
  46125. return true;
  46126. }
  46127. return false;
  46128. };
  46129. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46130. return "PBRBaseSimpleMaterial";
  46131. };
  46132. __decorate([
  46133. BABYLON.serialize(),
  46134. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46135. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46136. __decorate([
  46137. BABYLON.serialize(),
  46138. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46139. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46140. __decorate([
  46141. BABYLON.serializeAsTexture(),
  46142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46143. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46144. __decorate([
  46145. BABYLON.serialize(),
  46146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46147. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46148. __decorate([
  46149. BABYLON.serialize(),
  46150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46151. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46152. __decorate([
  46153. BABYLON.serializeAsTexture(),
  46154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46155. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46156. __decorate([
  46157. BABYLON.serializeAsColor3("emissive"),
  46158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46159. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46160. __decorate([
  46161. BABYLON.serializeAsTexture(),
  46162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46163. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46164. __decorate([
  46165. BABYLON.serialize(),
  46166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46167. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46168. __decorate([
  46169. BABYLON.serializeAsTexture(),
  46170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46171. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46172. __decorate([
  46173. BABYLON.serialize(),
  46174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46175. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46176. __decorate([
  46177. BABYLON.serialize()
  46178. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46179. __decorate([
  46180. BABYLON.serializeAsTexture(),
  46181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46182. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46183. __decorate([
  46184. BABYLON.serialize(),
  46185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46186. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46187. return PBRBaseSimpleMaterial;
  46188. }(BABYLON.PBRBaseMaterial));
  46189. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46190. })(BABYLON || (BABYLON = {}));
  46191. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46192. var BABYLON;
  46193. (function (BABYLON) {
  46194. /**
  46195. * The Physically based material of BJS.
  46196. *
  46197. * This offers the main features of a standard PBR material.
  46198. * For more information, please refer to the documentation :
  46199. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46200. */
  46201. var PBRMaterial = /** @class */ (function (_super) {
  46202. __extends(PBRMaterial, _super);
  46203. /**
  46204. * Instantiates a new PBRMaterial instance.
  46205. *
  46206. * @param name The material name
  46207. * @param scene The scene the material will be use in.
  46208. */
  46209. function PBRMaterial(name, scene) {
  46210. var _this = _super.call(this, name, scene) || this;
  46211. /**
  46212. * Intensity of the direct lights e.g. the four lights available in your scene.
  46213. * This impacts both the direct diffuse and specular highlights.
  46214. */
  46215. _this.directIntensity = 1.0;
  46216. /**
  46217. * Intensity of the emissive part of the material.
  46218. * This helps controlling the emissive effect without modifying the emissive color.
  46219. */
  46220. _this.emissiveIntensity = 1.0;
  46221. /**
  46222. * Intensity of the environment e.g. how much the environment will light the object
  46223. * either through harmonics for rough material or through the refelction for shiny ones.
  46224. */
  46225. _this.environmentIntensity = 1.0;
  46226. /**
  46227. * This is a special control allowing the reduction of the specular highlights coming from the
  46228. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46229. */
  46230. _this.specularIntensity = 1.0;
  46231. /**
  46232. * Debug Control allowing disabling the bump map on this material.
  46233. */
  46234. _this.disableBumpMap = false;
  46235. /**
  46236. * AKA Occlusion Texture Intensity in other nomenclature.
  46237. */
  46238. _this.ambientTextureStrength = 1.0;
  46239. /**
  46240. * The color of a material in ambient lighting.
  46241. */
  46242. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46243. /**
  46244. * AKA Diffuse Color in other nomenclature.
  46245. */
  46246. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46247. /**
  46248. * AKA Specular Color in other nomenclature.
  46249. */
  46250. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46251. /**
  46252. * The color reflected from the material.
  46253. */
  46254. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46255. /**
  46256. * The color emitted from the material.
  46257. */
  46258. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46259. /**
  46260. * AKA Glossiness in other nomenclature.
  46261. */
  46262. _this.microSurface = 1.0;
  46263. /**
  46264. * source material index of refraction (IOR)' / 'destination material IOR.
  46265. */
  46266. _this.indexOfRefraction = 0.66;
  46267. /**
  46268. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46269. */
  46270. _this.invertRefractionY = false;
  46271. /**
  46272. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46273. * Materials half opaque for instance using refraction could benefit from this control.
  46274. */
  46275. _this.linkRefractionWithTransparency = false;
  46276. _this.useLightmapAsShadowmap = false;
  46277. /**
  46278. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46279. */
  46280. _this.useAlphaFromAlbedoTexture = false;
  46281. /**
  46282. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46283. */
  46284. _this.forceAlphaTest = false;
  46285. /**
  46286. * Defines the alpha limits in alpha test mode.
  46287. */
  46288. _this.alphaCutOff = 0.4;
  46289. /**
  46290. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46291. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46292. */
  46293. _this.useSpecularOverAlpha = true;
  46294. /**
  46295. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46296. */
  46297. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46298. /**
  46299. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46300. */
  46301. _this.useRoughnessFromMetallicTextureAlpha = true;
  46302. /**
  46303. * Specifies if the metallic texture contains the roughness information in its green channel.
  46304. */
  46305. _this.useRoughnessFromMetallicTextureGreen = false;
  46306. /**
  46307. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46308. */
  46309. _this.useMetallnessFromMetallicTextureBlue = false;
  46310. /**
  46311. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46312. */
  46313. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46314. /**
  46315. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46316. */
  46317. _this.useAmbientInGrayScale = false;
  46318. /**
  46319. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46320. * The material will try to infer what glossiness each pixel should be.
  46321. */
  46322. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46323. /**
  46324. * BJS is using an harcoded light falloff based on a manually sets up range.
  46325. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46326. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46327. */
  46328. _this.usePhysicalLightFalloff = true;
  46329. /**
  46330. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46331. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46332. */
  46333. _this.useRadianceOverAlpha = true;
  46334. /**
  46335. * Allows using an object space normal map (instead of tangent space).
  46336. */
  46337. _this.useObjectSpaceNormalMap = false;
  46338. /**
  46339. * Allows using the bump map in parallax mode.
  46340. */
  46341. _this.useParallax = false;
  46342. /**
  46343. * Allows using the bump map in parallax occlusion mode.
  46344. */
  46345. _this.useParallaxOcclusion = false;
  46346. /**
  46347. * Controls the scale bias of the parallax mode.
  46348. */
  46349. _this.parallaxScaleBias = 0.05;
  46350. /**
  46351. * If sets to true, disables all the lights affecting the material.
  46352. */
  46353. _this.disableLighting = false;
  46354. /**
  46355. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46356. */
  46357. _this.forceIrradianceInFragment = false;
  46358. /**
  46359. * Number of Simultaneous lights allowed on the material.
  46360. */
  46361. _this.maxSimultaneousLights = 4;
  46362. /**
  46363. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46364. */
  46365. _this.invertNormalMapX = false;
  46366. /**
  46367. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46368. */
  46369. _this.invertNormalMapY = false;
  46370. /**
  46371. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46372. */
  46373. _this.twoSidedLighting = false;
  46374. /**
  46375. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46376. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46377. */
  46378. _this.useAlphaFresnel = false;
  46379. /**
  46380. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46381. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46382. */
  46383. _this.useLinearAlphaFresnel = false;
  46384. /**
  46385. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46386. * And/Or occlude the blended part.
  46387. */
  46388. _this.environmentBRDFTexture = null;
  46389. /**
  46390. * Force normal to face away from face.
  46391. */
  46392. _this.forceNormalForward = false;
  46393. /**
  46394. * Enables specular anti aliasing in the PBR shader.
  46395. * It will both interacts on the Geometry for analytical and IBL lighting.
  46396. * It also prefilter the roughness map based on the bump values.
  46397. */
  46398. _this.enableSpecularAntiAliasing = false;
  46399. /**
  46400. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46401. * makes the reflect vector face the model (under horizon).
  46402. */
  46403. _this.useHorizonOcclusion = true;
  46404. /**
  46405. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46406. * too much the area relying on ambient texture to define their ambient occlusion.
  46407. */
  46408. _this.useRadianceOcclusion = true;
  46409. /**
  46410. * If set to true, no lighting calculations will be applied.
  46411. */
  46412. _this.unlit = false;
  46413. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46414. return _this;
  46415. }
  46416. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46417. /**
  46418. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46419. */
  46420. get: function () {
  46421. return this._PBRMATERIAL_OPAQUE;
  46422. },
  46423. enumerable: true,
  46424. configurable: true
  46425. });
  46426. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46427. /**
  46428. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46429. */
  46430. get: function () {
  46431. return this._PBRMATERIAL_ALPHATEST;
  46432. },
  46433. enumerable: true,
  46434. configurable: true
  46435. });
  46436. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46437. /**
  46438. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46439. */
  46440. get: function () {
  46441. return this._PBRMATERIAL_ALPHABLEND;
  46442. },
  46443. enumerable: true,
  46444. configurable: true
  46445. });
  46446. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46447. /**
  46448. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46449. * They are also discarded below the alpha cutoff threshold to improve performances.
  46450. */
  46451. get: function () {
  46452. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46453. },
  46454. enumerable: true,
  46455. configurable: true
  46456. });
  46457. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46458. /**
  46459. * Gets the image processing configuration used either in this material.
  46460. */
  46461. get: function () {
  46462. return this._imageProcessingConfiguration;
  46463. },
  46464. /**
  46465. * Sets the Default image processing configuration used either in the this material.
  46466. *
  46467. * If sets to null, the scene one is in use.
  46468. */
  46469. set: function (value) {
  46470. this._attachImageProcessingConfiguration(value);
  46471. // Ensure the effect will be rebuilt.
  46472. this._markAllSubMeshesAsTexturesDirty();
  46473. },
  46474. enumerable: true,
  46475. configurable: true
  46476. });
  46477. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46478. /**
  46479. * Gets wether the color curves effect is enabled.
  46480. */
  46481. get: function () {
  46482. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46483. },
  46484. /**
  46485. * Sets wether the color curves effect is enabled.
  46486. */
  46487. set: function (value) {
  46488. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46489. },
  46490. enumerable: true,
  46491. configurable: true
  46492. });
  46493. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46494. /**
  46495. * Gets wether the color grading effect is enabled.
  46496. */
  46497. get: function () {
  46498. return this.imageProcessingConfiguration.colorGradingEnabled;
  46499. },
  46500. /**
  46501. * Gets wether the color grading effect is enabled.
  46502. */
  46503. set: function (value) {
  46504. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46505. },
  46506. enumerable: true,
  46507. configurable: true
  46508. });
  46509. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46510. /**
  46511. * Gets wether tonemapping is enabled or not.
  46512. */
  46513. get: function () {
  46514. return this._imageProcessingConfiguration.toneMappingEnabled;
  46515. },
  46516. /**
  46517. * Sets wether tonemapping is enabled or not
  46518. */
  46519. set: function (value) {
  46520. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46521. },
  46522. enumerable: true,
  46523. configurable: true
  46524. });
  46525. ;
  46526. ;
  46527. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46528. /**
  46529. * The camera exposure used on this material.
  46530. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46531. * This corresponds to a photographic exposure.
  46532. */
  46533. get: function () {
  46534. return this._imageProcessingConfiguration.exposure;
  46535. },
  46536. /**
  46537. * The camera exposure used on this material.
  46538. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46539. * This corresponds to a photographic exposure.
  46540. */
  46541. set: function (value) {
  46542. this._imageProcessingConfiguration.exposure = value;
  46543. },
  46544. enumerable: true,
  46545. configurable: true
  46546. });
  46547. ;
  46548. ;
  46549. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46550. /**
  46551. * Gets The camera contrast used on this material.
  46552. */
  46553. get: function () {
  46554. return this._imageProcessingConfiguration.contrast;
  46555. },
  46556. /**
  46557. * Sets The camera contrast used on this material.
  46558. */
  46559. set: function (value) {
  46560. this._imageProcessingConfiguration.contrast = value;
  46561. },
  46562. enumerable: true,
  46563. configurable: true
  46564. });
  46565. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46566. /**
  46567. * Gets the Color Grading 2D Lookup Texture.
  46568. */
  46569. get: function () {
  46570. return this._imageProcessingConfiguration.colorGradingTexture;
  46571. },
  46572. /**
  46573. * Sets the Color Grading 2D Lookup Texture.
  46574. */
  46575. set: function (value) {
  46576. this._imageProcessingConfiguration.colorGradingTexture = value;
  46577. },
  46578. enumerable: true,
  46579. configurable: true
  46580. });
  46581. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46582. /**
  46583. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46584. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46585. * 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;
  46586. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46587. */
  46588. get: function () {
  46589. return this._imageProcessingConfiguration.colorCurves;
  46590. },
  46591. /**
  46592. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46593. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46594. * 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;
  46595. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46596. */
  46597. set: function (value) {
  46598. this._imageProcessingConfiguration.colorCurves = value;
  46599. },
  46600. enumerable: true,
  46601. configurable: true
  46602. });
  46603. /**
  46604. * Returns the name of this material class.
  46605. */
  46606. PBRMaterial.prototype.getClassName = function () {
  46607. return "PBRMaterial";
  46608. };
  46609. /**
  46610. * Returns an array of the actively used textures.
  46611. * @returns - Array of BaseTextures
  46612. */
  46613. PBRMaterial.prototype.getActiveTextures = function () {
  46614. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46615. if (this._albedoTexture) {
  46616. activeTextures.push(this._albedoTexture);
  46617. }
  46618. if (this._ambientTexture) {
  46619. activeTextures.push(this._ambientTexture);
  46620. }
  46621. if (this._opacityTexture) {
  46622. activeTextures.push(this._opacityTexture);
  46623. }
  46624. if (this._reflectionTexture) {
  46625. activeTextures.push(this._reflectionTexture);
  46626. }
  46627. if (this._emissiveTexture) {
  46628. activeTextures.push(this._emissiveTexture);
  46629. }
  46630. if (this._reflectivityTexture) {
  46631. activeTextures.push(this._reflectivityTexture);
  46632. }
  46633. if (this._metallicTexture) {
  46634. activeTextures.push(this._metallicTexture);
  46635. }
  46636. if (this._microSurfaceTexture) {
  46637. activeTextures.push(this._microSurfaceTexture);
  46638. }
  46639. if (this._bumpTexture) {
  46640. activeTextures.push(this._bumpTexture);
  46641. }
  46642. if (this._lightmapTexture) {
  46643. activeTextures.push(this._lightmapTexture);
  46644. }
  46645. if (this._refractionTexture) {
  46646. activeTextures.push(this._refractionTexture);
  46647. }
  46648. return activeTextures;
  46649. };
  46650. /**
  46651. * Checks to see if a texture is used in the material.
  46652. * @param texture - Base texture to use.
  46653. * @returns - Boolean specifying if a texture is used in the material.
  46654. */
  46655. PBRMaterial.prototype.hasTexture = function (texture) {
  46656. if (_super.prototype.hasTexture.call(this, texture)) {
  46657. return true;
  46658. }
  46659. if (this._albedoTexture === texture) {
  46660. return true;
  46661. }
  46662. if (this._ambientTexture === texture) {
  46663. return true;
  46664. }
  46665. if (this._opacityTexture === texture) {
  46666. return true;
  46667. }
  46668. if (this._reflectionTexture === texture) {
  46669. return true;
  46670. }
  46671. if (this._reflectivityTexture === texture) {
  46672. return true;
  46673. }
  46674. if (this._metallicTexture === texture) {
  46675. return true;
  46676. }
  46677. if (this._microSurfaceTexture === texture) {
  46678. return true;
  46679. }
  46680. if (this._bumpTexture === texture) {
  46681. return true;
  46682. }
  46683. if (this._lightmapTexture === texture) {
  46684. return true;
  46685. }
  46686. if (this._refractionTexture === texture) {
  46687. return true;
  46688. }
  46689. return false;
  46690. };
  46691. /**
  46692. * Makes a duplicate of the current material.
  46693. * @param name - name to use for the new material.
  46694. */
  46695. PBRMaterial.prototype.clone = function (name) {
  46696. var _this = this;
  46697. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46698. clone.id = name;
  46699. clone.name = name;
  46700. return clone;
  46701. };
  46702. /**
  46703. * Serializes this PBR Material.
  46704. * @returns - An object with the serialized material.
  46705. */
  46706. PBRMaterial.prototype.serialize = function () {
  46707. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46708. serializationObject.customType = "BABYLON.PBRMaterial";
  46709. return serializationObject;
  46710. };
  46711. // Statics
  46712. /**
  46713. * Parses a PBR Material from a serialized object.
  46714. * @param source - Serialized object.
  46715. * @param scene - BJS scene instance.
  46716. * @param rootUrl - url for the scene object
  46717. * @returns - PBRMaterial
  46718. */
  46719. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46720. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46721. };
  46722. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46723. /**
  46724. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46725. */
  46726. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46727. /**
  46728. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46729. */
  46730. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46731. /**
  46732. * 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.
  46733. * They are also discarded below the alpha cutoff threshold to improve performances.
  46734. */
  46735. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46736. __decorate([
  46737. BABYLON.serialize(),
  46738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46739. ], PBRMaterial.prototype, "directIntensity", void 0);
  46740. __decorate([
  46741. BABYLON.serialize(),
  46742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46743. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46744. __decorate([
  46745. BABYLON.serialize(),
  46746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46747. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46748. __decorate([
  46749. BABYLON.serialize(),
  46750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46751. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46752. __decorate([
  46753. BABYLON.serialize(),
  46754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46755. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46756. __decorate([
  46757. BABYLON.serializeAsTexture(),
  46758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46759. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46760. __decorate([
  46761. BABYLON.serializeAsTexture(),
  46762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46763. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46764. __decorate([
  46765. BABYLON.serialize(),
  46766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46767. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46768. __decorate([
  46769. BABYLON.serializeAsTexture(),
  46770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46771. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46772. __decorate([
  46773. BABYLON.serializeAsTexture(),
  46774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46775. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46776. __decorate([
  46777. BABYLON.serializeAsTexture(),
  46778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46779. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46780. __decorate([
  46781. BABYLON.serializeAsTexture(),
  46782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46783. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46784. __decorate([
  46785. BABYLON.serializeAsTexture(),
  46786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46787. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46788. __decorate([
  46789. BABYLON.serialize(),
  46790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46791. ], PBRMaterial.prototype, "metallic", void 0);
  46792. __decorate([
  46793. BABYLON.serialize(),
  46794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46795. ], PBRMaterial.prototype, "roughness", void 0);
  46796. __decorate([
  46797. BABYLON.serializeAsTexture(),
  46798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46799. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46800. __decorate([
  46801. BABYLON.serializeAsTexture(),
  46802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46803. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46804. __decorate([
  46805. BABYLON.serializeAsTexture(),
  46806. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46807. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46808. __decorate([
  46809. BABYLON.serializeAsTexture(),
  46810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46811. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46812. __decorate([
  46813. BABYLON.serializeAsColor3("ambient"),
  46814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46815. ], PBRMaterial.prototype, "ambientColor", void 0);
  46816. __decorate([
  46817. BABYLON.serializeAsColor3("albedo"),
  46818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46819. ], PBRMaterial.prototype, "albedoColor", void 0);
  46820. __decorate([
  46821. BABYLON.serializeAsColor3("reflectivity"),
  46822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46823. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46824. __decorate([
  46825. BABYLON.serializeAsColor3("reflection"),
  46826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46827. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46828. __decorate([
  46829. BABYLON.serializeAsColor3("emissive"),
  46830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46831. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46832. __decorate([
  46833. BABYLON.serialize(),
  46834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46835. ], PBRMaterial.prototype, "microSurface", void 0);
  46836. __decorate([
  46837. BABYLON.serialize(),
  46838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46839. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46840. __decorate([
  46841. BABYLON.serialize(),
  46842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46843. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46844. __decorate([
  46845. BABYLON.serialize(),
  46846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46847. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46848. __decorate([
  46849. BABYLON.serialize(),
  46850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46851. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46852. __decorate([
  46853. BABYLON.serialize(),
  46854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46855. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46856. __decorate([
  46857. BABYLON.serialize(),
  46858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46859. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46860. __decorate([
  46861. BABYLON.serialize(),
  46862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46863. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46864. __decorate([
  46865. BABYLON.serialize(),
  46866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46867. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46868. __decorate([
  46869. BABYLON.serialize(),
  46870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46871. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46872. __decorate([
  46873. BABYLON.serialize(),
  46874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46875. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46876. __decorate([
  46877. BABYLON.serialize(),
  46878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46879. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46880. __decorate([
  46881. BABYLON.serialize(),
  46882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46883. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46884. __decorate([
  46885. BABYLON.serialize(),
  46886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46887. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46888. __decorate([
  46889. BABYLON.serialize(),
  46890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46891. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46892. __decorate([
  46893. BABYLON.serialize(),
  46894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46895. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46896. __decorate([
  46897. BABYLON.serialize(),
  46898. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46899. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46900. __decorate([
  46901. BABYLON.serialize(),
  46902. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46903. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46904. __decorate([
  46905. BABYLON.serialize(),
  46906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46907. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46908. __decorate([
  46909. BABYLON.serialize(),
  46910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46911. ], PBRMaterial.prototype, "useParallax", void 0);
  46912. __decorate([
  46913. BABYLON.serialize(),
  46914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46915. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46916. __decorate([
  46917. BABYLON.serialize(),
  46918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46919. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46920. __decorate([
  46921. BABYLON.serialize(),
  46922. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46923. ], PBRMaterial.prototype, "disableLighting", void 0);
  46924. __decorate([
  46925. BABYLON.serialize(),
  46926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46927. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46928. __decorate([
  46929. BABYLON.serialize(),
  46930. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46931. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46932. __decorate([
  46933. BABYLON.serialize(),
  46934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46935. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46936. __decorate([
  46937. BABYLON.serialize(),
  46938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46939. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46940. __decorate([
  46941. BABYLON.serialize(),
  46942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46943. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46944. __decorate([
  46945. BABYLON.serialize(),
  46946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46947. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46948. __decorate([
  46949. BABYLON.serialize(),
  46950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46951. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46952. __decorate([
  46953. BABYLON.serializeAsTexture(),
  46954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46955. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46956. __decorate([
  46957. BABYLON.serialize(),
  46958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46959. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46960. __decorate([
  46961. BABYLON.serialize(),
  46962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46963. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46964. __decorate([
  46965. BABYLON.serialize(),
  46966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46967. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46968. __decorate([
  46969. BABYLON.serialize(),
  46970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46971. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46972. __decorate([
  46973. BABYLON.serialize(),
  46974. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46975. ], PBRMaterial.prototype, "unlit", void 0);
  46976. return PBRMaterial;
  46977. }(BABYLON.PBRBaseMaterial));
  46978. BABYLON.PBRMaterial = PBRMaterial;
  46979. })(BABYLON || (BABYLON = {}));
  46980. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46981. var BABYLON;
  46982. (function (BABYLON) {
  46983. /**
  46984. * The PBR material of BJS following the metal roughness convention.
  46985. *
  46986. * This fits to the PBR convention in the GLTF definition:
  46987. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46988. */
  46989. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46990. __extends(PBRMetallicRoughnessMaterial, _super);
  46991. /**
  46992. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46993. *
  46994. * @param name The material name
  46995. * @param scene The scene the material will be use in.
  46996. */
  46997. function PBRMetallicRoughnessMaterial(name, scene) {
  46998. var _this = _super.call(this, name, scene) || this;
  46999. _this._useRoughnessFromMetallicTextureAlpha = false;
  47000. _this._useRoughnessFromMetallicTextureGreen = true;
  47001. _this._useMetallnessFromMetallicTextureBlue = true;
  47002. _this.metallic = 1.0;
  47003. _this.roughness = 1.0;
  47004. return _this;
  47005. }
  47006. /**
  47007. * Return the currrent class name of the material.
  47008. */
  47009. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47010. return "PBRMetallicRoughnessMaterial";
  47011. };
  47012. /**
  47013. * Return the active textures of the material.
  47014. */
  47015. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47016. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47017. if (this.baseTexture) {
  47018. activeTextures.push(this.baseTexture);
  47019. }
  47020. if (this.metallicRoughnessTexture) {
  47021. activeTextures.push(this.metallicRoughnessTexture);
  47022. }
  47023. return activeTextures;
  47024. };
  47025. /**
  47026. * Checks to see if a texture is used in the material.
  47027. * @param texture - Base texture to use.
  47028. * @returns - Boolean specifying if a texture is used in the material.
  47029. */
  47030. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47031. if (_super.prototype.hasTexture.call(this, texture)) {
  47032. return true;
  47033. }
  47034. if (this.baseTexture === texture) {
  47035. return true;
  47036. }
  47037. if (this.metallicRoughnessTexture === texture) {
  47038. return true;
  47039. }
  47040. return false;
  47041. };
  47042. /**
  47043. * Makes a duplicate of the current material.
  47044. * @param name - name to use for the new material.
  47045. */
  47046. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47047. var _this = this;
  47048. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47049. clone.id = name;
  47050. clone.name = name;
  47051. return clone;
  47052. };
  47053. /**
  47054. * Serialize the material to a parsable JSON object.
  47055. */
  47056. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47057. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47058. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47059. return serializationObject;
  47060. };
  47061. /**
  47062. * Parses a JSON object correponding to the serialize function.
  47063. */
  47064. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47065. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47066. };
  47067. __decorate([
  47068. BABYLON.serializeAsColor3(),
  47069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47070. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47071. __decorate([
  47072. BABYLON.serializeAsTexture(),
  47073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47074. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47075. __decorate([
  47076. BABYLON.serialize(),
  47077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47078. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47079. __decorate([
  47080. BABYLON.serialize(),
  47081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47082. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47083. __decorate([
  47084. BABYLON.serializeAsTexture(),
  47085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47086. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47087. return PBRMetallicRoughnessMaterial;
  47088. }(BABYLON.PBRBaseSimpleMaterial));
  47089. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47090. })(BABYLON || (BABYLON = {}));
  47091. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47092. var BABYLON;
  47093. (function (BABYLON) {
  47094. /**
  47095. * The PBR material of BJS following the specular glossiness convention.
  47096. *
  47097. * This fits to the PBR convention in the GLTF definition:
  47098. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47099. */
  47100. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47101. __extends(PBRSpecularGlossinessMaterial, _super);
  47102. /**
  47103. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47104. *
  47105. * @param name The material name
  47106. * @param scene The scene the material will be use in.
  47107. */
  47108. function PBRSpecularGlossinessMaterial(name, scene) {
  47109. var _this = _super.call(this, name, scene) || this;
  47110. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47111. return _this;
  47112. }
  47113. /**
  47114. * Return the currrent class name of the material.
  47115. */
  47116. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47117. return "PBRSpecularGlossinessMaterial";
  47118. };
  47119. /**
  47120. * Return the active textures of the material.
  47121. */
  47122. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47123. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47124. if (this.diffuseTexture) {
  47125. activeTextures.push(this.diffuseTexture);
  47126. }
  47127. if (this.specularGlossinessTexture) {
  47128. activeTextures.push(this.specularGlossinessTexture);
  47129. }
  47130. return activeTextures;
  47131. };
  47132. /**
  47133. * Checks to see if a texture is used in the material.
  47134. * @param texture - Base texture to use.
  47135. * @returns - Boolean specifying if a texture is used in the material.
  47136. */
  47137. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47138. if (_super.prototype.hasTexture.call(this, texture)) {
  47139. return true;
  47140. }
  47141. if (this.diffuseTexture === texture) {
  47142. return true;
  47143. }
  47144. if (this.specularGlossinessTexture === texture) {
  47145. return true;
  47146. }
  47147. return false;
  47148. };
  47149. /**
  47150. * Makes a duplicate of the current material.
  47151. * @param name - name to use for the new material.
  47152. */
  47153. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47154. var _this = this;
  47155. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47156. clone.id = name;
  47157. clone.name = name;
  47158. return clone;
  47159. };
  47160. /**
  47161. * Serialize the material to a parsable JSON object.
  47162. */
  47163. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47164. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47165. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47166. return serializationObject;
  47167. };
  47168. /**
  47169. * Parses a JSON object correponding to the serialize function.
  47170. */
  47171. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47172. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47173. };
  47174. __decorate([
  47175. BABYLON.serializeAsColor3("diffuse"),
  47176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47177. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47178. __decorate([
  47179. BABYLON.serializeAsTexture(),
  47180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47181. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47182. __decorate([
  47183. BABYLON.serializeAsColor3("specular"),
  47184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47185. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47186. __decorate([
  47187. BABYLON.serialize(),
  47188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47189. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47190. __decorate([
  47191. BABYLON.serializeAsTexture(),
  47192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47193. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47194. return PBRSpecularGlossinessMaterial;
  47195. }(BABYLON.PBRBaseSimpleMaterial));
  47196. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47197. })(BABYLON || (BABYLON = {}));
  47198. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47199. var BABYLON;
  47200. (function (BABYLON) {
  47201. BABYLON.CameraInputTypes = {};
  47202. var CameraInputsManager = /** @class */ (function () {
  47203. function CameraInputsManager(camera) {
  47204. this.attached = {};
  47205. this.camera = camera;
  47206. this.checkInputs = function () { };
  47207. }
  47208. /**
  47209. * Add an input method to a camera.
  47210. * builtin inputs example: camera.inputs.addGamepad();
  47211. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  47212. * @param input camera input method
  47213. */
  47214. CameraInputsManager.prototype.add = function (input) {
  47215. var type = input.getSimpleName();
  47216. if (this.attached[type]) {
  47217. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47218. return;
  47219. }
  47220. this.attached[type] = input;
  47221. input.camera = this.camera;
  47222. //for checkInputs, we are dynamically creating a function
  47223. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47224. if (input.checkInputs) {
  47225. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47226. }
  47227. if (this.attachedElement) {
  47228. input.attachControl(this.attachedElement);
  47229. }
  47230. };
  47231. /**
  47232. * Remove a specific input method from a camera
  47233. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47234. * @param inputToRemove camera input method
  47235. */
  47236. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47237. for (var cam in this.attached) {
  47238. var input = this.attached[cam];
  47239. if (input === inputToRemove) {
  47240. input.detachControl(this.attachedElement);
  47241. input.camera = null;
  47242. delete this.attached[cam];
  47243. this.rebuildInputCheck();
  47244. }
  47245. }
  47246. };
  47247. CameraInputsManager.prototype.removeByType = function (inputType) {
  47248. for (var cam in this.attached) {
  47249. var input = this.attached[cam];
  47250. if (input.getClassName() === inputType) {
  47251. input.detachControl(this.attachedElement);
  47252. input.camera = null;
  47253. delete this.attached[cam];
  47254. this.rebuildInputCheck();
  47255. }
  47256. }
  47257. };
  47258. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47259. var current = this.checkInputs;
  47260. return function () {
  47261. current();
  47262. fn();
  47263. };
  47264. };
  47265. CameraInputsManager.prototype.attachInput = function (input) {
  47266. if (this.attachedElement) {
  47267. input.attachControl(this.attachedElement, this.noPreventDefault);
  47268. }
  47269. };
  47270. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47271. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47272. if (this.attachedElement) {
  47273. return;
  47274. }
  47275. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47276. this.attachedElement = element;
  47277. this.noPreventDefault = noPreventDefault;
  47278. for (var cam in this.attached) {
  47279. this.attached[cam].attachControl(element, noPreventDefault);
  47280. }
  47281. };
  47282. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47283. if (disconnect === void 0) { disconnect = false; }
  47284. if (this.attachedElement !== element) {
  47285. return;
  47286. }
  47287. for (var cam in this.attached) {
  47288. this.attached[cam].detachControl(element);
  47289. if (disconnect) {
  47290. this.attached[cam].camera = null;
  47291. }
  47292. }
  47293. this.attachedElement = null;
  47294. };
  47295. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47296. this.checkInputs = function () { };
  47297. for (var cam in this.attached) {
  47298. var input = this.attached[cam];
  47299. if (input.checkInputs) {
  47300. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47301. }
  47302. }
  47303. };
  47304. /**
  47305. * Remove all attached input methods from a camera
  47306. */
  47307. CameraInputsManager.prototype.clear = function () {
  47308. if (this.attachedElement) {
  47309. this.detachElement(this.attachedElement, true);
  47310. }
  47311. this.attached = {};
  47312. this.attachedElement = null;
  47313. this.checkInputs = function () { };
  47314. };
  47315. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47316. var inputs = {};
  47317. for (var cam in this.attached) {
  47318. var input = this.attached[cam];
  47319. var res = BABYLON.SerializationHelper.Serialize(input);
  47320. inputs[input.getClassName()] = res;
  47321. }
  47322. serializedCamera.inputsmgr = inputs;
  47323. };
  47324. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47325. var parsedInputs = parsedCamera.inputsmgr;
  47326. if (parsedInputs) {
  47327. this.clear();
  47328. for (var n in parsedInputs) {
  47329. var construct = BABYLON.CameraInputTypes[n];
  47330. if (construct) {
  47331. var parsedinput = parsedInputs[n];
  47332. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47333. this.add(input);
  47334. }
  47335. }
  47336. }
  47337. else {
  47338. //2016-03-08 this part is for managing backward compatibility
  47339. for (var n in this.attached) {
  47340. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47341. if (construct) {
  47342. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47343. this.remove(this.attached[n]);
  47344. this.add(input);
  47345. }
  47346. }
  47347. }
  47348. };
  47349. return CameraInputsManager;
  47350. }());
  47351. BABYLON.CameraInputsManager = CameraInputsManager;
  47352. })(BABYLON || (BABYLON = {}));
  47353. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47354. var BABYLON;
  47355. (function (BABYLON) {
  47356. var TargetCamera = /** @class */ (function (_super) {
  47357. __extends(TargetCamera, _super);
  47358. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47359. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47360. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47361. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47362. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47363. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47364. _this.speed = 2.0;
  47365. _this.noRotationConstraint = false;
  47366. _this.lockedTarget = null;
  47367. _this._currentTarget = BABYLON.Vector3.Zero();
  47368. _this._viewMatrix = BABYLON.Matrix.Zero();
  47369. _this._camMatrix = BABYLON.Matrix.Zero();
  47370. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47371. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47372. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47373. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47374. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47375. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47376. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47377. return _this;
  47378. }
  47379. TargetCamera.prototype.getFrontPosition = function (distance) {
  47380. this.getWorldMatrix();
  47381. var direction = this.getTarget().subtract(this.position);
  47382. direction.normalize();
  47383. direction.scaleInPlace(distance);
  47384. return this.globalPosition.add(direction);
  47385. };
  47386. TargetCamera.prototype._getLockedTargetPosition = function () {
  47387. if (!this.lockedTarget) {
  47388. return null;
  47389. }
  47390. if (this.lockedTarget.absolutePosition) {
  47391. this.lockedTarget.computeWorldMatrix();
  47392. }
  47393. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47394. };
  47395. TargetCamera.prototype.storeState = function () {
  47396. this._storedPosition = this.position.clone();
  47397. this._storedRotation = this.rotation.clone();
  47398. if (this.rotationQuaternion) {
  47399. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47400. }
  47401. return _super.prototype.storeState.call(this);
  47402. };
  47403. /**
  47404. * Restored camera state. You must call storeState() first
  47405. */
  47406. TargetCamera.prototype._restoreStateValues = function () {
  47407. if (!_super.prototype._restoreStateValues.call(this)) {
  47408. return false;
  47409. }
  47410. this.position = this._storedPosition.clone();
  47411. this.rotation = this._storedRotation.clone();
  47412. if (this.rotationQuaternion) {
  47413. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47414. }
  47415. this.cameraDirection.copyFromFloats(0, 0, 0);
  47416. this.cameraRotation.copyFromFloats(0, 0);
  47417. return true;
  47418. };
  47419. // Cache
  47420. TargetCamera.prototype._initCache = function () {
  47421. _super.prototype._initCache.call(this);
  47422. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47423. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47424. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47425. };
  47426. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47427. if (!ignoreParentClass) {
  47428. _super.prototype._updateCache.call(this);
  47429. }
  47430. var lockedTargetPosition = this._getLockedTargetPosition();
  47431. if (!lockedTargetPosition) {
  47432. this._cache.lockedTarget = null;
  47433. }
  47434. else {
  47435. if (!this._cache.lockedTarget) {
  47436. this._cache.lockedTarget = lockedTargetPosition.clone();
  47437. }
  47438. else {
  47439. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47440. }
  47441. }
  47442. this._cache.rotation.copyFrom(this.rotation);
  47443. if (this.rotationQuaternion)
  47444. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47445. };
  47446. // Synchronized
  47447. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47448. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47449. return false;
  47450. }
  47451. var lockedTargetPosition = this._getLockedTargetPosition();
  47452. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47453. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47454. };
  47455. // Methods
  47456. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47457. var engine = this.getEngine();
  47458. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47459. };
  47460. // Target
  47461. TargetCamera.prototype.setTarget = function (target) {
  47462. this.upVector.normalize();
  47463. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47464. this._camMatrix.invert();
  47465. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47466. var vDir = target.subtract(this.position);
  47467. if (vDir.x >= 0.0) {
  47468. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47469. }
  47470. else {
  47471. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47472. }
  47473. this.rotation.z = 0;
  47474. if (isNaN(this.rotation.x)) {
  47475. this.rotation.x = 0;
  47476. }
  47477. if (isNaN(this.rotation.y)) {
  47478. this.rotation.y = 0;
  47479. }
  47480. if (isNaN(this.rotation.z)) {
  47481. this.rotation.z = 0;
  47482. }
  47483. if (this.rotationQuaternion) {
  47484. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47485. }
  47486. };
  47487. /**
  47488. * Return the current target position of the camera. This value is expressed in local space.
  47489. */
  47490. TargetCamera.prototype.getTarget = function () {
  47491. return this._currentTarget;
  47492. };
  47493. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47494. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47495. };
  47496. TargetCamera.prototype._updatePosition = function () {
  47497. if (this.parent) {
  47498. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47499. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47500. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47501. return;
  47502. }
  47503. this.position.addInPlace(this.cameraDirection);
  47504. };
  47505. TargetCamera.prototype._checkInputs = function () {
  47506. var needToMove = this._decideIfNeedsToMove();
  47507. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47508. // Move
  47509. if (needToMove) {
  47510. this._updatePosition();
  47511. }
  47512. // Rotate
  47513. if (needToRotate) {
  47514. this.rotation.x += this.cameraRotation.x;
  47515. this.rotation.y += this.cameraRotation.y;
  47516. //rotate, if quaternion is set and rotation was used
  47517. if (this.rotationQuaternion) {
  47518. var len = this.rotation.lengthSquared();
  47519. if (len) {
  47520. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47521. }
  47522. }
  47523. if (!this.noRotationConstraint) {
  47524. var limit = (Math.PI / 2) * 0.95;
  47525. if (this.rotation.x > limit)
  47526. this.rotation.x = limit;
  47527. if (this.rotation.x < -limit)
  47528. this.rotation.x = -limit;
  47529. }
  47530. }
  47531. // Inertia
  47532. if (needToMove) {
  47533. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47534. this.cameraDirection.x = 0;
  47535. }
  47536. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47537. this.cameraDirection.y = 0;
  47538. }
  47539. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47540. this.cameraDirection.z = 0;
  47541. }
  47542. this.cameraDirection.scaleInPlace(this.inertia);
  47543. }
  47544. if (needToRotate) {
  47545. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47546. this.cameraRotation.x = 0;
  47547. }
  47548. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47549. this.cameraRotation.y = 0;
  47550. }
  47551. this.cameraRotation.scaleInPlace(this.inertia);
  47552. }
  47553. _super.prototype._checkInputs.call(this);
  47554. };
  47555. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47556. if (this.rotationQuaternion) {
  47557. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47558. }
  47559. else {
  47560. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47561. }
  47562. //update the up vector!
  47563. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47564. };
  47565. TargetCamera.prototype._getViewMatrix = function () {
  47566. if (this.lockedTarget) {
  47567. this.setTarget(this._getLockedTargetPosition());
  47568. }
  47569. // Compute
  47570. this._updateCameraRotationMatrix();
  47571. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47572. // Computing target and final matrix
  47573. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47574. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47575. return this._viewMatrix;
  47576. };
  47577. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47578. if (this.parent) {
  47579. var parentWorldMatrix = this.parent.getWorldMatrix();
  47580. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47581. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47582. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47583. this._markSyncedWithParent();
  47584. }
  47585. else {
  47586. this._globalPosition.copyFrom(this.position);
  47587. this._globalCurrentTarget.copyFrom(target);
  47588. this._globalCurrentUpVector.copyFrom(up);
  47589. }
  47590. if (this.getScene().useRightHandedSystem) {
  47591. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47592. }
  47593. else {
  47594. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47595. }
  47596. };
  47597. /**
  47598. * @override
  47599. * Override Camera.createRigCamera
  47600. */
  47601. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47602. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47603. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47604. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47605. if (!this.rotationQuaternion) {
  47606. this.rotationQuaternion = new BABYLON.Quaternion();
  47607. }
  47608. rigCamera._cameraRigParams = {};
  47609. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47610. }
  47611. return rigCamera;
  47612. }
  47613. return null;
  47614. };
  47615. /**
  47616. * @override
  47617. * Override Camera._updateRigCameras
  47618. */
  47619. TargetCamera.prototype._updateRigCameras = function () {
  47620. var camLeft = this._rigCameras[0];
  47621. var camRight = this._rigCameras[1];
  47622. switch (this.cameraRigMode) {
  47623. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47624. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47626. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47627. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47628. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47629. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47630. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47631. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47632. camLeft.setTarget(this.getTarget());
  47633. camRight.setTarget(this.getTarget());
  47634. break;
  47635. case BABYLON.Camera.RIG_MODE_VR:
  47636. if (camLeft.rotationQuaternion) {
  47637. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47638. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47639. }
  47640. else {
  47641. camLeft.rotation.copyFrom(this.rotation);
  47642. camRight.rotation.copyFrom(this.rotation);
  47643. }
  47644. camLeft.position.copyFrom(this.position);
  47645. camRight.position.copyFrom(this.position);
  47646. break;
  47647. }
  47648. _super.prototype._updateRigCameras.call(this);
  47649. };
  47650. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47651. if (!this._rigCamTransformMatrix) {
  47652. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47653. }
  47654. var target = this.getTarget();
  47655. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47656. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47657. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47658. };
  47659. TargetCamera.prototype.getClassName = function () {
  47660. return "TargetCamera";
  47661. };
  47662. __decorate([
  47663. BABYLON.serializeAsVector3()
  47664. ], TargetCamera.prototype, "rotation", void 0);
  47665. __decorate([
  47666. BABYLON.serialize()
  47667. ], TargetCamera.prototype, "speed", void 0);
  47668. __decorate([
  47669. BABYLON.serializeAsMeshReference("lockedTargetId")
  47670. ], TargetCamera.prototype, "lockedTarget", void 0);
  47671. return TargetCamera;
  47672. }(BABYLON.Camera));
  47673. BABYLON.TargetCamera = TargetCamera;
  47674. })(BABYLON || (BABYLON = {}));
  47675. //# sourceMappingURL=babylon.targetCamera.js.map
  47676. var BABYLON;
  47677. (function (BABYLON) {
  47678. var FreeCameraMouseInput = /** @class */ (function () {
  47679. function FreeCameraMouseInput(touchEnabled) {
  47680. if (touchEnabled === void 0) { touchEnabled = true; }
  47681. this.touchEnabled = touchEnabled;
  47682. this.buttons = [0, 1, 2];
  47683. this.angularSensibility = 2000.0;
  47684. this.previousPosition = null;
  47685. }
  47686. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47687. var _this = this;
  47688. var engine = this.camera.getEngine();
  47689. if (!this._pointerInput) {
  47690. this._pointerInput = function (p, s) {
  47691. var evt = p.event;
  47692. if (engine.isInVRExclusivePointerMode) {
  47693. return;
  47694. }
  47695. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47696. return;
  47697. }
  47698. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47699. return;
  47700. }
  47701. var srcElement = (evt.srcElement || evt.target);
  47702. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47703. try {
  47704. srcElement.setPointerCapture(evt.pointerId);
  47705. }
  47706. catch (e) {
  47707. //Nothing to do with the error. Execution will continue.
  47708. }
  47709. _this.previousPosition = {
  47710. x: evt.clientX,
  47711. y: evt.clientY
  47712. };
  47713. if (!noPreventDefault) {
  47714. evt.preventDefault();
  47715. element.focus();
  47716. }
  47717. }
  47718. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47719. try {
  47720. srcElement.releasePointerCapture(evt.pointerId);
  47721. }
  47722. catch (e) {
  47723. //Nothing to do with the error.
  47724. }
  47725. _this.previousPosition = null;
  47726. if (!noPreventDefault) {
  47727. evt.preventDefault();
  47728. }
  47729. }
  47730. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47731. if (!_this.previousPosition || engine.isPointerLock) {
  47732. return;
  47733. }
  47734. var offsetX = evt.clientX - _this.previousPosition.x;
  47735. if (_this.camera.getScene().useRightHandedSystem)
  47736. offsetX *= -1;
  47737. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47738. offsetX *= -1;
  47739. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47740. var offsetY = evt.clientY - _this.previousPosition.y;
  47741. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47742. _this.previousPosition = {
  47743. x: evt.clientX,
  47744. y: evt.clientY
  47745. };
  47746. if (!noPreventDefault) {
  47747. evt.preventDefault();
  47748. }
  47749. }
  47750. };
  47751. }
  47752. this._onMouseMove = function (evt) {
  47753. if (!engine.isPointerLock) {
  47754. return;
  47755. }
  47756. if (engine.isInVRExclusivePointerMode) {
  47757. return;
  47758. }
  47759. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47760. if (_this.camera.getScene().useRightHandedSystem)
  47761. offsetX *= -1;
  47762. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47763. offsetX *= -1;
  47764. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47765. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47766. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47767. _this.previousPosition = null;
  47768. if (!noPreventDefault) {
  47769. evt.preventDefault();
  47770. }
  47771. };
  47772. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47773. element.addEventListener("mousemove", this._onMouseMove, false);
  47774. };
  47775. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47776. if (this._observer && element) {
  47777. this.camera.getScene().onPointerObservable.remove(this._observer);
  47778. if (this._onMouseMove) {
  47779. element.removeEventListener("mousemove", this._onMouseMove);
  47780. }
  47781. this._observer = null;
  47782. this._onMouseMove = null;
  47783. this.previousPosition = null;
  47784. }
  47785. };
  47786. FreeCameraMouseInput.prototype.getClassName = function () {
  47787. return "FreeCameraMouseInput";
  47788. };
  47789. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47790. return "mouse";
  47791. };
  47792. __decorate([
  47793. BABYLON.serialize()
  47794. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47795. __decorate([
  47796. BABYLON.serialize()
  47797. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47798. return FreeCameraMouseInput;
  47799. }());
  47800. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47801. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47802. })(BABYLON || (BABYLON = {}));
  47803. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47804. var BABYLON;
  47805. (function (BABYLON) {
  47806. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47807. function FreeCameraKeyboardMoveInput() {
  47808. this._keys = new Array();
  47809. this.keysUp = [38];
  47810. this.keysDown = [40];
  47811. this.keysLeft = [37];
  47812. this.keysRight = [39];
  47813. }
  47814. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47815. var _this = this;
  47816. if (this._onCanvasBlurObserver) {
  47817. return;
  47818. }
  47819. this._scene = this.camera.getScene();
  47820. this._engine = this._scene.getEngine();
  47821. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47822. _this._keys = [];
  47823. });
  47824. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47825. var evt = info.event;
  47826. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47827. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47828. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47829. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47830. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47831. var index = _this._keys.indexOf(evt.keyCode);
  47832. if (index === -1) {
  47833. _this._keys.push(evt.keyCode);
  47834. }
  47835. if (!noPreventDefault) {
  47836. evt.preventDefault();
  47837. }
  47838. }
  47839. }
  47840. else {
  47841. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47842. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47843. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47844. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47845. var index = _this._keys.indexOf(evt.keyCode);
  47846. if (index >= 0) {
  47847. _this._keys.splice(index, 1);
  47848. }
  47849. if (!noPreventDefault) {
  47850. evt.preventDefault();
  47851. }
  47852. }
  47853. }
  47854. });
  47855. };
  47856. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47857. if (this._scene) {
  47858. if (this._onKeyboardObserver) {
  47859. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47860. }
  47861. if (this._onCanvasBlurObserver) {
  47862. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47863. }
  47864. this._onKeyboardObserver = null;
  47865. this._onCanvasBlurObserver = null;
  47866. }
  47867. this._keys = [];
  47868. };
  47869. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47870. if (this._onKeyboardObserver) {
  47871. var camera = this.camera;
  47872. // Keyboard
  47873. for (var index = 0; index < this._keys.length; index++) {
  47874. var keyCode = this._keys[index];
  47875. var speed = camera._computeLocalCameraSpeed();
  47876. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47877. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47878. }
  47879. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47880. camera._localDirection.copyFromFloats(0, 0, speed);
  47881. }
  47882. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47883. camera._localDirection.copyFromFloats(speed, 0, 0);
  47884. }
  47885. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47886. camera._localDirection.copyFromFloats(0, 0, -speed);
  47887. }
  47888. if (camera.getScene().useRightHandedSystem) {
  47889. camera._localDirection.z *= -1;
  47890. }
  47891. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47892. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47893. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47894. }
  47895. }
  47896. };
  47897. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47898. return "FreeCameraKeyboardMoveInput";
  47899. };
  47900. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47901. this._keys = [];
  47902. };
  47903. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47904. return "keyboard";
  47905. };
  47906. __decorate([
  47907. BABYLON.serialize()
  47908. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47909. __decorate([
  47910. BABYLON.serialize()
  47911. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47912. __decorate([
  47913. BABYLON.serialize()
  47914. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47915. __decorate([
  47916. BABYLON.serialize()
  47917. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47918. return FreeCameraKeyboardMoveInput;
  47919. }());
  47920. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47921. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47922. })(BABYLON || (BABYLON = {}));
  47923. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47924. var BABYLON;
  47925. (function (BABYLON) {
  47926. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47927. __extends(FreeCameraInputsManager, _super);
  47928. function FreeCameraInputsManager(camera) {
  47929. return _super.call(this, camera) || this;
  47930. }
  47931. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47932. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47933. return this;
  47934. };
  47935. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47936. if (touchEnabled === void 0) { touchEnabled = true; }
  47937. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47938. return this;
  47939. };
  47940. FreeCameraInputsManager.prototype.addGamepad = function () {
  47941. this.add(new BABYLON.FreeCameraGamepadInput());
  47942. return this;
  47943. };
  47944. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47945. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47946. return this;
  47947. };
  47948. FreeCameraInputsManager.prototype.addTouch = function () {
  47949. this.add(new BABYLON.FreeCameraTouchInput());
  47950. return this;
  47951. };
  47952. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47953. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47954. return this;
  47955. };
  47956. return FreeCameraInputsManager;
  47957. }(BABYLON.CameraInputsManager));
  47958. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47959. })(BABYLON || (BABYLON = {}));
  47960. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47961. var BABYLON;
  47962. (function (BABYLON) {
  47963. var FreeCamera = /** @class */ (function (_super) {
  47964. __extends(FreeCamera, _super);
  47965. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47966. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47967. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47968. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47969. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47970. _this.checkCollisions = false;
  47971. _this.applyGravity = false;
  47972. _this._needMoveForGravity = false;
  47973. _this._oldPosition = BABYLON.Vector3.Zero();
  47974. _this._diffPosition = BABYLON.Vector3.Zero();
  47975. _this._newPosition = BABYLON.Vector3.Zero();
  47976. // Collisions
  47977. _this._collisionMask = -1;
  47978. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47979. if (collidedMesh === void 0) { collidedMesh = null; }
  47980. //TODO move this to the collision coordinator!
  47981. if (_this.getScene().workerCollisions)
  47982. newPosition.multiplyInPlace(_this._collider._radius);
  47983. var updatePosition = function (newPos) {
  47984. _this._newPosition.copyFrom(newPos);
  47985. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47986. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47987. _this.position.addInPlace(_this._diffPosition);
  47988. if (_this.onCollide && collidedMesh) {
  47989. _this.onCollide(collidedMesh);
  47990. }
  47991. }
  47992. };
  47993. updatePosition(newPosition);
  47994. };
  47995. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47996. _this.inputs.addKeyboard().addMouse();
  47997. return _this;
  47998. }
  47999. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48000. //-- begin properties for backward compatibility for inputs
  48001. /**
  48002. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48003. * Higher values reduce sensitivity.
  48004. */
  48005. get: function () {
  48006. var mouse = this.inputs.attached["mouse"];
  48007. if (mouse)
  48008. return mouse.angularSensibility;
  48009. return 0;
  48010. },
  48011. /**
  48012. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48013. * Higher values reduce sensitivity.
  48014. */
  48015. set: function (value) {
  48016. var mouse = this.inputs.attached["mouse"];
  48017. if (mouse)
  48018. mouse.angularSensibility = value;
  48019. },
  48020. enumerable: true,
  48021. configurable: true
  48022. });
  48023. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48024. get: function () {
  48025. var keyboard = this.inputs.attached["keyboard"];
  48026. if (keyboard)
  48027. return keyboard.keysUp;
  48028. return [];
  48029. },
  48030. set: function (value) {
  48031. var keyboard = this.inputs.attached["keyboard"];
  48032. if (keyboard)
  48033. keyboard.keysUp = value;
  48034. },
  48035. enumerable: true,
  48036. configurable: true
  48037. });
  48038. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48039. get: function () {
  48040. var keyboard = this.inputs.attached["keyboard"];
  48041. if (keyboard)
  48042. return keyboard.keysDown;
  48043. return [];
  48044. },
  48045. set: function (value) {
  48046. var keyboard = this.inputs.attached["keyboard"];
  48047. if (keyboard)
  48048. keyboard.keysDown = value;
  48049. },
  48050. enumerable: true,
  48051. configurable: true
  48052. });
  48053. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48054. get: function () {
  48055. var keyboard = this.inputs.attached["keyboard"];
  48056. if (keyboard)
  48057. return keyboard.keysLeft;
  48058. return [];
  48059. },
  48060. set: function (value) {
  48061. var keyboard = this.inputs.attached["keyboard"];
  48062. if (keyboard)
  48063. keyboard.keysLeft = value;
  48064. },
  48065. enumerable: true,
  48066. configurable: true
  48067. });
  48068. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48069. get: function () {
  48070. var keyboard = this.inputs.attached["keyboard"];
  48071. if (keyboard)
  48072. return keyboard.keysRight;
  48073. return [];
  48074. },
  48075. set: function (value) {
  48076. var keyboard = this.inputs.attached["keyboard"];
  48077. if (keyboard)
  48078. keyboard.keysRight = value;
  48079. },
  48080. enumerable: true,
  48081. configurable: true
  48082. });
  48083. // Controls
  48084. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48085. this.inputs.attachElement(element, noPreventDefault);
  48086. };
  48087. FreeCamera.prototype.detachControl = function (element) {
  48088. this.inputs.detachElement(element);
  48089. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48090. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48091. };
  48092. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48093. get: function () {
  48094. return this._collisionMask;
  48095. },
  48096. set: function (mask) {
  48097. this._collisionMask = !isNaN(mask) ? mask : -1;
  48098. },
  48099. enumerable: true,
  48100. configurable: true
  48101. });
  48102. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48103. var globalPosition;
  48104. if (this.parent) {
  48105. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48106. }
  48107. else {
  48108. globalPosition = this.position;
  48109. }
  48110. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48111. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48112. if (!this._collider) {
  48113. this._collider = new BABYLON.Collider();
  48114. }
  48115. this._collider._radius = this.ellipsoid;
  48116. this._collider.collisionMask = this._collisionMask;
  48117. //no need for clone, as long as gravity is not on.
  48118. var actualDisplacement = displacement;
  48119. //add gravity to the direction to prevent the dual-collision checking
  48120. if (this.applyGravity) {
  48121. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48122. actualDisplacement = displacement.add(this.getScene().gravity);
  48123. }
  48124. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48125. };
  48126. FreeCamera.prototype._checkInputs = function () {
  48127. if (!this._localDirection) {
  48128. this._localDirection = BABYLON.Vector3.Zero();
  48129. this._transformedDirection = BABYLON.Vector3.Zero();
  48130. }
  48131. this.inputs.checkInputs();
  48132. _super.prototype._checkInputs.call(this);
  48133. };
  48134. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48135. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48136. };
  48137. FreeCamera.prototype._updatePosition = function () {
  48138. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48139. this._collideWithWorld(this.cameraDirection);
  48140. }
  48141. else {
  48142. _super.prototype._updatePosition.call(this);
  48143. }
  48144. };
  48145. FreeCamera.prototype.dispose = function () {
  48146. this.inputs.clear();
  48147. _super.prototype.dispose.call(this);
  48148. };
  48149. FreeCamera.prototype.getClassName = function () {
  48150. return "FreeCamera";
  48151. };
  48152. __decorate([
  48153. BABYLON.serializeAsVector3()
  48154. ], FreeCamera.prototype, "ellipsoid", void 0);
  48155. __decorate([
  48156. BABYLON.serializeAsVector3()
  48157. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48158. __decorate([
  48159. BABYLON.serialize()
  48160. ], FreeCamera.prototype, "checkCollisions", void 0);
  48161. __decorate([
  48162. BABYLON.serialize()
  48163. ], FreeCamera.prototype, "applyGravity", void 0);
  48164. return FreeCamera;
  48165. }(BABYLON.TargetCamera));
  48166. BABYLON.FreeCamera = FreeCamera;
  48167. })(BABYLON || (BABYLON = {}));
  48168. //# sourceMappingURL=babylon.freeCamera.js.map
  48169. var BABYLON;
  48170. (function (BABYLON) {
  48171. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48172. function ArcRotateCameraKeyboardMoveInput() {
  48173. this._keys = new Array();
  48174. this.keysUp = [38];
  48175. this.keysDown = [40];
  48176. this.keysLeft = [37];
  48177. this.keysRight = [39];
  48178. this.keysReset = [220];
  48179. this.panningSensibility = 50.0;
  48180. this.zoomingSensibility = 25.0;
  48181. this.useAltToZoom = true;
  48182. }
  48183. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48184. var _this = this;
  48185. if (this._onCanvasBlurObserver) {
  48186. return;
  48187. }
  48188. this._scene = this.camera.getScene();
  48189. this._engine = this._scene.getEngine();
  48190. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48191. _this._keys = [];
  48192. });
  48193. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48194. var evt = info.event;
  48195. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48196. _this._ctrlPressed = evt.ctrlKey;
  48197. _this._altPressed = evt.altKey;
  48198. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48199. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48200. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48201. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48202. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48203. var index = _this._keys.indexOf(evt.keyCode);
  48204. if (index === -1) {
  48205. _this._keys.push(evt.keyCode);
  48206. }
  48207. if (evt.preventDefault) {
  48208. if (!noPreventDefault) {
  48209. evt.preventDefault();
  48210. }
  48211. }
  48212. }
  48213. }
  48214. else {
  48215. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48216. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48217. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48218. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48219. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48220. var index = _this._keys.indexOf(evt.keyCode);
  48221. if (index >= 0) {
  48222. _this._keys.splice(index, 1);
  48223. }
  48224. if (evt.preventDefault) {
  48225. if (!noPreventDefault) {
  48226. evt.preventDefault();
  48227. }
  48228. }
  48229. }
  48230. }
  48231. });
  48232. };
  48233. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48234. if (this._scene) {
  48235. if (this._onKeyboardObserver) {
  48236. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48237. }
  48238. if (this._onCanvasBlurObserver) {
  48239. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48240. }
  48241. this._onKeyboardObserver = null;
  48242. this._onCanvasBlurObserver = null;
  48243. }
  48244. this._keys = [];
  48245. };
  48246. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48247. if (this._onKeyboardObserver) {
  48248. var camera = this.camera;
  48249. for (var index = 0; index < this._keys.length; index++) {
  48250. var keyCode = this._keys[index];
  48251. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48252. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48253. camera.inertialPanningX -= 1 / this.panningSensibility;
  48254. }
  48255. else {
  48256. camera.inertialAlphaOffset -= 0.01;
  48257. }
  48258. }
  48259. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48260. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48261. camera.inertialPanningY += 1 / this.panningSensibility;
  48262. }
  48263. else if (this._altPressed && this.useAltToZoom) {
  48264. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  48265. }
  48266. else {
  48267. camera.inertialBetaOffset -= 0.01;
  48268. }
  48269. }
  48270. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48271. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48272. camera.inertialPanningX += 1 / this.panningSensibility;
  48273. }
  48274. else {
  48275. camera.inertialAlphaOffset += 0.01;
  48276. }
  48277. }
  48278. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48279. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  48280. camera.inertialPanningY -= 1 / this.panningSensibility;
  48281. }
  48282. else if (this._altPressed && this.useAltToZoom) {
  48283. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  48284. }
  48285. else {
  48286. camera.inertialBetaOffset += 0.01;
  48287. }
  48288. }
  48289. else if (this.keysReset.indexOf(keyCode) !== -1) {
  48290. camera.restoreState();
  48291. }
  48292. }
  48293. }
  48294. };
  48295. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48296. return "ArcRotateCameraKeyboardMoveInput";
  48297. };
  48298. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48299. return "keyboard";
  48300. };
  48301. __decorate([
  48302. BABYLON.serialize()
  48303. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48304. __decorate([
  48305. BABYLON.serialize()
  48306. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48307. __decorate([
  48308. BABYLON.serialize()
  48309. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48310. __decorate([
  48311. BABYLON.serialize()
  48312. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48313. __decorate([
  48314. BABYLON.serialize()
  48315. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48316. __decorate([
  48317. BABYLON.serialize()
  48318. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48319. __decorate([
  48320. BABYLON.serialize()
  48321. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48322. __decorate([
  48323. BABYLON.serialize()
  48324. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48325. return ArcRotateCameraKeyboardMoveInput;
  48326. }());
  48327. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48328. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48329. })(BABYLON || (BABYLON = {}));
  48330. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48331. var BABYLON;
  48332. (function (BABYLON) {
  48333. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48334. function ArcRotateCameraMouseWheelInput() {
  48335. this.wheelPrecision = 3.0;
  48336. /**
  48337. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48338. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48339. */
  48340. this.wheelDeltaPercentage = 0;
  48341. }
  48342. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48343. var _this = this;
  48344. this._wheel = function (p, s) {
  48345. //sanity check - this should be a PointerWheel event.
  48346. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48347. return;
  48348. var event = p.event;
  48349. var delta = 0;
  48350. if (event.wheelDelta) {
  48351. if (_this.wheelDeltaPercentage) {
  48352. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48353. if (event.wheelDelta > 0) {
  48354. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48355. }
  48356. else {
  48357. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48358. }
  48359. }
  48360. else {
  48361. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48362. }
  48363. }
  48364. else if (event.detail) {
  48365. delta = -event.detail / _this.wheelPrecision;
  48366. }
  48367. if (delta)
  48368. _this.camera.inertialRadiusOffset += delta;
  48369. if (event.preventDefault) {
  48370. if (!noPreventDefault) {
  48371. event.preventDefault();
  48372. }
  48373. }
  48374. };
  48375. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48376. };
  48377. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48378. if (this._observer && element) {
  48379. this.camera.getScene().onPointerObservable.remove(this._observer);
  48380. this._observer = null;
  48381. this._wheel = null;
  48382. }
  48383. };
  48384. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48385. return "ArcRotateCameraMouseWheelInput";
  48386. };
  48387. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48388. return "mousewheel";
  48389. };
  48390. __decorate([
  48391. BABYLON.serialize()
  48392. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48393. __decorate([
  48394. BABYLON.serialize()
  48395. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48396. return ArcRotateCameraMouseWheelInput;
  48397. }());
  48398. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48399. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48400. })(BABYLON || (BABYLON = {}));
  48401. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48402. var BABYLON;
  48403. (function (BABYLON) {
  48404. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48405. function ArcRotateCameraPointersInput() {
  48406. this.buttons = [0, 1, 2];
  48407. this.angularSensibilityX = 1000.0;
  48408. this.angularSensibilityY = 1000.0;
  48409. this.pinchPrecision = 12.0;
  48410. /**
  48411. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48412. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48413. */
  48414. this.pinchDeltaPercentage = 0;
  48415. this.panningSensibility = 1000.0;
  48416. this.multiTouchPanning = true;
  48417. this.multiTouchPanAndZoom = true;
  48418. this._isPanClick = false;
  48419. this.pinchInwards = true;
  48420. }
  48421. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48422. var _this = this;
  48423. var engine = this.camera.getEngine();
  48424. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48425. var pointA = null;
  48426. var pointB = null;
  48427. var previousPinchSquaredDistance = 0;
  48428. var initialDistance = 0;
  48429. var twoFingerActivityCount = 0;
  48430. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48431. this._pointerInput = function (p, s) {
  48432. var evt = p.event;
  48433. var isTouch = p.event.pointerType === "touch";
  48434. if (engine.isInVRExclusivePointerMode) {
  48435. return;
  48436. }
  48437. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48438. return;
  48439. }
  48440. var srcElement = (evt.srcElement || evt.target);
  48441. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48442. try {
  48443. srcElement.setPointerCapture(evt.pointerId);
  48444. }
  48445. catch (e) {
  48446. //Nothing to do with the error. Execution will continue.
  48447. }
  48448. // Manage panning with pan button click
  48449. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48450. // manage pointers
  48451. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48452. if (pointA === null) {
  48453. pointA = cacheSoloPointer;
  48454. }
  48455. else if (pointB === null) {
  48456. pointB = cacheSoloPointer;
  48457. }
  48458. if (!noPreventDefault) {
  48459. evt.preventDefault();
  48460. element.focus();
  48461. }
  48462. }
  48463. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48464. _this.camera.restoreState();
  48465. }
  48466. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48467. try {
  48468. srcElement.releasePointerCapture(evt.pointerId);
  48469. }
  48470. catch (e) {
  48471. //Nothing to do with the error.
  48472. }
  48473. cacheSoloPointer = null;
  48474. previousPinchSquaredDistance = 0;
  48475. previousMultiTouchPanPosition.isPaning = false;
  48476. previousMultiTouchPanPosition.isPinching = false;
  48477. twoFingerActivityCount = 0;
  48478. initialDistance = 0;
  48479. if (!isTouch) {
  48480. pointB = null; // Mouse and pen are mono pointer
  48481. }
  48482. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48483. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48484. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48485. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48486. if (engine._badOS) {
  48487. pointA = pointB = null;
  48488. }
  48489. else {
  48490. //only remove the impacted pointer in case of multitouch allowing on most
  48491. //platforms switching from rotate to zoom and pan seamlessly.
  48492. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48493. pointA = pointB;
  48494. pointB = null;
  48495. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48496. }
  48497. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48498. pointB = null;
  48499. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48500. }
  48501. else {
  48502. pointA = pointB = null;
  48503. }
  48504. }
  48505. if (!noPreventDefault) {
  48506. evt.preventDefault();
  48507. }
  48508. }
  48509. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48510. if (!noPreventDefault) {
  48511. evt.preventDefault();
  48512. }
  48513. // One button down
  48514. if (pointA && pointB === null && cacheSoloPointer) {
  48515. if (_this.panningSensibility !== 0 &&
  48516. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48517. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48518. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48519. }
  48520. else {
  48521. var offsetX = evt.clientX - cacheSoloPointer.x;
  48522. var offsetY = evt.clientY - cacheSoloPointer.y;
  48523. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48524. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48525. }
  48526. cacheSoloPointer.x = evt.clientX;
  48527. cacheSoloPointer.y = evt.clientY;
  48528. }
  48529. // Two buttons down: pinch/pan
  48530. else if (pointA && pointB) {
  48531. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48532. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48533. ed.x = evt.clientX;
  48534. ed.y = evt.clientY;
  48535. var direction = _this.pinchInwards ? 1 : -1;
  48536. var distX = pointA.x - pointB.x;
  48537. var distY = pointA.y - pointB.y;
  48538. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48539. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48540. if (previousPinchSquaredDistance === 0) {
  48541. initialDistance = pinchDistance;
  48542. previousPinchSquaredDistance = pinchSquaredDistance;
  48543. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48544. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48545. return;
  48546. }
  48547. if (_this.multiTouchPanAndZoom) {
  48548. if (_this.pinchDeltaPercentage) {
  48549. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48550. }
  48551. else {
  48552. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48553. (_this.pinchPrecision *
  48554. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48555. direction);
  48556. }
  48557. if (_this.panningSensibility !== 0) {
  48558. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48559. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48560. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48561. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48562. previousMultiTouchPanPosition.x = pointersCenterX;
  48563. previousMultiTouchPanPosition.y = pointersCenterY;
  48564. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48565. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48566. }
  48567. }
  48568. else {
  48569. twoFingerActivityCount++;
  48570. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48571. if (_this.pinchDeltaPercentage) {
  48572. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48573. }
  48574. else {
  48575. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48576. (_this.pinchPrecision *
  48577. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48578. direction);
  48579. }
  48580. previousMultiTouchPanPosition.isPaning = false;
  48581. previousMultiTouchPanPosition.isPinching = true;
  48582. }
  48583. else {
  48584. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48585. if (!previousMultiTouchPanPosition.isPaning) {
  48586. previousMultiTouchPanPosition.isPaning = true;
  48587. previousMultiTouchPanPosition.isPinching = false;
  48588. previousMultiTouchPanPosition.x = ed.x;
  48589. previousMultiTouchPanPosition.y = ed.y;
  48590. return;
  48591. }
  48592. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48593. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48594. }
  48595. }
  48596. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48597. previousMultiTouchPanPosition.x = ed.x;
  48598. previousMultiTouchPanPosition.y = ed.y;
  48599. }
  48600. }
  48601. previousPinchSquaredDistance = pinchSquaredDistance;
  48602. }
  48603. }
  48604. };
  48605. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48606. this._onContextMenu = function (evt) {
  48607. evt.preventDefault();
  48608. };
  48609. if (!this.camera._useCtrlForPanning) {
  48610. element.addEventListener("contextmenu", this._onContextMenu, false);
  48611. }
  48612. this._onLostFocus = function () {
  48613. //this._keys = [];
  48614. pointA = pointB = null;
  48615. previousPinchSquaredDistance = 0;
  48616. previousMultiTouchPanPosition.isPaning = false;
  48617. previousMultiTouchPanPosition.isPinching = false;
  48618. twoFingerActivityCount = 0;
  48619. cacheSoloPointer = null;
  48620. initialDistance = 0;
  48621. };
  48622. this._onMouseMove = function (evt) {
  48623. if (!engine.isPointerLock) {
  48624. return;
  48625. }
  48626. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48627. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48628. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48629. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48630. if (!noPreventDefault) {
  48631. evt.preventDefault();
  48632. }
  48633. };
  48634. this._onGestureStart = function (e) {
  48635. if (window.MSGesture === undefined) {
  48636. return;
  48637. }
  48638. if (!_this._MSGestureHandler) {
  48639. _this._MSGestureHandler = new MSGesture();
  48640. _this._MSGestureHandler.target = element;
  48641. }
  48642. _this._MSGestureHandler.addPointer(e.pointerId);
  48643. };
  48644. this._onGesture = function (e) {
  48645. _this.camera.radius *= e.scale;
  48646. if (e.preventDefault) {
  48647. if (!noPreventDefault) {
  48648. e.stopPropagation();
  48649. e.preventDefault();
  48650. }
  48651. }
  48652. };
  48653. element.addEventListener("mousemove", this._onMouseMove, false);
  48654. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48655. element.addEventListener("MSGestureChange", this._onGesture, false);
  48656. BABYLON.Tools.RegisterTopRootEvents([
  48657. { name: "blur", handler: this._onLostFocus }
  48658. ]);
  48659. };
  48660. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48661. if (this._onLostFocus) {
  48662. BABYLON.Tools.UnregisterTopRootEvents([
  48663. { name: "blur", handler: this._onLostFocus }
  48664. ]);
  48665. }
  48666. if (element && this._observer) {
  48667. this.camera.getScene().onPointerObservable.remove(this._observer);
  48668. this._observer = null;
  48669. if (this._onContextMenu) {
  48670. element.removeEventListener("contextmenu", this._onContextMenu);
  48671. }
  48672. if (this._onMouseMove) {
  48673. element.removeEventListener("mousemove", this._onMouseMove);
  48674. }
  48675. if (this._onGestureStart) {
  48676. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48677. }
  48678. if (this._onGesture) {
  48679. element.removeEventListener("MSGestureChange", this._onGesture);
  48680. }
  48681. this._isPanClick = false;
  48682. this.pinchInwards = true;
  48683. this._onMouseMove = null;
  48684. this._onGestureStart = null;
  48685. this._onGesture = null;
  48686. this._MSGestureHandler = null;
  48687. this._onLostFocus = null;
  48688. this._onContextMenu = null;
  48689. }
  48690. };
  48691. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48692. return "ArcRotateCameraPointersInput";
  48693. };
  48694. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48695. return "pointers";
  48696. };
  48697. __decorate([
  48698. BABYLON.serialize()
  48699. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48700. __decorate([
  48701. BABYLON.serialize()
  48702. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48703. __decorate([
  48704. BABYLON.serialize()
  48705. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48706. __decorate([
  48707. BABYLON.serialize()
  48708. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48709. __decorate([
  48710. BABYLON.serialize()
  48711. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48712. __decorate([
  48713. BABYLON.serialize()
  48714. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48715. __decorate([
  48716. BABYLON.serialize()
  48717. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48718. __decorate([
  48719. BABYLON.serialize()
  48720. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48721. return ArcRotateCameraPointersInput;
  48722. }());
  48723. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48724. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48725. })(BABYLON || (BABYLON = {}));
  48726. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48727. var BABYLON;
  48728. (function (BABYLON) {
  48729. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48730. __extends(ArcRotateCameraInputsManager, _super);
  48731. function ArcRotateCameraInputsManager(camera) {
  48732. return _super.call(this, camera) || this;
  48733. }
  48734. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48735. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48736. return this;
  48737. };
  48738. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48739. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48740. return this;
  48741. };
  48742. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48743. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48744. return this;
  48745. };
  48746. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48747. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48748. return this;
  48749. };
  48750. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48751. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48752. return this;
  48753. };
  48754. return ArcRotateCameraInputsManager;
  48755. }(BABYLON.CameraInputsManager));
  48756. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48757. })(BABYLON || (BABYLON = {}));
  48758. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48759. var BABYLON;
  48760. (function (BABYLON) {
  48761. var ArcRotateCamera = /** @class */ (function (_super) {
  48762. __extends(ArcRotateCamera, _super);
  48763. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48764. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48765. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48766. _this.inertialAlphaOffset = 0;
  48767. _this.inertialBetaOffset = 0;
  48768. _this.inertialRadiusOffset = 0;
  48769. _this.lowerAlphaLimit = null;
  48770. _this.upperAlphaLimit = null;
  48771. _this.lowerBetaLimit = 0.01;
  48772. _this.upperBetaLimit = Math.PI;
  48773. _this.lowerRadiusLimit = null;
  48774. _this.upperRadiusLimit = null;
  48775. _this.inertialPanningX = 0;
  48776. _this.inertialPanningY = 0;
  48777. _this.pinchToPanMaxDistance = 20;
  48778. _this.panningDistanceLimit = null;
  48779. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48780. _this.panningInertia = 0.9;
  48781. //-- end properties for backward compatibility for inputs
  48782. _this.zoomOnFactor = 1;
  48783. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48784. _this.allowUpsideDown = true;
  48785. _this._viewMatrix = new BABYLON.Matrix();
  48786. // Panning
  48787. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48788. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48789. _this.checkCollisions = false;
  48790. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48791. _this._previousPosition = BABYLON.Vector3.Zero();
  48792. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48793. _this._newPosition = BABYLON.Vector3.Zero();
  48794. _this._computationVector = BABYLON.Vector3.Zero();
  48795. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48796. if (collidedMesh === void 0) { collidedMesh = null; }
  48797. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48798. newPosition.multiplyInPlace(_this._collider._radius);
  48799. }
  48800. if (!collidedMesh) {
  48801. _this._previousPosition.copyFrom(_this.position);
  48802. }
  48803. else {
  48804. _this.setPosition(newPosition);
  48805. if (_this.onCollide) {
  48806. _this.onCollide(collidedMesh);
  48807. }
  48808. }
  48809. // Recompute because of constraints
  48810. var cosa = Math.cos(_this.alpha);
  48811. var sina = Math.sin(_this.alpha);
  48812. var cosb = Math.cos(_this.beta);
  48813. var sinb = Math.sin(_this.beta);
  48814. if (sinb === 0) {
  48815. sinb = 0.0001;
  48816. }
  48817. var target = _this._getTargetPosition();
  48818. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48819. target.addToRef(_this._computationVector, _this._newPosition);
  48820. _this.position.copyFrom(_this._newPosition);
  48821. var up = _this.upVector;
  48822. if (_this.allowUpsideDown && _this.beta < 0) {
  48823. up = up.clone();
  48824. up = up.negate();
  48825. }
  48826. _this._computeViewMatrix(_this.position, target, up);
  48827. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48828. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48829. _this._collisionTriggered = false;
  48830. };
  48831. _this._target = BABYLON.Vector3.Zero();
  48832. if (target) {
  48833. _this.setTarget(target);
  48834. }
  48835. _this.alpha = alpha;
  48836. _this.beta = beta;
  48837. _this.radius = radius;
  48838. _this.getViewMatrix();
  48839. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48840. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48841. return _this;
  48842. }
  48843. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48844. get: function () {
  48845. return this._target;
  48846. },
  48847. set: function (value) {
  48848. this.setTarget(value);
  48849. },
  48850. enumerable: true,
  48851. configurable: true
  48852. });
  48853. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48854. //-- begin properties for backward compatibility for inputs
  48855. get: function () {
  48856. var pointers = this.inputs.attached["pointers"];
  48857. if (pointers)
  48858. return pointers.angularSensibilityX;
  48859. return 0;
  48860. },
  48861. set: function (value) {
  48862. var pointers = this.inputs.attached["pointers"];
  48863. if (pointers) {
  48864. pointers.angularSensibilityX = value;
  48865. }
  48866. },
  48867. enumerable: true,
  48868. configurable: true
  48869. });
  48870. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48871. get: function () {
  48872. var pointers = this.inputs.attached["pointers"];
  48873. if (pointers)
  48874. return pointers.angularSensibilityY;
  48875. return 0;
  48876. },
  48877. set: function (value) {
  48878. var pointers = this.inputs.attached["pointers"];
  48879. if (pointers) {
  48880. pointers.angularSensibilityY = value;
  48881. }
  48882. },
  48883. enumerable: true,
  48884. configurable: true
  48885. });
  48886. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48887. get: function () {
  48888. var pointers = this.inputs.attached["pointers"];
  48889. if (pointers)
  48890. return pointers.pinchPrecision;
  48891. return 0;
  48892. },
  48893. set: function (value) {
  48894. var pointers = this.inputs.attached["pointers"];
  48895. if (pointers) {
  48896. pointers.pinchPrecision = value;
  48897. }
  48898. },
  48899. enumerable: true,
  48900. configurable: true
  48901. });
  48902. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48903. get: function () {
  48904. var pointers = this.inputs.attached["pointers"];
  48905. if (pointers)
  48906. return pointers.pinchDeltaPercentage;
  48907. return 0;
  48908. },
  48909. set: function (value) {
  48910. var pointers = this.inputs.attached["pointers"];
  48911. if (pointers) {
  48912. pointers.pinchDeltaPercentage = value;
  48913. }
  48914. },
  48915. enumerable: true,
  48916. configurable: true
  48917. });
  48918. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48919. get: function () {
  48920. var pointers = this.inputs.attached["pointers"];
  48921. if (pointers)
  48922. return pointers.panningSensibility;
  48923. return 0;
  48924. },
  48925. set: function (value) {
  48926. var pointers = this.inputs.attached["pointers"];
  48927. if (pointers) {
  48928. pointers.panningSensibility = value;
  48929. }
  48930. },
  48931. enumerable: true,
  48932. configurable: true
  48933. });
  48934. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48935. get: function () {
  48936. var keyboard = this.inputs.attached["keyboard"];
  48937. if (keyboard)
  48938. return keyboard.keysUp;
  48939. return [];
  48940. },
  48941. set: function (value) {
  48942. var keyboard = this.inputs.attached["keyboard"];
  48943. if (keyboard)
  48944. keyboard.keysUp = value;
  48945. },
  48946. enumerable: true,
  48947. configurable: true
  48948. });
  48949. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48950. get: function () {
  48951. var keyboard = this.inputs.attached["keyboard"];
  48952. if (keyboard)
  48953. return keyboard.keysDown;
  48954. return [];
  48955. },
  48956. set: function (value) {
  48957. var keyboard = this.inputs.attached["keyboard"];
  48958. if (keyboard)
  48959. keyboard.keysDown = value;
  48960. },
  48961. enumerable: true,
  48962. configurable: true
  48963. });
  48964. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48965. get: function () {
  48966. var keyboard = this.inputs.attached["keyboard"];
  48967. if (keyboard)
  48968. return keyboard.keysLeft;
  48969. return [];
  48970. },
  48971. set: function (value) {
  48972. var keyboard = this.inputs.attached["keyboard"];
  48973. if (keyboard)
  48974. keyboard.keysLeft = value;
  48975. },
  48976. enumerable: true,
  48977. configurable: true
  48978. });
  48979. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48980. get: function () {
  48981. var keyboard = this.inputs.attached["keyboard"];
  48982. if (keyboard)
  48983. return keyboard.keysRight;
  48984. return [];
  48985. },
  48986. set: function (value) {
  48987. var keyboard = this.inputs.attached["keyboard"];
  48988. if (keyboard)
  48989. keyboard.keysRight = value;
  48990. },
  48991. enumerable: true,
  48992. configurable: true
  48993. });
  48994. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48995. get: function () {
  48996. var mousewheel = this.inputs.attached["mousewheel"];
  48997. if (mousewheel)
  48998. return mousewheel.wheelPrecision;
  48999. return 0;
  49000. },
  49001. set: function (value) {
  49002. var mousewheel = this.inputs.attached["mousewheel"];
  49003. if (mousewheel)
  49004. mousewheel.wheelPrecision = value;
  49005. },
  49006. enumerable: true,
  49007. configurable: true
  49008. });
  49009. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  49010. get: function () {
  49011. var mousewheel = this.inputs.attached["mousewheel"];
  49012. if (mousewheel)
  49013. return mousewheel.wheelDeltaPercentage;
  49014. return 0;
  49015. },
  49016. set: function (value) {
  49017. var mousewheel = this.inputs.attached["mousewheel"];
  49018. if (mousewheel)
  49019. mousewheel.wheelDeltaPercentage = value;
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  49025. get: function () {
  49026. return this._bouncingBehavior;
  49027. },
  49028. enumerable: true,
  49029. configurable: true
  49030. });
  49031. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  49032. get: function () {
  49033. return this._bouncingBehavior != null;
  49034. },
  49035. set: function (value) {
  49036. if (value === this.useBouncingBehavior) {
  49037. return;
  49038. }
  49039. if (value) {
  49040. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  49041. this.addBehavior(this._bouncingBehavior);
  49042. }
  49043. else if (this._bouncingBehavior) {
  49044. this.removeBehavior(this._bouncingBehavior);
  49045. this._bouncingBehavior = null;
  49046. }
  49047. },
  49048. enumerable: true,
  49049. configurable: true
  49050. });
  49051. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  49052. get: function () {
  49053. return this._framingBehavior;
  49054. },
  49055. enumerable: true,
  49056. configurable: true
  49057. });
  49058. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  49059. get: function () {
  49060. return this._framingBehavior != null;
  49061. },
  49062. set: function (value) {
  49063. if (value === this.useFramingBehavior) {
  49064. return;
  49065. }
  49066. if (value) {
  49067. this._framingBehavior = new BABYLON.FramingBehavior();
  49068. this.addBehavior(this._framingBehavior);
  49069. }
  49070. else if (this._framingBehavior) {
  49071. this.removeBehavior(this._framingBehavior);
  49072. this._framingBehavior = null;
  49073. }
  49074. },
  49075. enumerable: true,
  49076. configurable: true
  49077. });
  49078. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  49079. get: function () {
  49080. return this._autoRotationBehavior;
  49081. },
  49082. enumerable: true,
  49083. configurable: true
  49084. });
  49085. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  49086. get: function () {
  49087. return this._autoRotationBehavior != null;
  49088. },
  49089. set: function (value) {
  49090. if (value === this.useAutoRotationBehavior) {
  49091. return;
  49092. }
  49093. if (value) {
  49094. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  49095. this.addBehavior(this._autoRotationBehavior);
  49096. }
  49097. else if (this._autoRotationBehavior) {
  49098. this.removeBehavior(this._autoRotationBehavior);
  49099. this._autoRotationBehavior = null;
  49100. }
  49101. },
  49102. enumerable: true,
  49103. configurable: true
  49104. });
  49105. // Cache
  49106. ArcRotateCamera.prototype._initCache = function () {
  49107. _super.prototype._initCache.call(this);
  49108. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  49109. this._cache.alpha = undefined;
  49110. this._cache.beta = undefined;
  49111. this._cache.radius = undefined;
  49112. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  49113. };
  49114. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  49115. if (!ignoreParentClass) {
  49116. _super.prototype._updateCache.call(this);
  49117. }
  49118. this._cache._target.copyFrom(this._getTargetPosition());
  49119. this._cache.alpha = this.alpha;
  49120. this._cache.beta = this.beta;
  49121. this._cache.radius = this.radius;
  49122. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  49123. };
  49124. ArcRotateCamera.prototype._getTargetPosition = function () {
  49125. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  49126. var pos = this._targetHost.getAbsolutePosition();
  49127. if (this._targetBoundingCenter) {
  49128. pos.addToRef(this._targetBoundingCenter, this._target);
  49129. }
  49130. else {
  49131. this._target.copyFrom(pos);
  49132. }
  49133. }
  49134. var lockedTargetPosition = this._getLockedTargetPosition();
  49135. if (lockedTargetPosition) {
  49136. return lockedTargetPosition;
  49137. }
  49138. return this._target;
  49139. };
  49140. ArcRotateCamera.prototype.storeState = function () {
  49141. this._storedAlpha = this.alpha;
  49142. this._storedBeta = this.beta;
  49143. this._storedRadius = this.radius;
  49144. this._storedTarget = this._getTargetPosition().clone();
  49145. return _super.prototype.storeState.call(this);
  49146. };
  49147. /**
  49148. * Restored camera state. You must call storeState() first
  49149. */
  49150. ArcRotateCamera.prototype._restoreStateValues = function () {
  49151. if (!_super.prototype._restoreStateValues.call(this)) {
  49152. return false;
  49153. }
  49154. this.alpha = this._storedAlpha;
  49155. this.beta = this._storedBeta;
  49156. this.radius = this._storedRadius;
  49157. this.setTarget(this._storedTarget.clone());
  49158. this.inertialAlphaOffset = 0;
  49159. this.inertialBetaOffset = 0;
  49160. this.inertialRadiusOffset = 0;
  49161. this.inertialPanningX = 0;
  49162. this.inertialPanningY = 0;
  49163. return true;
  49164. };
  49165. // Synchronized
  49166. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  49167. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  49168. return false;
  49169. return this._cache._target.equals(this._getTargetPosition())
  49170. && this._cache.alpha === this.alpha
  49171. && this._cache.beta === this.beta
  49172. && this._cache.radius === this.radius
  49173. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  49174. };
  49175. // Methods
  49176. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  49177. var _this = this;
  49178. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  49179. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  49180. this._useCtrlForPanning = useCtrlForPanning;
  49181. this._panningMouseButton = panningMouseButton;
  49182. this.inputs.attachElement(element, noPreventDefault);
  49183. this._reset = function () {
  49184. _this.inertialAlphaOffset = 0;
  49185. _this.inertialBetaOffset = 0;
  49186. _this.inertialRadiusOffset = 0;
  49187. _this.inertialPanningX = 0;
  49188. _this.inertialPanningY = 0;
  49189. };
  49190. };
  49191. ArcRotateCamera.prototype.detachControl = function (element) {
  49192. this.inputs.detachElement(element);
  49193. if (this._reset) {
  49194. this._reset();
  49195. }
  49196. };
  49197. ArcRotateCamera.prototype._checkInputs = function () {
  49198. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  49199. if (this._collisionTriggered) {
  49200. return;
  49201. }
  49202. this.inputs.checkInputs();
  49203. // Inertia
  49204. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  49205. var inertialAlphaOffset = this.inertialAlphaOffset;
  49206. if (this.beta <= 0)
  49207. inertialAlphaOffset *= -1;
  49208. if (this.getScene().useRightHandedSystem)
  49209. inertialAlphaOffset *= -1;
  49210. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  49211. inertialAlphaOffset *= -1;
  49212. this.alpha += inertialAlphaOffset;
  49213. this.beta += this.inertialBetaOffset;
  49214. this.radius -= this.inertialRadiusOffset;
  49215. this.inertialAlphaOffset *= this.inertia;
  49216. this.inertialBetaOffset *= this.inertia;
  49217. this.inertialRadiusOffset *= this.inertia;
  49218. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  49219. this.inertialAlphaOffset = 0;
  49220. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  49221. this.inertialBetaOffset = 0;
  49222. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  49223. this.inertialRadiusOffset = 0;
  49224. }
  49225. // Panning inertia
  49226. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  49227. if (!this._localDirection) {
  49228. this._localDirection = BABYLON.Vector3.Zero();
  49229. this._transformedDirection = BABYLON.Vector3.Zero();
  49230. }
  49231. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  49232. this._localDirection.multiplyInPlace(this.panningAxis);
  49233. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  49234. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  49235. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  49236. if (!this.panningAxis.y) {
  49237. this._transformedDirection.y = 0;
  49238. }
  49239. if (!this._targetHost) {
  49240. if (this.panningDistanceLimit) {
  49241. this._transformedDirection.addInPlace(this._target);
  49242. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  49243. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  49244. this._target.copyFrom(this._transformedDirection);
  49245. }
  49246. }
  49247. else {
  49248. this._target.addInPlace(this._transformedDirection);
  49249. }
  49250. }
  49251. this.inertialPanningX *= this.panningInertia;
  49252. this.inertialPanningY *= this.panningInertia;
  49253. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  49254. this.inertialPanningX = 0;
  49255. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  49256. this.inertialPanningY = 0;
  49257. }
  49258. // Limits
  49259. this._checkLimits();
  49260. _super.prototype._checkInputs.call(this);
  49261. };
  49262. ArcRotateCamera.prototype._checkLimits = function () {
  49263. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  49264. if (this.allowUpsideDown && this.beta > Math.PI) {
  49265. this.beta = this.beta - (2 * Math.PI);
  49266. }
  49267. }
  49268. else {
  49269. if (this.beta < this.lowerBetaLimit) {
  49270. this.beta = this.lowerBetaLimit;
  49271. }
  49272. }
  49273. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  49274. if (this.allowUpsideDown && this.beta < -Math.PI) {
  49275. this.beta = this.beta + (2 * Math.PI);
  49276. }
  49277. }
  49278. else {
  49279. if (this.beta > this.upperBetaLimit) {
  49280. this.beta = this.upperBetaLimit;
  49281. }
  49282. }
  49283. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  49284. this.alpha = this.lowerAlphaLimit;
  49285. }
  49286. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  49287. this.alpha = this.upperAlphaLimit;
  49288. }
  49289. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  49290. this.radius = this.lowerRadiusLimit;
  49291. }
  49292. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49293. this.radius = this.upperRadiusLimit;
  49294. }
  49295. };
  49296. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49297. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49298. this.radius = this._computationVector.length();
  49299. if (this.radius === 0) {
  49300. this.radius = 0.0001; // Just to avoid division by zero
  49301. }
  49302. // Alpha
  49303. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49304. if (this._computationVector.z < 0) {
  49305. this.alpha = 2 * Math.PI - this.alpha;
  49306. }
  49307. // Beta
  49308. this.beta = Math.acos(this._computationVector.y / this.radius);
  49309. this._checkLimits();
  49310. };
  49311. ArcRotateCamera.prototype.setPosition = function (position) {
  49312. if (this.position.equals(position)) {
  49313. return;
  49314. }
  49315. this.position.copyFrom(position);
  49316. this.rebuildAnglesAndRadius();
  49317. };
  49318. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49319. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49320. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49321. if (target.getBoundingInfo) {
  49322. if (toBoundingCenter) {
  49323. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49324. }
  49325. else {
  49326. this._targetBoundingCenter = null;
  49327. }
  49328. this._targetHost = target;
  49329. this._target = this._getTargetPosition();
  49330. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49331. }
  49332. else {
  49333. var newTarget = target;
  49334. var currentTarget = this._getTargetPosition();
  49335. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49336. return;
  49337. }
  49338. this._targetHost = null;
  49339. this._target = newTarget;
  49340. this._targetBoundingCenter = null;
  49341. this.onMeshTargetChangedObservable.notifyObservers(null);
  49342. }
  49343. this.rebuildAnglesAndRadius();
  49344. };
  49345. ArcRotateCamera.prototype._getViewMatrix = function () {
  49346. // Compute
  49347. var cosa = Math.cos(this.alpha);
  49348. var sina = Math.sin(this.alpha);
  49349. var cosb = Math.cos(this.beta);
  49350. var sinb = Math.sin(this.beta);
  49351. if (sinb === 0) {
  49352. sinb = 0.0001;
  49353. }
  49354. var target = this._getTargetPosition();
  49355. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49356. target.addToRef(this._computationVector, this._newPosition);
  49357. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49358. if (!this._collider) {
  49359. this._collider = new BABYLON.Collider();
  49360. }
  49361. this._collider._radius = this.collisionRadius;
  49362. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49363. this._collisionTriggered = true;
  49364. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49365. }
  49366. else {
  49367. this.position.copyFrom(this._newPosition);
  49368. var up = this.upVector;
  49369. if (this.allowUpsideDown && sinb < 0) {
  49370. up = up.clone();
  49371. up = up.negate();
  49372. }
  49373. this._computeViewMatrix(this.position, target, up);
  49374. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49375. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49376. }
  49377. this._currentTarget = target;
  49378. return this._viewMatrix;
  49379. };
  49380. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49381. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49382. meshes = meshes || this.getScene().meshes;
  49383. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49384. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49385. this.radius = distance * this.zoomOnFactor;
  49386. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49387. };
  49388. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49389. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49390. var meshesOrMinMaxVector;
  49391. var distance;
  49392. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49393. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49394. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49395. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49396. }
  49397. else { //minMaxVector and distance
  49398. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49399. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49400. distance = minMaxVectorAndDistance.distance;
  49401. }
  49402. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49403. if (!doNotUpdateMaxZ) {
  49404. this.maxZ = distance * 2;
  49405. }
  49406. };
  49407. /**
  49408. * @override
  49409. * Override Camera.createRigCamera
  49410. */
  49411. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49412. var alphaShift = 0;
  49413. switch (this.cameraRigMode) {
  49414. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49415. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49416. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49417. case BABYLON.Camera.RIG_MODE_VR:
  49418. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49419. break;
  49420. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49421. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49422. break;
  49423. }
  49424. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49425. rigCam._cameraRigParams = {};
  49426. return rigCam;
  49427. };
  49428. /**
  49429. * @override
  49430. * Override Camera._updateRigCameras
  49431. */
  49432. ArcRotateCamera.prototype._updateRigCameras = function () {
  49433. var camLeft = this._rigCameras[0];
  49434. var camRight = this._rigCameras[1];
  49435. camLeft.beta = camRight.beta = this.beta;
  49436. camLeft.radius = camRight.radius = this.radius;
  49437. switch (this.cameraRigMode) {
  49438. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49439. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49440. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49441. case BABYLON.Camera.RIG_MODE_VR:
  49442. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49443. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49444. break;
  49445. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49446. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49447. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49448. break;
  49449. }
  49450. _super.prototype._updateRigCameras.call(this);
  49451. };
  49452. ArcRotateCamera.prototype.dispose = function () {
  49453. this.inputs.clear();
  49454. _super.prototype.dispose.call(this);
  49455. };
  49456. ArcRotateCamera.prototype.getClassName = function () {
  49457. return "ArcRotateCamera";
  49458. };
  49459. __decorate([
  49460. BABYLON.serialize()
  49461. ], ArcRotateCamera.prototype, "alpha", void 0);
  49462. __decorate([
  49463. BABYLON.serialize()
  49464. ], ArcRotateCamera.prototype, "beta", void 0);
  49465. __decorate([
  49466. BABYLON.serialize()
  49467. ], ArcRotateCamera.prototype, "radius", void 0);
  49468. __decorate([
  49469. BABYLON.serializeAsVector3("target")
  49470. ], ArcRotateCamera.prototype, "_target", void 0);
  49471. __decorate([
  49472. BABYLON.serialize()
  49473. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49474. __decorate([
  49475. BABYLON.serialize()
  49476. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49477. __decorate([
  49478. BABYLON.serialize()
  49479. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49480. __decorate([
  49481. BABYLON.serialize()
  49482. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49483. __decorate([
  49484. BABYLON.serialize()
  49485. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49486. __decorate([
  49487. BABYLON.serialize()
  49488. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49489. __decorate([
  49490. BABYLON.serialize()
  49491. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49492. __decorate([
  49493. BABYLON.serialize()
  49494. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49495. __decorate([
  49496. BABYLON.serialize()
  49497. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49498. __decorate([
  49499. BABYLON.serialize()
  49500. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49501. __decorate([
  49502. BABYLON.serialize()
  49503. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49504. __decorate([
  49505. BABYLON.serialize()
  49506. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49507. __decorate([
  49508. BABYLON.serialize()
  49509. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49510. __decorate([
  49511. BABYLON.serializeAsVector3()
  49512. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49513. __decorate([
  49514. BABYLON.serialize()
  49515. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49516. __decorate([
  49517. BABYLON.serialize()
  49518. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49519. __decorate([
  49520. BABYLON.serialize()
  49521. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49522. return ArcRotateCamera;
  49523. }(BABYLON.TargetCamera));
  49524. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49525. })(BABYLON || (BABYLON = {}));
  49526. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49527. var BABYLON;
  49528. (function (BABYLON) {
  49529. /**
  49530. * The HemisphericLight simulates the ambient environment light,
  49531. * so the passed direction is the light reflection direction, not the incoming direction.
  49532. */
  49533. var HemisphericLight = /** @class */ (function (_super) {
  49534. __extends(HemisphericLight, _super);
  49535. /**
  49536. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49537. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49538. * The HemisphericLight can't cast shadows.
  49539. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49540. * @param name The friendly name of the light
  49541. * @param direction The direction of the light reflection
  49542. * @param scene The scene the light belongs to
  49543. */
  49544. function HemisphericLight(name, direction, scene) {
  49545. var _this = _super.call(this, name, scene) || this;
  49546. /**
  49547. * The groundColor is the light in the opposite direction to the one specified during creation.
  49548. * 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.
  49549. */
  49550. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49551. _this.direction = direction || BABYLON.Vector3.Up();
  49552. return _this;
  49553. }
  49554. HemisphericLight.prototype._buildUniformLayout = function () {
  49555. this._uniformBuffer.addUniform("vLightData", 4);
  49556. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49557. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49558. this._uniformBuffer.addUniform("vLightGround", 3);
  49559. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49560. this._uniformBuffer.addUniform("depthValues", 2);
  49561. this._uniformBuffer.create();
  49562. };
  49563. /**
  49564. * Returns the string "HemisphericLight".
  49565. * @return The class name
  49566. */
  49567. HemisphericLight.prototype.getClassName = function () {
  49568. return "HemisphericLight";
  49569. };
  49570. /**
  49571. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49572. * Returns the updated direction.
  49573. * @param target The target the direction should point to
  49574. * @return The computed direction
  49575. */
  49576. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49577. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49578. return this.direction;
  49579. };
  49580. /**
  49581. * Returns the shadow generator associated to the light.
  49582. * @returns Always null for hemispheric lights because it does not support shadows.
  49583. */
  49584. HemisphericLight.prototype.getShadowGenerator = function () {
  49585. return null;
  49586. };
  49587. /**
  49588. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49589. * @param effect The effect to update
  49590. * @param lightIndex The index of the light in the effect to update
  49591. * @returns The hemispheric light
  49592. */
  49593. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49594. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49595. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49596. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49597. return this;
  49598. };
  49599. /**
  49600. * @hidden internal use only.
  49601. */
  49602. HemisphericLight.prototype._getWorldMatrix = function () {
  49603. if (!this._worldMatrix) {
  49604. this._worldMatrix = BABYLON.Matrix.Identity();
  49605. }
  49606. return this._worldMatrix;
  49607. };
  49608. /**
  49609. * Returns the integer 3.
  49610. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49611. */
  49612. HemisphericLight.prototype.getTypeID = function () {
  49613. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49614. };
  49615. __decorate([
  49616. BABYLON.serializeAsColor3()
  49617. ], HemisphericLight.prototype, "groundColor", void 0);
  49618. __decorate([
  49619. BABYLON.serializeAsVector3()
  49620. ], HemisphericLight.prototype, "direction", void 0);
  49621. return HemisphericLight;
  49622. }(BABYLON.Light));
  49623. BABYLON.HemisphericLight = HemisphericLight;
  49624. })(BABYLON || (BABYLON = {}));
  49625. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49626. var BABYLON;
  49627. (function (BABYLON) {
  49628. /**
  49629. * Base implementation IShadowLight
  49630. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49631. */
  49632. var ShadowLight = /** @class */ (function (_super) {
  49633. __extends(ShadowLight, _super);
  49634. function ShadowLight() {
  49635. var _this = _super !== null && _super.apply(this, arguments) || this;
  49636. _this._needProjectionMatrixCompute = true;
  49637. return _this;
  49638. }
  49639. ShadowLight.prototype._setPosition = function (value) {
  49640. this._position = value;
  49641. };
  49642. Object.defineProperty(ShadowLight.prototype, "position", {
  49643. /**
  49644. * Sets the position the shadow will be casted from. Also use as the light position for both
  49645. * point and spot lights.
  49646. */
  49647. get: function () {
  49648. return this._position;
  49649. },
  49650. /**
  49651. * Sets the position the shadow will be casted from. Also use as the light position for both
  49652. * point and spot lights.
  49653. */
  49654. set: function (value) {
  49655. this._setPosition(value);
  49656. },
  49657. enumerable: true,
  49658. configurable: true
  49659. });
  49660. ShadowLight.prototype._setDirection = function (value) {
  49661. this._direction = value;
  49662. };
  49663. Object.defineProperty(ShadowLight.prototype, "direction", {
  49664. /**
  49665. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49666. * Also use as the light direction on spot and directional lights.
  49667. */
  49668. get: function () {
  49669. return this._direction;
  49670. },
  49671. /**
  49672. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49673. * Also use as the light direction on spot and directional lights.
  49674. */
  49675. set: function (value) {
  49676. this._setDirection(value);
  49677. },
  49678. enumerable: true,
  49679. configurable: true
  49680. });
  49681. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49682. /**
  49683. * Gets the shadow projection clipping minimum z value.
  49684. */
  49685. get: function () {
  49686. return this._shadowMinZ;
  49687. },
  49688. /**
  49689. * Sets the shadow projection clipping minimum z value.
  49690. */
  49691. set: function (value) {
  49692. this._shadowMinZ = value;
  49693. this.forceProjectionMatrixCompute();
  49694. },
  49695. enumerable: true,
  49696. configurable: true
  49697. });
  49698. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49699. /**
  49700. * Sets the shadow projection clipping maximum z value.
  49701. */
  49702. get: function () {
  49703. return this._shadowMaxZ;
  49704. },
  49705. /**
  49706. * Gets the shadow projection clipping maximum z value.
  49707. */
  49708. set: function (value) {
  49709. this._shadowMaxZ = value;
  49710. this.forceProjectionMatrixCompute();
  49711. },
  49712. enumerable: true,
  49713. configurable: true
  49714. });
  49715. /**
  49716. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49717. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49718. */
  49719. ShadowLight.prototype.computeTransformedInformation = function () {
  49720. if (this.parent && this.parent.getWorldMatrix) {
  49721. if (!this.transformedPosition) {
  49722. this.transformedPosition = BABYLON.Vector3.Zero();
  49723. }
  49724. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49725. // In case the direction is present.
  49726. if (this.direction) {
  49727. if (!this.transformedDirection) {
  49728. this.transformedDirection = BABYLON.Vector3.Zero();
  49729. }
  49730. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49731. }
  49732. return true;
  49733. }
  49734. return false;
  49735. };
  49736. /**
  49737. * Return the depth scale used for the shadow map.
  49738. * @returns the depth scale.
  49739. */
  49740. ShadowLight.prototype.getDepthScale = function () {
  49741. return 50.0;
  49742. };
  49743. /**
  49744. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49745. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49746. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49747. */
  49748. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49749. return this.transformedDirection ? this.transformedDirection : this.direction;
  49750. };
  49751. /**
  49752. * Returns the ShadowLight absolute position in the World.
  49753. * @returns the position vector in world space
  49754. */
  49755. ShadowLight.prototype.getAbsolutePosition = function () {
  49756. return this.transformedPosition ? this.transformedPosition : this.position;
  49757. };
  49758. /**
  49759. * Sets the ShadowLight direction toward the passed target.
  49760. * @param target The point tot target in local space
  49761. * @returns the updated ShadowLight direction
  49762. */
  49763. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49764. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49765. return this.direction;
  49766. };
  49767. /**
  49768. * Returns the light rotation in euler definition.
  49769. * @returns the x y z rotation in local space.
  49770. */
  49771. ShadowLight.prototype.getRotation = function () {
  49772. this.direction.normalize();
  49773. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49774. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49775. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49776. };
  49777. /**
  49778. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49779. * @returns true if a cube texture needs to be use
  49780. */
  49781. ShadowLight.prototype.needCube = function () {
  49782. return false;
  49783. };
  49784. /**
  49785. * Detects if the projection matrix requires to be recomputed this frame.
  49786. * @returns true if it requires to be recomputed otherwise, false.
  49787. */
  49788. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49789. return this._needProjectionMatrixCompute;
  49790. };
  49791. /**
  49792. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49793. */
  49794. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49795. this._needProjectionMatrixCompute = true;
  49796. };
  49797. /**
  49798. * Get the world matrix of the sahdow lights.
  49799. * @hidden Internal Use Only
  49800. */
  49801. ShadowLight.prototype._getWorldMatrix = function () {
  49802. if (!this._worldMatrix) {
  49803. this._worldMatrix = BABYLON.Matrix.Identity();
  49804. }
  49805. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49806. return this._worldMatrix;
  49807. };
  49808. /**
  49809. * Gets the minZ used for shadow according to both the scene and the light.
  49810. * @param activeCamera The camera we are returning the min for
  49811. * @returns the depth min z
  49812. */
  49813. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49814. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49815. };
  49816. /**
  49817. * Gets the maxZ used for shadow according to both the scene and the light.
  49818. * @param activeCamera The camera we are returning the max for
  49819. * @returns the depth max z
  49820. */
  49821. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49822. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49823. };
  49824. /**
  49825. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49826. * @param matrix The materix to updated with the projection information
  49827. * @param viewMatrix The transform matrix of the light
  49828. * @param renderList The list of mesh to render in the map
  49829. * @returns The current light
  49830. */
  49831. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49832. if (this.customProjectionMatrixBuilder) {
  49833. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49834. }
  49835. else {
  49836. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49837. }
  49838. return this;
  49839. };
  49840. __decorate([
  49841. BABYLON.serializeAsVector3()
  49842. ], ShadowLight.prototype, "position", null);
  49843. __decorate([
  49844. BABYLON.serializeAsVector3()
  49845. ], ShadowLight.prototype, "direction", null);
  49846. __decorate([
  49847. BABYLON.serialize()
  49848. ], ShadowLight.prototype, "shadowMinZ", null);
  49849. __decorate([
  49850. BABYLON.serialize()
  49851. ], ShadowLight.prototype, "shadowMaxZ", null);
  49852. return ShadowLight;
  49853. }(BABYLON.Light));
  49854. BABYLON.ShadowLight = ShadowLight;
  49855. })(BABYLON || (BABYLON = {}));
  49856. //# sourceMappingURL=babylon.shadowLight.js.map
  49857. var BABYLON;
  49858. (function (BABYLON) {
  49859. /**
  49860. * A point light is a light defined by an unique point in world space.
  49861. * The light is emitted in every direction from this point.
  49862. * A good example of a point light is a standard light bulb.
  49863. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49864. */
  49865. var PointLight = /** @class */ (function (_super) {
  49866. __extends(PointLight, _super);
  49867. /**
  49868. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49869. * A PointLight emits the light in every direction.
  49870. * It can cast shadows.
  49871. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49872. * ```javascript
  49873. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49874. * ```
  49875. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49876. * @param name The light friendly name
  49877. * @param position The position of the point light in the scene
  49878. * @param scene The scene the lights belongs to
  49879. */
  49880. function PointLight(name, position, scene) {
  49881. var _this = _super.call(this, name, scene) || this;
  49882. _this._shadowAngle = Math.PI / 2;
  49883. _this.position = position;
  49884. return _this;
  49885. }
  49886. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49887. /**
  49888. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49889. * This specifies what angle the shadow will use to be created.
  49890. *
  49891. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49892. */
  49893. get: function () {
  49894. return this._shadowAngle;
  49895. },
  49896. /**
  49897. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49898. * This specifies what angle the shadow will use to be created.
  49899. *
  49900. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49901. */
  49902. set: function (value) {
  49903. this._shadowAngle = value;
  49904. this.forceProjectionMatrixCompute();
  49905. },
  49906. enumerable: true,
  49907. configurable: true
  49908. });
  49909. Object.defineProperty(PointLight.prototype, "direction", {
  49910. /**
  49911. * Gets the direction if it has been set.
  49912. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49913. */
  49914. get: function () {
  49915. return this._direction;
  49916. },
  49917. /**
  49918. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49919. */
  49920. set: function (value) {
  49921. var previousNeedCube = this.needCube();
  49922. this._direction = value;
  49923. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49924. this._shadowGenerator.recreateShadowMap();
  49925. }
  49926. },
  49927. enumerable: true,
  49928. configurable: true
  49929. });
  49930. /**
  49931. * Returns the string "PointLight"
  49932. * @returns the class name
  49933. */
  49934. PointLight.prototype.getClassName = function () {
  49935. return "PointLight";
  49936. };
  49937. /**
  49938. * Returns the integer 0.
  49939. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49940. */
  49941. PointLight.prototype.getTypeID = function () {
  49942. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49943. };
  49944. /**
  49945. * Specifies wether or not the shadowmap should be a cube texture.
  49946. * @returns true if the shadowmap needs to be a cube texture.
  49947. */
  49948. PointLight.prototype.needCube = function () {
  49949. return !this.direction;
  49950. };
  49951. /**
  49952. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49953. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49954. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49955. */
  49956. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49957. if (this.direction) {
  49958. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49959. }
  49960. else {
  49961. switch (faceIndex) {
  49962. case 0:
  49963. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49964. case 1:
  49965. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49966. case 2:
  49967. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49968. case 3:
  49969. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49970. case 4:
  49971. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49972. case 5:
  49973. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49974. }
  49975. }
  49976. return BABYLON.Vector3.Zero();
  49977. };
  49978. /**
  49979. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49980. * - fov = PI / 2
  49981. * - aspect ratio : 1.0
  49982. * - z-near and far equal to the active camera minZ and maxZ.
  49983. * Returns the PointLight.
  49984. */
  49985. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49986. var activeCamera = this.getScene().activeCamera;
  49987. if (!activeCamera) {
  49988. return;
  49989. }
  49990. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49991. };
  49992. PointLight.prototype._buildUniformLayout = function () {
  49993. this._uniformBuffer.addUniform("vLightData", 4);
  49994. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49995. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49996. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49997. this._uniformBuffer.addUniform("depthValues", 2);
  49998. this._uniformBuffer.create();
  49999. };
  50000. /**
  50001. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  50002. * @param effect The effect to update
  50003. * @param lightIndex The index of the light in the effect to update
  50004. * @returns The point light
  50005. */
  50006. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  50007. if (this.computeTransformedInformation()) {
  50008. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  50009. return this;
  50010. }
  50011. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  50012. return this;
  50013. };
  50014. __decorate([
  50015. BABYLON.serialize()
  50016. ], PointLight.prototype, "shadowAngle", null);
  50017. return PointLight;
  50018. }(BABYLON.ShadowLight));
  50019. BABYLON.PointLight = PointLight;
  50020. })(BABYLON || (BABYLON = {}));
  50021. //# sourceMappingURL=babylon.pointLight.js.map
  50022. var BABYLON;
  50023. (function (BABYLON) {
  50024. /**
  50025. * A directional light is defined by a direction (what a surprise!).
  50026. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  50027. * 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.
  50028. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50029. */
  50030. var DirectionalLight = /** @class */ (function (_super) {
  50031. __extends(DirectionalLight, _super);
  50032. /**
  50033. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  50034. * The directional light is emitted from everywhere in the given direction.
  50035. * It can cast shawdows.
  50036. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50037. * @param name The friendly name of the light
  50038. * @param direction The direction of the light
  50039. * @param scene The scene the light belongs to
  50040. */
  50041. function DirectionalLight(name, direction, scene) {
  50042. var _this = _super.call(this, name, scene) || this;
  50043. _this._shadowFrustumSize = 0;
  50044. _this._shadowOrthoScale = 0.1;
  50045. /**
  50046. * Automatically compute the projection matrix to best fit (including all the casters)
  50047. * on each frame.
  50048. */
  50049. _this.autoUpdateExtends = true;
  50050. // Cache
  50051. _this._orthoLeft = Number.MAX_VALUE;
  50052. _this._orthoRight = Number.MIN_VALUE;
  50053. _this._orthoTop = Number.MIN_VALUE;
  50054. _this._orthoBottom = Number.MAX_VALUE;
  50055. _this.position = direction.scale(-1.0);
  50056. _this.direction = direction;
  50057. return _this;
  50058. }
  50059. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  50060. /**
  50061. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  50062. */
  50063. get: function () {
  50064. return this._shadowFrustumSize;
  50065. },
  50066. /**
  50067. * Specifies a fix frustum size for the shadow generation.
  50068. */
  50069. set: function (value) {
  50070. this._shadowFrustumSize = value;
  50071. this.forceProjectionMatrixCompute();
  50072. },
  50073. enumerable: true,
  50074. configurable: true
  50075. });
  50076. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  50077. /**
  50078. * Gets the shadow projection scale against the optimal computed one.
  50079. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50080. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50081. */
  50082. get: function () {
  50083. return this._shadowOrthoScale;
  50084. },
  50085. /**
  50086. * Sets the shadow projection scale against the optimal computed one.
  50087. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  50088. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  50089. */
  50090. set: function (value) {
  50091. this._shadowOrthoScale = value;
  50092. this.forceProjectionMatrixCompute();
  50093. },
  50094. enumerable: true,
  50095. configurable: true
  50096. });
  50097. /**
  50098. * Returns the string "DirectionalLight".
  50099. * @return The class name
  50100. */
  50101. DirectionalLight.prototype.getClassName = function () {
  50102. return "DirectionalLight";
  50103. };
  50104. /**
  50105. * Returns the integer 1.
  50106. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50107. */
  50108. DirectionalLight.prototype.getTypeID = function () {
  50109. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  50110. };
  50111. /**
  50112. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  50113. * Returns the DirectionalLight Shadow projection matrix.
  50114. */
  50115. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50116. if (this.shadowFrustumSize > 0) {
  50117. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  50118. }
  50119. else {
  50120. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50121. }
  50122. };
  50123. /**
  50124. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  50125. * Returns the DirectionalLight Shadow projection matrix.
  50126. */
  50127. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  50128. var activeCamera = this.getScene().activeCamera;
  50129. if (!activeCamera) {
  50130. return;
  50131. }
  50132. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  50133. };
  50134. /**
  50135. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  50136. * Returns the DirectionalLight Shadow projection matrix.
  50137. */
  50138. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50139. var activeCamera = this.getScene().activeCamera;
  50140. if (!activeCamera) {
  50141. return;
  50142. }
  50143. // Check extends
  50144. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  50145. var tempVector3 = BABYLON.Vector3.Zero();
  50146. this._orthoLeft = Number.MAX_VALUE;
  50147. this._orthoRight = Number.MIN_VALUE;
  50148. this._orthoTop = Number.MIN_VALUE;
  50149. this._orthoBottom = Number.MAX_VALUE;
  50150. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  50151. var mesh = renderList[meshIndex];
  50152. if (!mesh) {
  50153. continue;
  50154. }
  50155. var boundingInfo = mesh.getBoundingInfo();
  50156. var boundingBox = boundingInfo.boundingBox;
  50157. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  50158. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  50159. if (tempVector3.x < this._orthoLeft)
  50160. this._orthoLeft = tempVector3.x;
  50161. if (tempVector3.y < this._orthoBottom)
  50162. this._orthoBottom = tempVector3.y;
  50163. if (tempVector3.x > this._orthoRight)
  50164. this._orthoRight = tempVector3.x;
  50165. if (tempVector3.y > this._orthoTop)
  50166. this._orthoTop = tempVector3.y;
  50167. }
  50168. }
  50169. }
  50170. var xOffset = this._orthoRight - this._orthoLeft;
  50171. var yOffset = this._orthoTop - this._orthoBottom;
  50172. 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);
  50173. };
  50174. DirectionalLight.prototype._buildUniformLayout = function () {
  50175. this._uniformBuffer.addUniform("vLightData", 4);
  50176. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50177. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50178. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50179. this._uniformBuffer.addUniform("depthValues", 2);
  50180. this._uniformBuffer.create();
  50181. };
  50182. /**
  50183. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  50184. * @param effect The effect to update
  50185. * @param lightIndex The index of the light in the effect to update
  50186. * @returns The directional light
  50187. */
  50188. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  50189. if (this.computeTransformedInformation()) {
  50190. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  50191. return this;
  50192. }
  50193. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  50194. return this;
  50195. };
  50196. /**
  50197. * Gets the minZ used for shadow according to both the scene and the light.
  50198. *
  50199. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50200. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50201. * @param activeCamera The camera we are returning the min for
  50202. * @returns the depth min z
  50203. */
  50204. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  50205. return 1;
  50206. };
  50207. /**
  50208. * Gets the maxZ used for shadow according to both the scene and the light.
  50209. *
  50210. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  50211. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  50212. * @param activeCamera The camera we are returning the max for
  50213. * @returns the depth max z
  50214. */
  50215. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  50216. return 1;
  50217. };
  50218. __decorate([
  50219. BABYLON.serialize()
  50220. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  50221. __decorate([
  50222. BABYLON.serialize()
  50223. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  50224. __decorate([
  50225. BABYLON.serialize()
  50226. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  50227. return DirectionalLight;
  50228. }(BABYLON.ShadowLight));
  50229. BABYLON.DirectionalLight = DirectionalLight;
  50230. })(BABYLON || (BABYLON = {}));
  50231. //# sourceMappingURL=babylon.directionalLight.js.map
  50232. var BABYLON;
  50233. (function (BABYLON) {
  50234. /**
  50235. * A spot light is defined by a position, a direction, an angle, and an exponent.
  50236. * These values define a cone of light starting from the position, emitting toward the direction.
  50237. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  50238. * and the exponent defines the speed of the decay of the light with distance (reach).
  50239. * Documentation: https://doc.babylonjs.com/babylon101/lights
  50240. */
  50241. var SpotLight = /** @class */ (function (_super) {
  50242. __extends(SpotLight, _super);
  50243. /**
  50244. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  50245. * It can cast shadows.
  50246. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50247. * @param name The light friendly name
  50248. * @param position The position of the spot light in the scene
  50249. * @param direction The direction of the light in the scene
  50250. * @param angle The cone angle of the light in Radians
  50251. * @param exponent The light decay speed with the distance from the emission spot
  50252. * @param scene The scene the lights belongs to
  50253. */
  50254. function SpotLight(name, position, direction, angle, exponent, scene) {
  50255. var _this = _super.call(this, name, scene) || this;
  50256. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  50257. _this._projectionTextureLightNear = 1e-6;
  50258. _this._projectionTextureLightFar = 1000.0;
  50259. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  50260. _this._projectionTextureViewLightDirty = true;
  50261. _this._projectionTextureProjectionLightDirty = true;
  50262. _this._projectionTextureDirty = true;
  50263. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  50264. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  50265. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  50266. _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);
  50267. _this.position = position;
  50268. _this.direction = direction;
  50269. _this.angle = angle;
  50270. _this.exponent = exponent;
  50271. return _this;
  50272. }
  50273. Object.defineProperty(SpotLight.prototype, "angle", {
  50274. /**
  50275. * Gets the cone angle of the spot light in Radians.
  50276. */
  50277. get: function () {
  50278. return this._angle;
  50279. },
  50280. /**
  50281. * Sets the cone angle of the spot light in Radians.
  50282. */
  50283. set: function (value) {
  50284. this._angle = value;
  50285. this._projectionTextureProjectionLightDirty = true;
  50286. this.forceProjectionMatrixCompute();
  50287. },
  50288. enumerable: true,
  50289. configurable: true
  50290. });
  50291. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50292. /**
  50293. * Allows scaling the angle of the light for shadow generation only.
  50294. */
  50295. get: function () {
  50296. return this._shadowAngleScale;
  50297. },
  50298. /**
  50299. * Allows scaling the angle of the light for shadow generation only.
  50300. */
  50301. set: function (value) {
  50302. this._shadowAngleScale = value;
  50303. this.forceProjectionMatrixCompute();
  50304. },
  50305. enumerable: true,
  50306. configurable: true
  50307. });
  50308. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50309. /**
  50310. * Allows reading the projecton texture
  50311. */
  50312. get: function () {
  50313. return this._projectionTextureMatrix;
  50314. },
  50315. enumerable: true,
  50316. configurable: true
  50317. });
  50318. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50319. /**
  50320. * Gets the near clip of the Spotlight for texture projection.
  50321. */
  50322. get: function () {
  50323. return this._projectionTextureLightNear;
  50324. },
  50325. /**
  50326. * Sets the near clip of the Spotlight for texture projection.
  50327. */
  50328. set: function (value) {
  50329. this._projectionTextureLightNear = value;
  50330. this._projectionTextureProjectionLightDirty = true;
  50331. },
  50332. enumerable: true,
  50333. configurable: true
  50334. });
  50335. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50336. /**
  50337. * Gets the far clip of the Spotlight for texture projection.
  50338. */
  50339. get: function () {
  50340. return this._projectionTextureLightFar;
  50341. },
  50342. /**
  50343. * Sets the far clip of the Spotlight for texture projection.
  50344. */
  50345. set: function (value) {
  50346. this._projectionTextureLightFar = value;
  50347. this._projectionTextureProjectionLightDirty = true;
  50348. },
  50349. enumerable: true,
  50350. configurable: true
  50351. });
  50352. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50353. /**
  50354. * Gets the Up vector of the Spotlight for texture projection.
  50355. */
  50356. get: function () {
  50357. return this._projectionTextureUpDirection;
  50358. },
  50359. /**
  50360. * Sets the Up vector of the Spotlight for texture projection.
  50361. */
  50362. set: function (value) {
  50363. this._projectionTextureUpDirection = value;
  50364. this._projectionTextureProjectionLightDirty = true;
  50365. },
  50366. enumerable: true,
  50367. configurable: true
  50368. });
  50369. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50370. /**
  50371. * Gets the projection texture of the light.
  50372. */
  50373. get: function () {
  50374. return this._projectionTexture;
  50375. },
  50376. /**
  50377. * Sets the projection texture of the light.
  50378. */
  50379. set: function (value) {
  50380. this._projectionTexture = value;
  50381. this._projectionTextureDirty = true;
  50382. },
  50383. enumerable: true,
  50384. configurable: true
  50385. });
  50386. /**
  50387. * Returns the string "SpotLight".
  50388. * @returns the class name
  50389. */
  50390. SpotLight.prototype.getClassName = function () {
  50391. return "SpotLight";
  50392. };
  50393. /**
  50394. * Returns the integer 2.
  50395. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50396. */
  50397. SpotLight.prototype.getTypeID = function () {
  50398. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50399. };
  50400. /**
  50401. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50402. */
  50403. SpotLight.prototype._setDirection = function (value) {
  50404. _super.prototype._setDirection.call(this, value);
  50405. this._projectionTextureViewLightDirty = true;
  50406. };
  50407. /**
  50408. * Overrides the position setter to recompute the projection texture view light Matrix.
  50409. */
  50410. SpotLight.prototype._setPosition = function (value) {
  50411. _super.prototype._setPosition.call(this, value);
  50412. this._projectionTextureViewLightDirty = true;
  50413. };
  50414. /**
  50415. * 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.
  50416. * Returns the SpotLight.
  50417. */
  50418. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50419. var activeCamera = this.getScene().activeCamera;
  50420. if (!activeCamera) {
  50421. return;
  50422. }
  50423. this._shadowAngleScale = this._shadowAngleScale || 1;
  50424. var angle = this._shadowAngleScale * this._angle;
  50425. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50426. };
  50427. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50428. this._projectionTextureViewLightDirty = false;
  50429. this._projectionTextureDirty = true;
  50430. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50431. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50432. };
  50433. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50434. this._projectionTextureProjectionLightDirty = false;
  50435. this._projectionTextureDirty = true;
  50436. var light_far = this.projectionTextureLightFar;
  50437. var light_near = this.projectionTextureLightNear;
  50438. var P = light_far / (light_far - light_near);
  50439. var Q = -P * light_near;
  50440. var S = 1.0 / Math.tan(this._angle / 2.0);
  50441. var A = 1.0;
  50442. 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);
  50443. };
  50444. /**
  50445. * Main function for light texture projection matrix computing.
  50446. */
  50447. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50448. this._projectionTextureDirty = false;
  50449. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50450. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50451. };
  50452. SpotLight.prototype._buildUniformLayout = function () {
  50453. this._uniformBuffer.addUniform("vLightData", 4);
  50454. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50455. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50456. this._uniformBuffer.addUniform("vLightDirection", 3);
  50457. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50458. this._uniformBuffer.addUniform("depthValues", 2);
  50459. this._uniformBuffer.create();
  50460. };
  50461. /**
  50462. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50463. * @param effect The effect to update
  50464. * @param lightIndex The index of the light in the effect to update
  50465. * @returns The spot light
  50466. */
  50467. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50468. var normalizeDirection;
  50469. if (this.computeTransformedInformation()) {
  50470. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50471. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50472. }
  50473. else {
  50474. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50475. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50476. }
  50477. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50478. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50479. if (this._projectionTextureViewLightDirty) {
  50480. this._computeProjectionTextureViewLightMatrix();
  50481. }
  50482. if (this._projectionTextureProjectionLightDirty) {
  50483. this._computeProjectionTextureProjectionLightMatrix();
  50484. }
  50485. if (this._projectionTextureDirty) {
  50486. this._computeProjectionTextureMatrix();
  50487. }
  50488. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50489. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50490. }
  50491. return this;
  50492. };
  50493. /**
  50494. * Disposes the light and the associated resources.
  50495. */
  50496. SpotLight.prototype.dispose = function () {
  50497. _super.prototype.dispose.call(this);
  50498. if (this._projectionTexture) {
  50499. this._projectionTexture.dispose();
  50500. }
  50501. };
  50502. __decorate([
  50503. BABYLON.serialize()
  50504. ], SpotLight.prototype, "angle", null);
  50505. __decorate([
  50506. BABYLON.serialize()
  50507. ], SpotLight.prototype, "shadowAngleScale", null);
  50508. __decorate([
  50509. BABYLON.serialize()
  50510. ], SpotLight.prototype, "exponent", void 0);
  50511. __decorate([
  50512. BABYLON.serialize()
  50513. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50514. __decorate([
  50515. BABYLON.serialize()
  50516. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50517. __decorate([
  50518. BABYLON.serialize()
  50519. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50520. __decorate([
  50521. BABYLON.serializeAsTexture("projectedLightTexture")
  50522. ], SpotLight.prototype, "_projectionTexture", void 0);
  50523. return SpotLight;
  50524. }(BABYLON.ShadowLight));
  50525. BABYLON.SpotLight = SpotLight;
  50526. })(BABYLON || (BABYLON = {}));
  50527. //# sourceMappingURL=babylon.spotLight.js.map
  50528. var BABYLON;
  50529. (function (BABYLON) {
  50530. /**
  50531. * Class used to override all child animations of a given target
  50532. */
  50533. var AnimationPropertiesOverride = /** @class */ (function () {
  50534. function AnimationPropertiesOverride() {
  50535. /**
  50536. * Gets or sets a value indicating if animation blending must be used
  50537. */
  50538. this.enableBlending = false;
  50539. /**
  50540. * Gets or sets the blending speed to use when enableBlending is true
  50541. */
  50542. this.blendingSpeed = 0.01;
  50543. /**
  50544. * Gets or sets the default loop mode to use
  50545. */
  50546. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50547. }
  50548. return AnimationPropertiesOverride;
  50549. }());
  50550. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50551. })(BABYLON || (BABYLON = {}));
  50552. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50553. var BABYLON;
  50554. (function (BABYLON) {
  50555. /**
  50556. * Represents the range of an animation
  50557. */
  50558. var AnimationRange = /** @class */ (function () {
  50559. /**
  50560. * Initializes the range of an animation
  50561. * @param name The name of the animation range
  50562. * @param from The starting frame of the animation
  50563. * @param to The ending frame of the animation
  50564. */
  50565. function AnimationRange(
  50566. /**The name of the animation range**/
  50567. name,
  50568. /**The starting frame of the animation */
  50569. from,
  50570. /**The ending frame of the animation*/
  50571. to) {
  50572. this.name = name;
  50573. this.from = from;
  50574. this.to = to;
  50575. }
  50576. /**
  50577. * Makes a copy of the animation range
  50578. * @returns A copy of the animation range
  50579. */
  50580. AnimationRange.prototype.clone = function () {
  50581. return new AnimationRange(this.name, this.from, this.to);
  50582. };
  50583. return AnimationRange;
  50584. }());
  50585. BABYLON.AnimationRange = AnimationRange;
  50586. /**
  50587. * Composed of a frame, and an action function
  50588. */
  50589. var AnimationEvent = /** @class */ (function () {
  50590. /**
  50591. * Initializes the animation event
  50592. * @param frame The frame for which the event is triggered
  50593. * @param action The event to perform when triggered
  50594. * @param onlyOnce Specifies if the event should be triggered only once
  50595. */
  50596. function AnimationEvent(
  50597. /** The frame for which the event is triggered **/
  50598. frame,
  50599. /** The event to perform when triggered **/
  50600. action,
  50601. /** Specifies if the event should be triggered only once**/
  50602. onlyOnce) {
  50603. this.frame = frame;
  50604. this.action = action;
  50605. this.onlyOnce = onlyOnce;
  50606. /**
  50607. * Specifies if the animation event is done
  50608. */
  50609. this.isDone = false;
  50610. }
  50611. /** @hidden */
  50612. AnimationEvent.prototype._clone = function () {
  50613. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50614. };
  50615. return AnimationEvent;
  50616. }());
  50617. BABYLON.AnimationEvent = AnimationEvent;
  50618. /**
  50619. * A cursor which tracks a point on a path
  50620. */
  50621. var PathCursor = /** @class */ (function () {
  50622. /**
  50623. * Initializes the path cursor
  50624. * @param path The path to track
  50625. */
  50626. function PathCursor(path) {
  50627. this.path = path;
  50628. /**
  50629. * Stores path cursor callbacks for when an onchange event is triggered
  50630. */
  50631. this._onchange = new Array();
  50632. /**
  50633. * The value of the path cursor
  50634. */
  50635. this.value = 0;
  50636. /**
  50637. * The animation array of the path cursor
  50638. */
  50639. this.animations = new Array();
  50640. }
  50641. /**
  50642. * Gets the cursor point on the path
  50643. * @returns A point on the path cursor at the cursor location
  50644. */
  50645. PathCursor.prototype.getPoint = function () {
  50646. var point = this.path.getPointAtLengthPosition(this.value);
  50647. return new BABYLON.Vector3(point.x, 0, point.y);
  50648. };
  50649. /**
  50650. * Moves the cursor ahead by the step amount
  50651. * @param step The amount to move the cursor forward
  50652. * @returns This path cursor
  50653. */
  50654. PathCursor.prototype.moveAhead = function (step) {
  50655. if (step === void 0) { step = 0.002; }
  50656. this.move(step);
  50657. return this;
  50658. };
  50659. /**
  50660. * Moves the cursor behind by the step amount
  50661. * @param step The amount to move the cursor back
  50662. * @returns This path cursor
  50663. */
  50664. PathCursor.prototype.moveBack = function (step) {
  50665. if (step === void 0) { step = 0.002; }
  50666. this.move(-step);
  50667. return this;
  50668. };
  50669. /**
  50670. * Moves the cursor by the step amount
  50671. * If the step amount is greater than one, an exception is thrown
  50672. * @param step The amount to move the cursor
  50673. * @returns This path cursor
  50674. */
  50675. PathCursor.prototype.move = function (step) {
  50676. if (Math.abs(step) > 1) {
  50677. throw "step size should be less than 1.";
  50678. }
  50679. this.value += step;
  50680. this.ensureLimits();
  50681. this.raiseOnChange();
  50682. return this;
  50683. };
  50684. /**
  50685. * Ensures that the value is limited between zero and one
  50686. * @returns This path cursor
  50687. */
  50688. PathCursor.prototype.ensureLimits = function () {
  50689. while (this.value > 1) {
  50690. this.value -= 1;
  50691. }
  50692. while (this.value < 0) {
  50693. this.value += 1;
  50694. }
  50695. return this;
  50696. };
  50697. /**
  50698. * Runs onchange callbacks on change (used by the animation engine)
  50699. * @returns This path cursor
  50700. */
  50701. PathCursor.prototype.raiseOnChange = function () {
  50702. var _this = this;
  50703. this._onchange.forEach(function (f) { return f(_this); });
  50704. return this;
  50705. };
  50706. /**
  50707. * Executes a function on change
  50708. * @param f A path cursor onchange callback
  50709. * @returns This path cursor
  50710. */
  50711. PathCursor.prototype.onchange = function (f) {
  50712. this._onchange.push(f);
  50713. return this;
  50714. };
  50715. return PathCursor;
  50716. }());
  50717. BABYLON.PathCursor = PathCursor;
  50718. /**
  50719. * Enum for the animation key frame interpolation type
  50720. */
  50721. var AnimationKeyInterpolation;
  50722. (function (AnimationKeyInterpolation) {
  50723. /**
  50724. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50725. */
  50726. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50727. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50728. /**
  50729. * Class used to store any kind of animation
  50730. */
  50731. var Animation = /** @class */ (function () {
  50732. /**
  50733. * Initializes the animation
  50734. * @param name Name of the animation
  50735. * @param targetProperty Property to animate
  50736. * @param framePerSecond The frames per second of the animation
  50737. * @param dataType The data type of the animation
  50738. * @param loopMode The loop mode of the animation
  50739. * @param enableBlendings Specifies if blending should be enabled
  50740. */
  50741. function Animation(
  50742. /**Name of the animation */
  50743. name,
  50744. /**Property to animate */
  50745. targetProperty,
  50746. /**The frames per second of the animation */
  50747. framePerSecond,
  50748. /**The data type of the animation */
  50749. dataType,
  50750. /**The loop mode of the animation */
  50751. loopMode,
  50752. /**Specifies if blending should be enabled */
  50753. enableBlending) {
  50754. this.name = name;
  50755. this.targetProperty = targetProperty;
  50756. this.framePerSecond = framePerSecond;
  50757. this.dataType = dataType;
  50758. this.loopMode = loopMode;
  50759. this.enableBlending = enableBlending;
  50760. /**
  50761. * @hidden Internal use only
  50762. */
  50763. this._runtimeAnimations = new Array();
  50764. /**
  50765. * The set of event that will be linked to this animation
  50766. */
  50767. this._events = new Array();
  50768. /**
  50769. * Stores the blending speed of the animation
  50770. */
  50771. this.blendingSpeed = 0.01;
  50772. /**
  50773. * Stores the animation ranges for the animation
  50774. */
  50775. this._ranges = {};
  50776. this.targetPropertyPath = targetProperty.split(".");
  50777. this.dataType = dataType;
  50778. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50779. }
  50780. /**
  50781. * @hidden Internal use
  50782. */
  50783. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50784. var dataType = undefined;
  50785. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50786. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50787. }
  50788. else if (from instanceof BABYLON.Quaternion) {
  50789. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50790. }
  50791. else if (from instanceof BABYLON.Vector3) {
  50792. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50793. }
  50794. else if (from instanceof BABYLON.Vector2) {
  50795. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50796. }
  50797. else if (from instanceof BABYLON.Color3) {
  50798. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50799. }
  50800. else if (from instanceof BABYLON.Size) {
  50801. dataType = Animation.ANIMATIONTYPE_SIZE;
  50802. }
  50803. if (dataType == undefined) {
  50804. return null;
  50805. }
  50806. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50807. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50808. animation.setKeys(keys);
  50809. if (easingFunction !== undefined) {
  50810. animation.setEasingFunction(easingFunction);
  50811. }
  50812. return animation;
  50813. };
  50814. /**
  50815. * Sets up an animation
  50816. * @param property The property to animate
  50817. * @param animationType The animation type to apply
  50818. * @param framePerSecond The frames per second of the animation
  50819. * @param easingFunction The easing function used in the animation
  50820. * @returns The created animation
  50821. */
  50822. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50823. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50824. animation.setEasingFunction(easingFunction);
  50825. return animation;
  50826. };
  50827. /**
  50828. * Create and start an animation on a node
  50829. * @param name defines the name of the global animation that will be run on all nodes
  50830. * @param node defines the root node where the animation will take place
  50831. * @param targetProperty defines property to animate
  50832. * @param framePerSecond defines the number of frame per second yo use
  50833. * @param totalFrame defines the number of frames in total
  50834. * @param from defines the initial value
  50835. * @param to defines the final value
  50836. * @param loopMode defines which loop mode you want to use (off by default)
  50837. * @param easingFunction defines the easing function to use (linear by default)
  50838. * @param onAnimationEnd defines the callback to call when animation end
  50839. * @returns the animatable created for this animation
  50840. */
  50841. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50842. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50843. if (!animation) {
  50844. return null;
  50845. }
  50846. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50847. };
  50848. /**
  50849. * Create and start an animation on a node and its descendants
  50850. * @param name defines the name of the global animation that will be run on all nodes
  50851. * @param node defines the root node where the animation will take place
  50852. * @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
  50853. * @param targetProperty defines property to animate
  50854. * @param framePerSecond defines the number of frame per second to use
  50855. * @param totalFrame defines the number of frames in total
  50856. * @param from defines the initial value
  50857. * @param to defines the final value
  50858. * @param loopMode defines which loop mode you want to use (off by default)
  50859. * @param easingFunction defines the easing function to use (linear by default)
  50860. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50861. * @returns the list of animatables created for all nodes
  50862. * @example https://www.babylonjs-playground.com/#MH0VLI
  50863. */
  50864. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50865. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50866. if (!animation) {
  50867. return null;
  50868. }
  50869. var scene = node.getScene();
  50870. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50871. };
  50872. /**
  50873. * Creates a new animation, merges it with the existing animations and starts it
  50874. * @param name Name of the animation
  50875. * @param node Node which contains the scene that begins the animations
  50876. * @param targetProperty Specifies which property to animate
  50877. * @param framePerSecond The frames per second of the animation
  50878. * @param totalFrame The total number of frames
  50879. * @param from The frame at the beginning of the animation
  50880. * @param to The frame at the end of the animation
  50881. * @param loopMode Specifies the loop mode of the animation
  50882. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50883. * @param onAnimationEnd Callback to run once the animation is complete
  50884. * @returns Nullable animation
  50885. */
  50886. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50887. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50888. if (!animation) {
  50889. return null;
  50890. }
  50891. node.animations.push(animation);
  50892. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50893. };
  50894. /**
  50895. * Transition property of an host to the target Value
  50896. * @param property The property to transition
  50897. * @param targetValue The target Value of the property
  50898. * @param host The object where the property to animate belongs
  50899. * @param scene Scene used to run the animation
  50900. * @param frameRate Framerate (in frame/s) to use
  50901. * @param transition The transition type we want to use
  50902. * @param duration The duration of the animation, in milliseconds
  50903. * @param onAnimationEnd Callback trigger at the end of the animation
  50904. * @returns Nullable animation
  50905. */
  50906. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50907. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50908. if (duration <= 0) {
  50909. host[property] = targetValue;
  50910. if (onAnimationEnd) {
  50911. onAnimationEnd();
  50912. }
  50913. return null;
  50914. }
  50915. var endFrame = frameRate * (duration / 1000);
  50916. transition.setKeys([{
  50917. frame: 0,
  50918. value: host[property].clone ? host[property].clone() : host[property]
  50919. },
  50920. {
  50921. frame: endFrame,
  50922. value: targetValue
  50923. }]);
  50924. if (!host.animations) {
  50925. host.animations = [];
  50926. }
  50927. host.animations.push(transition);
  50928. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50929. animation.onAnimationEnd = onAnimationEnd;
  50930. return animation;
  50931. };
  50932. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50933. /**
  50934. * Return the array of runtime animations currently using this animation
  50935. */
  50936. get: function () {
  50937. return this._runtimeAnimations;
  50938. },
  50939. enumerable: true,
  50940. configurable: true
  50941. });
  50942. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50943. /**
  50944. * Specifies if any of the runtime animations are currently running
  50945. */
  50946. get: function () {
  50947. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50948. var runtimeAnimation = _a[_i];
  50949. if (!runtimeAnimation.isStopped) {
  50950. return true;
  50951. }
  50952. }
  50953. return false;
  50954. },
  50955. enumerable: true,
  50956. configurable: true
  50957. });
  50958. // Methods
  50959. /**
  50960. * Converts the animation to a string
  50961. * @param fullDetails support for multiple levels of logging within scene loading
  50962. * @returns String form of the animation
  50963. */
  50964. Animation.prototype.toString = function (fullDetails) {
  50965. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50966. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50967. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50968. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50969. if (fullDetails) {
  50970. ret += ", Ranges: {";
  50971. var first = true;
  50972. for (var name in this._ranges) {
  50973. if (first) {
  50974. ret += ", ";
  50975. first = false;
  50976. }
  50977. ret += name;
  50978. }
  50979. ret += "}";
  50980. }
  50981. return ret;
  50982. };
  50983. /**
  50984. * Add an event to this animation
  50985. * @param event Event to add
  50986. */
  50987. Animation.prototype.addEvent = function (event) {
  50988. this._events.push(event);
  50989. };
  50990. /**
  50991. * Remove all events found at the given frame
  50992. * @param frame The frame to remove events from
  50993. */
  50994. Animation.prototype.removeEvents = function (frame) {
  50995. for (var index = 0; index < this._events.length; index++) {
  50996. if (this._events[index].frame === frame) {
  50997. this._events.splice(index, 1);
  50998. index--;
  50999. }
  51000. }
  51001. };
  51002. /**
  51003. * Retrieves all the events from the animation
  51004. * @returns Events from the animation
  51005. */
  51006. Animation.prototype.getEvents = function () {
  51007. return this._events;
  51008. };
  51009. /**
  51010. * Creates an animation range
  51011. * @param name Name of the animation range
  51012. * @param from Starting frame of the animation range
  51013. * @param to Ending frame of the animation
  51014. */
  51015. Animation.prototype.createRange = function (name, from, to) {
  51016. // check name not already in use; could happen for bones after serialized
  51017. if (!this._ranges[name]) {
  51018. this._ranges[name] = new AnimationRange(name, from, to);
  51019. }
  51020. };
  51021. /**
  51022. * Deletes an animation range by name
  51023. * @param name Name of the animation range to delete
  51024. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  51025. */
  51026. Animation.prototype.deleteRange = function (name, deleteFrames) {
  51027. if (deleteFrames === void 0) { deleteFrames = true; }
  51028. var range = this._ranges[name];
  51029. if (!range) {
  51030. return;
  51031. }
  51032. if (deleteFrames) {
  51033. var from = range.from;
  51034. var to = range.to;
  51035. // this loop MUST go high to low for multiple splices to work
  51036. for (var key = this._keys.length - 1; key >= 0; key--) {
  51037. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  51038. this._keys.splice(key, 1);
  51039. }
  51040. }
  51041. }
  51042. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  51043. };
  51044. /**
  51045. * Gets the animation range by name, or null if not defined
  51046. * @param name Name of the animation range
  51047. * @returns Nullable animation range
  51048. */
  51049. Animation.prototype.getRange = function (name) {
  51050. return this._ranges[name];
  51051. };
  51052. /**
  51053. * Gets the key frames from the animation
  51054. * @returns The key frames of the animation
  51055. */
  51056. Animation.prototype.getKeys = function () {
  51057. return this._keys;
  51058. };
  51059. /**
  51060. * Gets the highest frame rate of the animation
  51061. * @returns Highest frame rate of the animation
  51062. */
  51063. Animation.prototype.getHighestFrame = function () {
  51064. var ret = 0;
  51065. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  51066. if (ret < this._keys[key].frame) {
  51067. ret = this._keys[key].frame;
  51068. }
  51069. }
  51070. return ret;
  51071. };
  51072. /**
  51073. * Gets the easing function of the animation
  51074. * @returns Easing function of the animation
  51075. */
  51076. Animation.prototype.getEasingFunction = function () {
  51077. return this._easingFunction;
  51078. };
  51079. /**
  51080. * Sets the easing function of the animation
  51081. * @param easingFunction A custom mathematical formula for animation
  51082. */
  51083. Animation.prototype.setEasingFunction = function (easingFunction) {
  51084. this._easingFunction = easingFunction;
  51085. };
  51086. /**
  51087. * Interpolates a scalar 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 scalar value
  51092. */
  51093. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  51094. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  51095. };
  51096. /**
  51097. * Interpolates a scalar 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 scalar value
  51104. */
  51105. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51106. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51107. };
  51108. /**
  51109. * Interpolates a quaternion using a spherical linear interpolation
  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 quaternion value
  51114. */
  51115. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  51116. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  51117. };
  51118. /**
  51119. * Interpolates a quaternion cubically
  51120. * @param startValue Start value of the animation curve
  51121. * @param outTangent End tangent of the animation curve
  51122. * @param endValue End value of the animation curve
  51123. * @param inTangent Start tangent of the animation curve
  51124. * @param gradient Scalar amount to interpolate
  51125. * @returns Interpolated quaternion value
  51126. */
  51127. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51128. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  51129. };
  51130. /**
  51131. * Interpolates a Vector3 linearl
  51132. * @param startValue Start value of the animation curve
  51133. * @param endValue End value of the animation curve
  51134. * @param gradient Scalar amount to interpolate
  51135. * @returns Interpolated scalar value
  51136. */
  51137. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  51138. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  51139. };
  51140. /**
  51141. * Interpolates a Vector3 cubically
  51142. * @param startValue Start value of the animation curve
  51143. * @param outTangent End tangent of the animation
  51144. * @param endValue End value of the animation curve
  51145. * @param inTangent Start tangent of the animation curve
  51146. * @param gradient Scalar amount to interpolate
  51147. * @returns InterpolatedVector3 value
  51148. */
  51149. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51150. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51151. };
  51152. /**
  51153. * Interpolates a Vector2 linearly
  51154. * @param startValue Start value of the animation curve
  51155. * @param endValue End value of the animation curve
  51156. * @param gradient Scalar amount to interpolate
  51157. * @returns Interpolated Vector2 value
  51158. */
  51159. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  51160. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  51161. };
  51162. /**
  51163. * Interpolates a Vector2 cubically
  51164. * @param startValue Start value of the animation curve
  51165. * @param outTangent End tangent of the animation
  51166. * @param endValue End value of the animation curve
  51167. * @param inTangent Start tangent of the animation curve
  51168. * @param gradient Scalar amount to interpolate
  51169. * @returns Interpolated Vector2 value
  51170. */
  51171. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  51172. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  51173. };
  51174. /**
  51175. * Interpolates a size linearly
  51176. * @param startValue Start value of the animation curve
  51177. * @param endValue End value of the animation curve
  51178. * @param gradient Scalar amount to interpolate
  51179. * @returns Interpolated Size value
  51180. */
  51181. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  51182. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  51183. };
  51184. /**
  51185. * Interpolates a Color3 linearly
  51186. * @param startValue Start value of the animation curve
  51187. * @param endValue End value of the animation curve
  51188. * @param gradient Scalar amount to interpolate
  51189. * @returns Interpolated Color3 value
  51190. */
  51191. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  51192. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  51193. };
  51194. /**
  51195. * @hidden Internal use only
  51196. */
  51197. Animation.prototype._getKeyValue = function (value) {
  51198. if (typeof value === "function") {
  51199. return value();
  51200. }
  51201. return value;
  51202. };
  51203. /**
  51204. * @hidden Internal use only
  51205. */
  51206. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  51207. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  51208. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  51209. }
  51210. var keys = this.getKeys();
  51211. // Try to get a hash to find the right key
  51212. 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));
  51213. if (keys[startKeyIndex].frame >= currentFrame) {
  51214. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  51215. startKeyIndex--;
  51216. }
  51217. }
  51218. for (var key = startKeyIndex; key < keys.length; key++) {
  51219. var endKey = keys[key + 1];
  51220. if (endKey.frame >= currentFrame) {
  51221. var startKey = keys[key];
  51222. var startValue = this._getKeyValue(startKey.value);
  51223. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  51224. return startValue;
  51225. }
  51226. var endValue = this._getKeyValue(endKey.value);
  51227. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  51228. var frameDelta = endKey.frame - startKey.frame;
  51229. // gradient : percent of currentFrame between the frame inf and the frame sup
  51230. var gradient = (currentFrame - startKey.frame) / frameDelta;
  51231. // check for easingFunction and correction of gradient
  51232. var easingFunction = this.getEasingFunction();
  51233. if (easingFunction != null) {
  51234. gradient = easingFunction.ease(gradient);
  51235. }
  51236. switch (this.dataType) {
  51237. // Float
  51238. case Animation.ANIMATIONTYPE_FLOAT:
  51239. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  51240. switch (loopMode) {
  51241. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51242. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51243. return floatValue;
  51244. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51245. return offsetValue * repeatCount + floatValue;
  51246. }
  51247. break;
  51248. // Quaternion
  51249. case Animation.ANIMATIONTYPE_QUATERNION:
  51250. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  51251. switch (loopMode) {
  51252. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51253. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51254. return quatValue;
  51255. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51256. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  51257. }
  51258. return quatValue;
  51259. // Vector3
  51260. case Animation.ANIMATIONTYPE_VECTOR3:
  51261. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  51262. switch (loopMode) {
  51263. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51264. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51265. return vec3Value;
  51266. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51267. return vec3Value.add(offsetValue.scale(repeatCount));
  51268. }
  51269. // Vector2
  51270. case Animation.ANIMATIONTYPE_VECTOR2:
  51271. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  51272. switch (loopMode) {
  51273. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51274. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51275. return vec2Value;
  51276. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51277. return vec2Value.add(offsetValue.scale(repeatCount));
  51278. }
  51279. // Size
  51280. case Animation.ANIMATIONTYPE_SIZE:
  51281. switch (loopMode) {
  51282. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51283. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51284. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  51285. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51286. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51287. }
  51288. // Color3
  51289. case Animation.ANIMATIONTYPE_COLOR3:
  51290. switch (loopMode) {
  51291. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51292. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51293. return this.color3InterpolateFunction(startValue, endValue, gradient);
  51294. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51295. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51296. }
  51297. // Matrix
  51298. case Animation.ANIMATIONTYPE_MATRIX:
  51299. switch (loopMode) {
  51300. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51301. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51302. if (Animation.AllowMatricesInterpolation) {
  51303. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51304. }
  51305. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51306. return startValue;
  51307. }
  51308. default:
  51309. break;
  51310. }
  51311. break;
  51312. }
  51313. }
  51314. return this._getKeyValue(keys[keys.length - 1].value);
  51315. };
  51316. /**
  51317. * Defines the function to use to interpolate matrices
  51318. * @param startValue defines the start matrix
  51319. * @param endValue defines the end matrix
  51320. * @param gradient defines the gradient between both matrices
  51321. * @param result defines an optional target matrix where to store the interpolation
  51322. * @returns the interpolated matrix
  51323. */
  51324. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51325. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51326. if (result) {
  51327. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51328. return result;
  51329. }
  51330. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51331. }
  51332. if (result) {
  51333. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51334. return result;
  51335. }
  51336. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51337. };
  51338. /**
  51339. * Makes a copy of the animation
  51340. * @returns Cloned animation
  51341. */
  51342. Animation.prototype.clone = function () {
  51343. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51344. clone.enableBlending = this.enableBlending;
  51345. clone.blendingSpeed = this.blendingSpeed;
  51346. if (this._keys) {
  51347. clone.setKeys(this._keys);
  51348. }
  51349. if (this._ranges) {
  51350. clone._ranges = {};
  51351. for (var name in this._ranges) {
  51352. var range = this._ranges[name];
  51353. if (!range) {
  51354. continue;
  51355. }
  51356. clone._ranges[name] = range.clone();
  51357. }
  51358. }
  51359. return clone;
  51360. };
  51361. /**
  51362. * Sets the key frames of the animation
  51363. * @param values The animation key frames to set
  51364. */
  51365. Animation.prototype.setKeys = function (values) {
  51366. this._keys = values.slice(0);
  51367. };
  51368. /**
  51369. * Serializes the animation to an object
  51370. * @returns Serialized object
  51371. */
  51372. Animation.prototype.serialize = function () {
  51373. var serializationObject = {};
  51374. serializationObject.name = this.name;
  51375. serializationObject.property = this.targetProperty;
  51376. serializationObject.framePerSecond = this.framePerSecond;
  51377. serializationObject.dataType = this.dataType;
  51378. serializationObject.loopBehavior = this.loopMode;
  51379. serializationObject.enableBlending = this.enableBlending;
  51380. serializationObject.blendingSpeed = this.blendingSpeed;
  51381. var dataType = this.dataType;
  51382. serializationObject.keys = [];
  51383. var keys = this.getKeys();
  51384. for (var index = 0; index < keys.length; index++) {
  51385. var animationKey = keys[index];
  51386. var key = {};
  51387. key.frame = animationKey.frame;
  51388. switch (dataType) {
  51389. case Animation.ANIMATIONTYPE_FLOAT:
  51390. key.values = [animationKey.value];
  51391. break;
  51392. case Animation.ANIMATIONTYPE_QUATERNION:
  51393. case Animation.ANIMATIONTYPE_MATRIX:
  51394. case Animation.ANIMATIONTYPE_VECTOR3:
  51395. case Animation.ANIMATIONTYPE_COLOR3:
  51396. key.values = animationKey.value.asArray();
  51397. break;
  51398. }
  51399. serializationObject.keys.push(key);
  51400. }
  51401. serializationObject.ranges = [];
  51402. for (var name in this._ranges) {
  51403. var source = this._ranges[name];
  51404. if (!source) {
  51405. continue;
  51406. }
  51407. var range = {};
  51408. range.name = name;
  51409. range.from = source.from;
  51410. range.to = source.to;
  51411. serializationObject.ranges.push(range);
  51412. }
  51413. return serializationObject;
  51414. };
  51415. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51416. /**
  51417. * Get the float animation type
  51418. */
  51419. get: function () {
  51420. return Animation._ANIMATIONTYPE_FLOAT;
  51421. },
  51422. enumerable: true,
  51423. configurable: true
  51424. });
  51425. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51426. /**
  51427. * Get the Vector3 animation type
  51428. */
  51429. get: function () {
  51430. return Animation._ANIMATIONTYPE_VECTOR3;
  51431. },
  51432. enumerable: true,
  51433. configurable: true
  51434. });
  51435. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51436. /**
  51437. * Get the Vectpr2 animation type
  51438. */
  51439. get: function () {
  51440. return Animation._ANIMATIONTYPE_VECTOR2;
  51441. },
  51442. enumerable: true,
  51443. configurable: true
  51444. });
  51445. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51446. /**
  51447. * Get the Size animation type
  51448. */
  51449. get: function () {
  51450. return Animation._ANIMATIONTYPE_SIZE;
  51451. },
  51452. enumerable: true,
  51453. configurable: true
  51454. });
  51455. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51456. /**
  51457. * Get the Quaternion animation type
  51458. */
  51459. get: function () {
  51460. return Animation._ANIMATIONTYPE_QUATERNION;
  51461. },
  51462. enumerable: true,
  51463. configurable: true
  51464. });
  51465. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51466. /**
  51467. * Get the Matrix animation type
  51468. */
  51469. get: function () {
  51470. return Animation._ANIMATIONTYPE_MATRIX;
  51471. },
  51472. enumerable: true,
  51473. configurable: true
  51474. });
  51475. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51476. /**
  51477. * Get the Color3 animation type
  51478. */
  51479. get: function () {
  51480. return Animation._ANIMATIONTYPE_COLOR3;
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51486. /**
  51487. * Get the Relative Loop Mode
  51488. */
  51489. get: function () {
  51490. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51491. },
  51492. enumerable: true,
  51493. configurable: true
  51494. });
  51495. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51496. /**
  51497. * Get the Cycle Loop Mode
  51498. */
  51499. get: function () {
  51500. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51506. /**
  51507. * Get the Constant Loop Mode
  51508. */
  51509. get: function () {
  51510. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51511. },
  51512. enumerable: true,
  51513. configurable: true
  51514. });
  51515. /** @hidden */
  51516. Animation._UniversalLerp = function (left, right, amount) {
  51517. var constructor = left.constructor;
  51518. if (constructor.Lerp) { // Lerp supported
  51519. return constructor.Lerp(left, right, amount);
  51520. }
  51521. else if (constructor.Slerp) { // Slerp supported
  51522. return constructor.Slerp(left, right, amount);
  51523. }
  51524. else if (left.toFixed) { // Number
  51525. return left * (1.0 - amount) + amount * right;
  51526. }
  51527. else { // Blending not supported
  51528. return right;
  51529. }
  51530. };
  51531. /**
  51532. * Parses an animation object and creates an animation
  51533. * @param parsedAnimation Parsed animation object
  51534. * @returns Animation object
  51535. */
  51536. Animation.Parse = function (parsedAnimation) {
  51537. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51538. var dataType = parsedAnimation.dataType;
  51539. var keys = [];
  51540. var data;
  51541. var index;
  51542. if (parsedAnimation.enableBlending) {
  51543. animation.enableBlending = parsedAnimation.enableBlending;
  51544. }
  51545. if (parsedAnimation.blendingSpeed) {
  51546. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51547. }
  51548. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51549. var key = parsedAnimation.keys[index];
  51550. var inTangent;
  51551. var outTangent;
  51552. switch (dataType) {
  51553. case Animation.ANIMATIONTYPE_FLOAT:
  51554. data = key.values[0];
  51555. if (key.values.length >= 1) {
  51556. inTangent = key.values[1];
  51557. }
  51558. if (key.values.length >= 2) {
  51559. outTangent = key.values[2];
  51560. }
  51561. break;
  51562. case Animation.ANIMATIONTYPE_QUATERNION:
  51563. data = BABYLON.Quaternion.FromArray(key.values);
  51564. if (key.values.length >= 8) {
  51565. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51566. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51567. inTangent = _inTangent;
  51568. }
  51569. }
  51570. if (key.values.length >= 12) {
  51571. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51572. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51573. outTangent = _outTangent;
  51574. }
  51575. }
  51576. break;
  51577. case Animation.ANIMATIONTYPE_MATRIX:
  51578. data = BABYLON.Matrix.FromArray(key.values);
  51579. break;
  51580. case Animation.ANIMATIONTYPE_COLOR3:
  51581. data = BABYLON.Color3.FromArray(key.values);
  51582. break;
  51583. case Animation.ANIMATIONTYPE_VECTOR3:
  51584. default:
  51585. data = BABYLON.Vector3.FromArray(key.values);
  51586. break;
  51587. }
  51588. var keyData = {};
  51589. keyData.frame = key.frame;
  51590. keyData.value = data;
  51591. if (inTangent != undefined) {
  51592. keyData.inTangent = inTangent;
  51593. }
  51594. if (outTangent != undefined) {
  51595. keyData.outTangent = outTangent;
  51596. }
  51597. keys.push(keyData);
  51598. }
  51599. animation.setKeys(keys);
  51600. if (parsedAnimation.ranges) {
  51601. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51602. data = parsedAnimation.ranges[index];
  51603. animation.createRange(data.name, data.from, data.to);
  51604. }
  51605. }
  51606. return animation;
  51607. };
  51608. /**
  51609. * Appends the serialized animations from the source animations
  51610. * @param source Source containing the animations
  51611. * @param destination Target to store the animations
  51612. */
  51613. Animation.AppendSerializedAnimations = function (source, destination) {
  51614. if (source.animations) {
  51615. destination.animations = [];
  51616. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51617. var animation = source.animations[animationIndex];
  51618. destination.animations.push(animation.serialize());
  51619. }
  51620. }
  51621. };
  51622. /**
  51623. * Use matrix interpolation instead of using direct key value when animating matrices
  51624. */
  51625. Animation.AllowMatricesInterpolation = false;
  51626. /**
  51627. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51628. */
  51629. Animation.AllowMatrixDecomposeForInterpolation = true;
  51630. // Statics
  51631. /**
  51632. * Float animation type
  51633. */
  51634. Animation._ANIMATIONTYPE_FLOAT = 0;
  51635. /**
  51636. * Vector3 animation type
  51637. */
  51638. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51639. /**
  51640. * Quaternion animation type
  51641. */
  51642. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51643. /**
  51644. * Matrix animation type
  51645. */
  51646. Animation._ANIMATIONTYPE_MATRIX = 3;
  51647. /**
  51648. * Color3 animation type
  51649. */
  51650. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51651. /**
  51652. * Vector2 animation type
  51653. */
  51654. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51655. /**
  51656. * Size animation type
  51657. */
  51658. Animation._ANIMATIONTYPE_SIZE = 6;
  51659. /**
  51660. * Relative Loop Mode
  51661. */
  51662. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51663. /**
  51664. * Cycle Loop Mode
  51665. */
  51666. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51667. /**
  51668. * Constant Loop Mode
  51669. */
  51670. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51671. return Animation;
  51672. }());
  51673. BABYLON.Animation = Animation;
  51674. })(BABYLON || (BABYLON = {}));
  51675. //# sourceMappingURL=babylon.animation.js.map
  51676. var BABYLON;
  51677. (function (BABYLON) {
  51678. /**
  51679. * This class defines the direct association between an animation and a target
  51680. */
  51681. var TargetedAnimation = /** @class */ (function () {
  51682. function TargetedAnimation() {
  51683. }
  51684. return TargetedAnimation;
  51685. }());
  51686. BABYLON.TargetedAnimation = TargetedAnimation;
  51687. /**
  51688. * Use this class to create coordinated animations on multiple targets
  51689. */
  51690. var AnimationGroup = /** @class */ (function () {
  51691. function AnimationGroup(name, scene) {
  51692. if (scene === void 0) { scene = null; }
  51693. this.name = name;
  51694. this._targetedAnimations = new Array();
  51695. this._animatables = new Array();
  51696. this._from = Number.MAX_VALUE;
  51697. this._to = -Number.MAX_VALUE;
  51698. this._speedRatio = 1;
  51699. this.onAnimationEndObservable = new BABYLON.Observable();
  51700. /**
  51701. * This observable will notify when all animations have ended.
  51702. */
  51703. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51704. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51705. this._scene.animationGroups.push(this);
  51706. }
  51707. Object.defineProperty(AnimationGroup.prototype, "from", {
  51708. /**
  51709. * Gets the first frame
  51710. */
  51711. get: function () {
  51712. return this._from;
  51713. },
  51714. enumerable: true,
  51715. configurable: true
  51716. });
  51717. Object.defineProperty(AnimationGroup.prototype, "to", {
  51718. /**
  51719. * Gets the last frame
  51720. */
  51721. get: function () {
  51722. return this._to;
  51723. },
  51724. enumerable: true,
  51725. configurable: true
  51726. });
  51727. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51728. /**
  51729. * Define if the animations are started
  51730. */
  51731. get: function () {
  51732. return this._isStarted;
  51733. },
  51734. enumerable: true,
  51735. configurable: true
  51736. });
  51737. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51738. /**
  51739. * Gets or sets the speed ratio to use for all animations
  51740. */
  51741. get: function () {
  51742. return this._speedRatio;
  51743. },
  51744. /**
  51745. * Gets or sets the speed ratio to use for all animations
  51746. */
  51747. set: function (value) {
  51748. if (this._speedRatio === value) {
  51749. return;
  51750. }
  51751. this._speedRatio = value;
  51752. for (var index = 0; index < this._animatables.length; index++) {
  51753. var animatable = this._animatables[index];
  51754. animatable.speedRatio = this._speedRatio;
  51755. }
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51761. /**
  51762. * Gets the targeted animations for this animation group
  51763. */
  51764. get: function () {
  51765. return this._targetedAnimations;
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51771. /**
  51772. * returning the list of animatables controlled by this animation group.
  51773. */
  51774. get: function () {
  51775. return this._animatables;
  51776. },
  51777. enumerable: true,
  51778. configurable: true
  51779. });
  51780. /**
  51781. * Add an animation (with its target) in the group
  51782. * @param animation defines the animation we want to add
  51783. * @param target defines the target of the animation
  51784. * @returns the {BABYLON.TargetedAnimation} object
  51785. */
  51786. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51787. var targetedAnimation = {
  51788. animation: animation,
  51789. target: target
  51790. };
  51791. var keys = animation.getKeys();
  51792. if (this._from > keys[0].frame) {
  51793. this._from = keys[0].frame;
  51794. }
  51795. if (this._to < keys[keys.length - 1].frame) {
  51796. this._to = keys[keys.length - 1].frame;
  51797. }
  51798. this._targetedAnimations.push(targetedAnimation);
  51799. return targetedAnimation;
  51800. };
  51801. /**
  51802. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51803. * It can add constant keys at begin or end
  51804. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51805. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51806. */
  51807. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51808. if (beginFrame === void 0) { beginFrame = null; }
  51809. if (endFrame === void 0) { endFrame = null; }
  51810. if (beginFrame == null)
  51811. beginFrame = this._from;
  51812. if (endFrame == null)
  51813. endFrame = this._to;
  51814. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51815. var targetedAnimation = this._targetedAnimations[index];
  51816. var keys = targetedAnimation.animation.getKeys();
  51817. var startKey = keys[0];
  51818. var endKey = keys[keys.length - 1];
  51819. if (startKey.frame > beginFrame) {
  51820. var newKey = {
  51821. frame: beginFrame,
  51822. value: startKey.value,
  51823. inTangent: startKey.inTangent,
  51824. outTangent: startKey.outTangent,
  51825. interpolation: startKey.interpolation
  51826. };
  51827. keys.splice(0, 0, newKey);
  51828. }
  51829. if (endKey.frame < endFrame) {
  51830. var newKey = {
  51831. frame: endFrame,
  51832. value: endKey.value,
  51833. inTangent: endKey.outTangent,
  51834. outTangent: endKey.outTangent,
  51835. interpolation: endKey.interpolation
  51836. };
  51837. keys.push(newKey);
  51838. }
  51839. }
  51840. this._from = beginFrame;
  51841. this._to = endFrame;
  51842. return this;
  51843. };
  51844. /**
  51845. * Start all animations on given targets
  51846. * @param loop defines if animations must loop
  51847. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51848. * @param from defines the from key (optional)
  51849. * @param to defines the to key (optional)
  51850. * @returns the current animation group
  51851. */
  51852. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51853. var _this = this;
  51854. if (loop === void 0) { loop = false; }
  51855. if (speedRatio === void 0) { speedRatio = 1; }
  51856. if (this._isStarted || this._targetedAnimations.length === 0) {
  51857. return this;
  51858. }
  51859. var _loop_1 = function (targetedAnimation) {
  51860. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51861. animatable.onAnimationEnd = function () {
  51862. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51863. _this._checkAnimationGroupEnded(animatable);
  51864. };
  51865. this_1._animatables.push(animatable);
  51866. };
  51867. var this_1 = this;
  51868. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51869. var targetedAnimation = _a[_i];
  51870. _loop_1(targetedAnimation);
  51871. }
  51872. this._speedRatio = speedRatio;
  51873. this._isStarted = true;
  51874. return this;
  51875. };
  51876. /**
  51877. * Pause all animations
  51878. */
  51879. AnimationGroup.prototype.pause = function () {
  51880. if (!this._isStarted) {
  51881. return this;
  51882. }
  51883. for (var index = 0; index < this._animatables.length; index++) {
  51884. var animatable = this._animatables[index];
  51885. animatable.pause();
  51886. }
  51887. return this;
  51888. };
  51889. /**
  51890. * Play all animations to initial state
  51891. * This function will start() the animations if they were not started or will restart() them if they were paused
  51892. * @param loop defines if animations must loop
  51893. */
  51894. AnimationGroup.prototype.play = function (loop) {
  51895. // only if all animatables are ready and exist
  51896. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51897. if (loop !== undefined) {
  51898. for (var index = 0; index < this._animatables.length; index++) {
  51899. var animatable = this._animatables[index];
  51900. animatable.loopAnimation = loop;
  51901. }
  51902. }
  51903. this.restart();
  51904. }
  51905. else {
  51906. this.stop();
  51907. this.start(loop, this._speedRatio);
  51908. }
  51909. return this;
  51910. };
  51911. /**
  51912. * Reset all animations to initial state
  51913. */
  51914. AnimationGroup.prototype.reset = function () {
  51915. if (!this._isStarted) {
  51916. return this;
  51917. }
  51918. for (var index = 0; index < this._animatables.length; index++) {
  51919. var animatable = this._animatables[index];
  51920. animatable.reset();
  51921. }
  51922. return this;
  51923. };
  51924. /**
  51925. * Restart animations from key 0
  51926. */
  51927. AnimationGroup.prototype.restart = function () {
  51928. if (!this._isStarted) {
  51929. return this;
  51930. }
  51931. for (var index = 0; index < this._animatables.length; index++) {
  51932. var animatable = this._animatables[index];
  51933. animatable.restart();
  51934. }
  51935. return this;
  51936. };
  51937. /**
  51938. * Stop all animations
  51939. */
  51940. AnimationGroup.prototype.stop = function () {
  51941. if (!this._isStarted) {
  51942. return this;
  51943. }
  51944. for (var index = 0; index < this._animatables.length; index++) {
  51945. var animatable = this._animatables[index];
  51946. animatable.stop();
  51947. }
  51948. this._isStarted = false;
  51949. return this;
  51950. };
  51951. /**
  51952. * Set animation weight for all animatables
  51953. * @param weight defines the weight to use
  51954. * @return the animationGroup
  51955. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51956. */
  51957. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51958. for (var index = 0; index < this._animatables.length; index++) {
  51959. var animatable = this._animatables[index];
  51960. animatable.weight = weight;
  51961. }
  51962. return this;
  51963. };
  51964. /**
  51965. * Synchronize and normalize all animatables with a source animatable
  51966. * @param root defines the root animatable to synchronize with
  51967. * @return the animationGroup
  51968. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51969. */
  51970. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51971. for (var index = 0; index < this._animatables.length; index++) {
  51972. var animatable = this._animatables[index];
  51973. animatable.syncWith(root);
  51974. }
  51975. return this;
  51976. };
  51977. /**
  51978. * Goes to a specific frame in this animation group
  51979. * @param frame the frame number to go to
  51980. * @return the animationGroup
  51981. */
  51982. AnimationGroup.prototype.goToFrame = function (frame) {
  51983. if (!this._isStarted) {
  51984. return this;
  51985. }
  51986. for (var index = 0; index < this._animatables.length; index++) {
  51987. var animatable = this._animatables[index];
  51988. animatable.goToFrame(frame);
  51989. }
  51990. return this;
  51991. };
  51992. /**
  51993. * Dispose all associated resources
  51994. */
  51995. AnimationGroup.prototype.dispose = function () {
  51996. this._targetedAnimations = [];
  51997. this._animatables = [];
  51998. var index = this._scene.animationGroups.indexOf(this);
  51999. if (index > -1) {
  52000. this._scene.animationGroups.splice(index, 1);
  52001. }
  52002. };
  52003. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  52004. // animatable should be taken out of the array
  52005. var idx = this._animatables.indexOf(animatable);
  52006. if (idx > -1) {
  52007. this._animatables.splice(idx, 1);
  52008. }
  52009. // all animatables were removed? animation group ended!
  52010. if (this._animatables.length === 0) {
  52011. this._isStarted = false;
  52012. this.onAnimationGroupEndObservable.notifyObservers(this);
  52013. }
  52014. };
  52015. return AnimationGroup;
  52016. }());
  52017. BABYLON.AnimationGroup = AnimationGroup;
  52018. })(BABYLON || (BABYLON = {}));
  52019. //# sourceMappingURL=babylon.animationGroup.js.map
  52020. var BABYLON;
  52021. (function (BABYLON) {
  52022. /**
  52023. * Defines a runtime animation
  52024. */
  52025. var RuntimeAnimation = /** @class */ (function () {
  52026. /**
  52027. * Create a new RuntimeAnimation object
  52028. * @param target defines the target of the animation
  52029. * @param animation defines the source animation object
  52030. * @param scene defines the hosting scene
  52031. * @param host defines the initiating Animatable
  52032. */
  52033. function RuntimeAnimation(target, animation, scene, host) {
  52034. var _this = this;
  52035. this._events = new Array();
  52036. /**
  52037. * The current frame of the runtime animation
  52038. */
  52039. this._currentFrame = 0;
  52040. /**
  52041. * The original value of the runtime animation
  52042. */
  52043. this._originalValue = new Array();
  52044. /**
  52045. * The offsets cache of the runtime animation
  52046. */
  52047. this._offsetsCache = {};
  52048. /**
  52049. * The high limits cache of the runtime animation
  52050. */
  52051. this._highLimitsCache = {};
  52052. /**
  52053. * Specifies if the runtime animation has been stopped
  52054. */
  52055. this._stopped = false;
  52056. /**
  52057. * The blending factor of the runtime animation
  52058. */
  52059. this._blendingFactor = 0;
  52060. /**
  52061. * The target path of the runtime animation
  52062. */
  52063. this._targetPath = "";
  52064. /**
  52065. * The weight of the runtime animation
  52066. */
  52067. this._weight = 1.0;
  52068. /**
  52069. * The ratio offset of the runtime animation
  52070. */
  52071. this._ratioOffset = 0;
  52072. /**
  52073. * The previous delay of the runtime animation
  52074. */
  52075. this._previousDelay = 0;
  52076. /**
  52077. * The previous ratio of the runtime animation
  52078. */
  52079. this._previousRatio = 0;
  52080. this._animation = animation;
  52081. this._target = target;
  52082. this._scene = scene;
  52083. this._host = host;
  52084. animation._runtimeAnimations.push(this);
  52085. // Cloning events locally
  52086. var events = animation.getEvents();
  52087. if (events && events.length > 0) {
  52088. events.forEach(function (e) {
  52089. _this._events.push(e._clone());
  52090. });
  52091. }
  52092. }
  52093. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  52094. /**
  52095. * Gets the current frame of the runtime animation
  52096. */
  52097. get: function () {
  52098. return this._currentFrame;
  52099. },
  52100. enumerable: true,
  52101. configurable: true
  52102. });
  52103. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  52104. /**
  52105. * Gets the weight of the runtime animation
  52106. */
  52107. get: function () {
  52108. return this._weight;
  52109. },
  52110. enumerable: true,
  52111. configurable: true
  52112. });
  52113. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  52114. /**
  52115. * Gets the current value of the runtime animation
  52116. */
  52117. get: function () {
  52118. return this._currentValue;
  52119. },
  52120. enumerable: true,
  52121. configurable: true
  52122. });
  52123. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  52124. /**
  52125. * Gets the target path of the runtime animation
  52126. */
  52127. get: function () {
  52128. return this._targetPath;
  52129. },
  52130. enumerable: true,
  52131. configurable: true
  52132. });
  52133. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  52134. /**
  52135. * Gets the actual target of the runtime animation
  52136. */
  52137. get: function () {
  52138. return this._activeTarget;
  52139. },
  52140. enumerable: true,
  52141. configurable: true
  52142. });
  52143. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  52144. /**
  52145. * Gets the animation from the runtime animation
  52146. */
  52147. get: function () {
  52148. return this._animation;
  52149. },
  52150. enumerable: true,
  52151. configurable: true
  52152. });
  52153. /**
  52154. * Resets the runtime animation to the beginning
  52155. * @param restoreOriginal defines whether to restore the target property to the original value
  52156. */
  52157. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  52158. if (restoreOriginal === void 0) { restoreOriginal = false; }
  52159. if (restoreOriginal) {
  52160. if (this._target instanceof Array) {
  52161. var index = 0;
  52162. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52163. var target = _a[_i];
  52164. if (this._originalValue[index] !== undefined) {
  52165. this._setValue(target, this._originalValue[index], -1);
  52166. }
  52167. index++;
  52168. }
  52169. }
  52170. else {
  52171. if (this._originalValue[0] !== undefined) {
  52172. this._setValue(this._target, this._originalValue[0], -1);
  52173. }
  52174. }
  52175. }
  52176. this._offsetsCache = {};
  52177. this._highLimitsCache = {};
  52178. this._currentFrame = 0;
  52179. this._blendingFactor = 0;
  52180. this._originalValue = new Array();
  52181. // Events
  52182. for (var index = 0; index < this._events.length; index++) {
  52183. this._events[index].isDone = false;
  52184. }
  52185. };
  52186. /**
  52187. * Specifies if the runtime animation is stopped
  52188. * @returns Boolean specifying if the runtime animation is stopped
  52189. */
  52190. RuntimeAnimation.prototype.isStopped = function () {
  52191. return this._stopped;
  52192. };
  52193. /**
  52194. * Disposes of the runtime animation
  52195. */
  52196. RuntimeAnimation.prototype.dispose = function () {
  52197. var index = this._animation.runtimeAnimations.indexOf(this);
  52198. if (index > -1) {
  52199. this._animation.runtimeAnimations.splice(index, 1);
  52200. }
  52201. };
  52202. /**
  52203. * Interpolates the animation from the current frame
  52204. * @param currentFrame The frame to interpolate the animation to
  52205. * @param repeatCount The number of times that the animation should loop
  52206. * @param loopMode The type of looping mode to use
  52207. * @param offsetValue Animation offset value
  52208. * @param highLimitValue The high limit value
  52209. * @returns The interpolated value
  52210. */
  52211. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  52212. this._currentFrame = currentFrame;
  52213. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  52214. this._workValue = BABYLON.Matrix.Zero();
  52215. }
  52216. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  52217. };
  52218. /**
  52219. * Apply the interpolated value to the target
  52220. * @param currentValue defines the value computed by the animation
  52221. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  52222. */
  52223. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  52224. if (weight === void 0) { weight = 1.0; }
  52225. if (this._target instanceof Array) {
  52226. var index = 0;
  52227. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  52228. var target = _a[_i];
  52229. this._setValue(target, currentValue, weight, index);
  52230. index++;
  52231. }
  52232. }
  52233. else {
  52234. this._setValue(this._target, currentValue, weight);
  52235. }
  52236. };
  52237. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  52238. if (targetIndex === void 0) { targetIndex = 0; }
  52239. // Set value
  52240. var path;
  52241. var destination;
  52242. var targetPropertyPath = this._animation.targetPropertyPath;
  52243. if (targetPropertyPath.length > 1) {
  52244. var property = target[targetPropertyPath[0]];
  52245. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  52246. property = property[targetPropertyPath[index]];
  52247. }
  52248. path = targetPropertyPath[targetPropertyPath.length - 1];
  52249. destination = property;
  52250. }
  52251. else {
  52252. path = targetPropertyPath[0];
  52253. destination = target;
  52254. }
  52255. this._targetPath = path;
  52256. this._activeTarget = destination;
  52257. this._weight = weight;
  52258. if (this._originalValue[targetIndex] === undefined) {
  52259. var originalValue = void 0;
  52260. if (destination.getRestPose && path === "_matrix") { // For bones
  52261. originalValue = destination.getRestPose();
  52262. }
  52263. else {
  52264. originalValue = destination[path];
  52265. }
  52266. if (originalValue && originalValue.clone) {
  52267. this._originalValue[targetIndex] = originalValue.clone();
  52268. }
  52269. else {
  52270. this._originalValue[targetIndex] = originalValue;
  52271. }
  52272. }
  52273. // Blending
  52274. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  52275. if (enableBlending && this._blendingFactor <= 1.0) {
  52276. if (!this._originalBlendValue) {
  52277. var originalValue = destination[path];
  52278. if (originalValue.clone) {
  52279. this._originalBlendValue = originalValue.clone();
  52280. }
  52281. else {
  52282. this._originalBlendValue = originalValue;
  52283. }
  52284. }
  52285. if (this._originalBlendValue.m) { // Matrix
  52286. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  52287. if (this._currentValue) {
  52288. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52289. }
  52290. else {
  52291. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52292. }
  52293. }
  52294. else {
  52295. if (this._currentValue) {
  52296. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  52297. }
  52298. else {
  52299. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52300. }
  52301. }
  52302. }
  52303. else {
  52304. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  52305. }
  52306. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  52307. this._blendingFactor += blendingSpeed;
  52308. }
  52309. else {
  52310. this._currentValue = currentValue;
  52311. }
  52312. if (weight !== -1.0) {
  52313. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  52314. }
  52315. else {
  52316. destination[path] = this._currentValue;
  52317. }
  52318. if (target.markAsDirty) {
  52319. target.markAsDirty(this._animation.targetProperty);
  52320. }
  52321. };
  52322. /**
  52323. * Gets the loop pmode of the runtime animation
  52324. * @returns Loop Mode
  52325. */
  52326. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  52327. if (this._target && this._target.animationPropertiesOverride) {
  52328. return this._target.animationPropertiesOverride.loopMode;
  52329. }
  52330. return this._animation.loopMode;
  52331. };
  52332. /**
  52333. * Move the current animation to a given frame
  52334. * @param frame defines the frame to move to
  52335. */
  52336. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52337. var keys = this._animation.getKeys();
  52338. if (frame < keys[0].frame) {
  52339. frame = keys[0].frame;
  52340. }
  52341. else if (frame > keys[keys.length - 1].frame) {
  52342. frame = keys[keys.length - 1].frame;
  52343. }
  52344. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52345. this.setValue(currentValue, -1);
  52346. };
  52347. /**
  52348. * @hidden Internal use only
  52349. */
  52350. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52351. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52352. this._ratioOffset = this._previousRatio - newRatio;
  52353. };
  52354. /**
  52355. * Execute the current animation
  52356. * @param delay defines the delay to add to the current frame
  52357. * @param from defines the lower bound of the animation range
  52358. * @param to defines the upper bound of the animation range
  52359. * @param loop defines if the current animation must loop
  52360. * @param speedRatio defines the current speed ratio
  52361. * @param weight defines the weight of the animation (default is -1 so no weight)
  52362. * @returns a boolean indicating if the animation has ended
  52363. */
  52364. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52365. if (weight === void 0) { weight = -1.0; }
  52366. var targetPropertyPath = this._animation.targetPropertyPath;
  52367. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52368. this._stopped = true;
  52369. return false;
  52370. }
  52371. var returnValue = true;
  52372. var keys = this._animation.getKeys();
  52373. // Adding a start key at frame 0 if missing
  52374. if (keys[0].frame !== 0) {
  52375. var newKey = { frame: 0, value: keys[0].value };
  52376. keys.splice(0, 0, newKey);
  52377. }
  52378. // Check limits
  52379. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52380. from = keys[0].frame;
  52381. }
  52382. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52383. to = keys[keys.length - 1].frame;
  52384. }
  52385. //to and from cannot be the same key
  52386. if (from === to) {
  52387. if (from > keys[0].frame) {
  52388. from--;
  52389. }
  52390. else if (to < keys[keys.length - 1].frame) {
  52391. to++;
  52392. }
  52393. }
  52394. // Compute ratio
  52395. var range = to - from;
  52396. var offsetValue;
  52397. // ratio represents the frame delta between from and to
  52398. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52399. var highLimitValue = 0;
  52400. this._previousDelay = delay;
  52401. this._previousRatio = ratio;
  52402. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52403. returnValue = false;
  52404. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52405. }
  52406. else {
  52407. // Get max value if required
  52408. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52409. var keyOffset = to.toString() + from.toString();
  52410. if (!this._offsetsCache[keyOffset]) {
  52411. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52412. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52413. switch (this._animation.dataType) {
  52414. // Float
  52415. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52416. this._offsetsCache[keyOffset] = toValue - fromValue;
  52417. break;
  52418. // Quaternion
  52419. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52420. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52421. break;
  52422. // Vector3
  52423. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52424. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52425. // Vector2
  52426. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52427. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52428. // Size
  52429. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52430. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52431. // Color3
  52432. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52433. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52434. default:
  52435. break;
  52436. }
  52437. this._highLimitsCache[keyOffset] = toValue;
  52438. }
  52439. highLimitValue = this._highLimitsCache[keyOffset];
  52440. offsetValue = this._offsetsCache[keyOffset];
  52441. }
  52442. }
  52443. if (offsetValue === undefined) {
  52444. switch (this._animation.dataType) {
  52445. // Float
  52446. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52447. offsetValue = 0;
  52448. break;
  52449. // Quaternion
  52450. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52451. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52452. break;
  52453. // Vector3
  52454. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52455. offsetValue = BABYLON.Vector3.Zero();
  52456. break;
  52457. // Vector2
  52458. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52459. offsetValue = BABYLON.Vector2.Zero();
  52460. break;
  52461. // Size
  52462. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52463. offsetValue = BABYLON.Size.Zero();
  52464. break;
  52465. // Color3
  52466. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52467. offsetValue = BABYLON.Color3.Black();
  52468. }
  52469. }
  52470. // Compute value
  52471. var repeatCount = (ratio / range) >> 0;
  52472. var currentFrame = returnValue ? from + ratio % range : to;
  52473. // Need to normalize?
  52474. if (this._host && this._host.syncRoot) {
  52475. var syncRoot = this._host.syncRoot;
  52476. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52477. currentFrame = from + (to - from) * hostNormalizedFrame;
  52478. }
  52479. // Reset events if looping
  52480. var events = this._events;
  52481. if (range > 0 && this.currentFrame > currentFrame ||
  52482. range < 0 && this.currentFrame < currentFrame) {
  52483. // Need to reset animation events
  52484. for (var index = 0; index < events.length; index++) {
  52485. if (!events[index].onlyOnce) {
  52486. // reset event, the animation is looping
  52487. events[index].isDone = false;
  52488. }
  52489. }
  52490. }
  52491. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52492. // Set value
  52493. this.setValue(currentValue, weight);
  52494. // Check events
  52495. for (var index = 0; index < events.length; index++) {
  52496. // Make sure current frame has passed event frame and that event frame is within the current range
  52497. // Also, handle both forward and reverse animations
  52498. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52499. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52500. var event = events[index];
  52501. if (!event.isDone) {
  52502. // If event should be done only once, remove it.
  52503. if (event.onlyOnce) {
  52504. events.splice(index, 1);
  52505. index--;
  52506. }
  52507. event.isDone = true;
  52508. event.action();
  52509. } // Don't do anything if the event has already be done.
  52510. }
  52511. }
  52512. if (!returnValue) {
  52513. this._stopped = true;
  52514. }
  52515. return returnValue;
  52516. };
  52517. return RuntimeAnimation;
  52518. }());
  52519. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52520. })(BABYLON || (BABYLON = {}));
  52521. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52522. var BABYLON;
  52523. (function (BABYLON) {
  52524. var Animatable = /** @class */ (function () {
  52525. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52526. if (fromFrame === void 0) { fromFrame = 0; }
  52527. if (toFrame === void 0) { toFrame = 100; }
  52528. if (loopAnimation === void 0) { loopAnimation = false; }
  52529. if (speedRatio === void 0) { speedRatio = 1.0; }
  52530. this.target = target;
  52531. this.fromFrame = fromFrame;
  52532. this.toFrame = toFrame;
  52533. this.loopAnimation = loopAnimation;
  52534. this.onAnimationEnd = onAnimationEnd;
  52535. this._localDelayOffset = null;
  52536. this._pausedDelay = null;
  52537. this._runtimeAnimations = new Array();
  52538. this._paused = false;
  52539. this._speedRatio = 1;
  52540. this._weight = -1.0;
  52541. this.animationStarted = false;
  52542. /**
  52543. * Observer raised when the animation ends
  52544. */
  52545. this.onAnimationEndObservable = new BABYLON.Observable();
  52546. this._scene = scene;
  52547. if (animations) {
  52548. this.appendAnimations(target, animations);
  52549. }
  52550. this._speedRatio = speedRatio;
  52551. scene._activeAnimatables.push(this);
  52552. }
  52553. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52554. /**
  52555. * Gets the root Animatable used to synchronize and normalize animations
  52556. */
  52557. get: function () {
  52558. return this._syncRoot;
  52559. },
  52560. enumerable: true,
  52561. configurable: true
  52562. });
  52563. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52564. /**
  52565. * Gets the current frame of the first RuntimeAnimation
  52566. * Used to synchronize Animatables
  52567. */
  52568. get: function () {
  52569. if (this._runtimeAnimations.length === 0) {
  52570. return 0;
  52571. }
  52572. return this._runtimeAnimations[0].currentFrame;
  52573. },
  52574. enumerable: true,
  52575. configurable: true
  52576. });
  52577. Object.defineProperty(Animatable.prototype, "weight", {
  52578. /**
  52579. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52580. */
  52581. get: function () {
  52582. return this._weight;
  52583. },
  52584. set: function (value) {
  52585. if (value === -1) { // -1 is ok and means no weight
  52586. this._weight = -1;
  52587. return;
  52588. }
  52589. // Else weight must be in [0, 1] range
  52590. this._weight = Math.min(Math.max(value, 0), 1.0);
  52591. },
  52592. enumerable: true,
  52593. configurable: true
  52594. });
  52595. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52596. /**
  52597. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52598. */
  52599. get: function () {
  52600. return this._speedRatio;
  52601. },
  52602. set: function (value) {
  52603. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52604. var animation = this._runtimeAnimations[index];
  52605. animation._prepareForSpeedRatioChange(value);
  52606. }
  52607. this._speedRatio = value;
  52608. },
  52609. enumerable: true,
  52610. configurable: true
  52611. });
  52612. // Methods
  52613. /**
  52614. * Synchronize and normalize current Animatable with a source Animatable
  52615. * This is useful when using animation weights and when animations are not of the same length
  52616. * @param root defines the root Animatable to synchronize with
  52617. * @returns the current Animatable
  52618. */
  52619. Animatable.prototype.syncWith = function (root) {
  52620. this._syncRoot = root;
  52621. if (root) {
  52622. // Make sure this animatable will animate after the root
  52623. var index = this._scene._activeAnimatables.indexOf(this);
  52624. if (index > -1) {
  52625. this._scene._activeAnimatables.splice(index, 1);
  52626. this._scene._activeAnimatables.push(this);
  52627. }
  52628. }
  52629. return this;
  52630. };
  52631. Animatable.prototype.getAnimations = function () {
  52632. return this._runtimeAnimations;
  52633. };
  52634. Animatable.prototype.appendAnimations = function (target, animations) {
  52635. for (var index = 0; index < animations.length; index++) {
  52636. var animation = animations[index];
  52637. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52638. }
  52639. };
  52640. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52641. var runtimeAnimations = this._runtimeAnimations;
  52642. for (var index = 0; index < runtimeAnimations.length; index++) {
  52643. if (runtimeAnimations[index].animation.targetProperty === property) {
  52644. return runtimeAnimations[index].animation;
  52645. }
  52646. }
  52647. return null;
  52648. };
  52649. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52650. var runtimeAnimations = this._runtimeAnimations;
  52651. for (var index = 0; index < runtimeAnimations.length; index++) {
  52652. if (runtimeAnimations[index].animation.targetProperty === property) {
  52653. return runtimeAnimations[index];
  52654. }
  52655. }
  52656. return null;
  52657. };
  52658. Animatable.prototype.reset = function () {
  52659. var runtimeAnimations = this._runtimeAnimations;
  52660. for (var index = 0; index < runtimeAnimations.length; index++) {
  52661. runtimeAnimations[index].reset(true);
  52662. }
  52663. this._localDelayOffset = null;
  52664. this._pausedDelay = null;
  52665. };
  52666. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52667. var runtimeAnimations = this._runtimeAnimations;
  52668. for (var index = 0; index < runtimeAnimations.length; index++) {
  52669. runtimeAnimations[index].animation.enableBlending = true;
  52670. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52671. }
  52672. };
  52673. Animatable.prototype.disableBlending = function () {
  52674. var runtimeAnimations = this._runtimeAnimations;
  52675. for (var index = 0; index < runtimeAnimations.length; index++) {
  52676. runtimeAnimations[index].animation.enableBlending = false;
  52677. }
  52678. };
  52679. Animatable.prototype.goToFrame = function (frame) {
  52680. var runtimeAnimations = this._runtimeAnimations;
  52681. if (runtimeAnimations[0]) {
  52682. var fps = runtimeAnimations[0].animation.framePerSecond;
  52683. var currentFrame = runtimeAnimations[0].currentFrame;
  52684. var adjustTime = frame - currentFrame;
  52685. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52686. if (this._localDelayOffset === null) {
  52687. this._localDelayOffset = 0;
  52688. }
  52689. this._localDelayOffset -= delay;
  52690. }
  52691. for (var index = 0; index < runtimeAnimations.length; index++) {
  52692. runtimeAnimations[index].goToFrame(frame);
  52693. }
  52694. };
  52695. Animatable.prototype.pause = function () {
  52696. if (this._paused) {
  52697. return;
  52698. }
  52699. this._paused = true;
  52700. };
  52701. Animatable.prototype.restart = function () {
  52702. this._paused = false;
  52703. };
  52704. Animatable.prototype._raiseOnAnimationEnd = function () {
  52705. if (this.onAnimationEnd) {
  52706. this.onAnimationEnd();
  52707. }
  52708. this.onAnimationEndObservable.notifyObservers(this);
  52709. };
  52710. Animatable.prototype.stop = function (animationName) {
  52711. if (animationName) {
  52712. var idx = this._scene._activeAnimatables.indexOf(this);
  52713. if (idx > -1) {
  52714. var runtimeAnimations = this._runtimeAnimations;
  52715. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52716. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52717. continue;
  52718. }
  52719. runtimeAnimations[index].dispose();
  52720. runtimeAnimations.splice(index, 1);
  52721. }
  52722. if (runtimeAnimations.length == 0) {
  52723. this._scene._activeAnimatables.splice(idx, 1);
  52724. this._raiseOnAnimationEnd();
  52725. }
  52726. }
  52727. }
  52728. else {
  52729. var index = this._scene._activeAnimatables.indexOf(this);
  52730. if (index > -1) {
  52731. this._scene._activeAnimatables.splice(index, 1);
  52732. var runtimeAnimations = this._runtimeAnimations;
  52733. for (var index = 0; index < runtimeAnimations.length; index++) {
  52734. runtimeAnimations[index].dispose();
  52735. }
  52736. this._raiseOnAnimationEnd();
  52737. }
  52738. }
  52739. };
  52740. /**
  52741. * Wait asynchronously for the animation to end
  52742. * @returns a promise which will be fullfilled when the animation ends
  52743. */
  52744. Animatable.prototype.waitAsync = function () {
  52745. var _this = this;
  52746. return new Promise(function (resolve, reject) {
  52747. _this.onAnimationEndObservable.add(function () {
  52748. resolve(_this);
  52749. }, undefined, undefined, _this, true);
  52750. });
  52751. };
  52752. /** @hidden */
  52753. Animatable.prototype._animate = function (delay) {
  52754. if (this._paused) {
  52755. this.animationStarted = false;
  52756. if (this._pausedDelay === null) {
  52757. this._pausedDelay = delay;
  52758. }
  52759. return true;
  52760. }
  52761. if (this._localDelayOffset === null) {
  52762. this._localDelayOffset = delay;
  52763. this._pausedDelay = null;
  52764. }
  52765. else if (this._pausedDelay !== null) {
  52766. this._localDelayOffset += delay - this._pausedDelay;
  52767. this._pausedDelay = null;
  52768. }
  52769. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52770. return true;
  52771. }
  52772. // Animating
  52773. var running = false;
  52774. var runtimeAnimations = this._runtimeAnimations;
  52775. var index;
  52776. for (index = 0; index < runtimeAnimations.length; index++) {
  52777. var animation = runtimeAnimations[index];
  52778. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52779. running = running || isRunning;
  52780. }
  52781. this.animationStarted = running;
  52782. if (!running) {
  52783. // Remove from active animatables
  52784. index = this._scene._activeAnimatables.indexOf(this);
  52785. this._scene._activeAnimatables.splice(index, 1);
  52786. // Dispose all runtime animations
  52787. for (index = 0; index < runtimeAnimations.length; index++) {
  52788. runtimeAnimations[index].dispose();
  52789. }
  52790. this._raiseOnAnimationEnd();
  52791. this.onAnimationEnd = null;
  52792. this.onAnimationEndObservable.clear();
  52793. }
  52794. return running;
  52795. };
  52796. return Animatable;
  52797. }());
  52798. BABYLON.Animatable = Animatable;
  52799. })(BABYLON || (BABYLON = {}));
  52800. //# sourceMappingURL=babylon.animatable.js.map
  52801. var BABYLON;
  52802. (function (BABYLON) {
  52803. var EasingFunction = /** @class */ (function () {
  52804. function EasingFunction() {
  52805. // Properties
  52806. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52807. }
  52808. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52809. get: function () {
  52810. return EasingFunction._EASINGMODE_EASEIN;
  52811. },
  52812. enumerable: true,
  52813. configurable: true
  52814. });
  52815. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52816. get: function () {
  52817. return EasingFunction._EASINGMODE_EASEOUT;
  52818. },
  52819. enumerable: true,
  52820. configurable: true
  52821. });
  52822. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52823. get: function () {
  52824. return EasingFunction._EASINGMODE_EASEINOUT;
  52825. },
  52826. enumerable: true,
  52827. configurable: true
  52828. });
  52829. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52830. var n = Math.min(Math.max(easingMode, 0), 2);
  52831. this._easingMode = n;
  52832. };
  52833. EasingFunction.prototype.getEasingMode = function () {
  52834. return this._easingMode;
  52835. };
  52836. EasingFunction.prototype.easeInCore = function (gradient) {
  52837. throw new Error('You must implement this method');
  52838. };
  52839. EasingFunction.prototype.ease = function (gradient) {
  52840. switch (this._easingMode) {
  52841. case EasingFunction.EASINGMODE_EASEIN:
  52842. return this.easeInCore(gradient);
  52843. case EasingFunction.EASINGMODE_EASEOUT:
  52844. return (1 - this.easeInCore(1 - gradient));
  52845. }
  52846. if (gradient >= 0.5) {
  52847. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52848. }
  52849. return (this.easeInCore(gradient * 2) * 0.5);
  52850. };
  52851. //Statics
  52852. EasingFunction._EASINGMODE_EASEIN = 0;
  52853. EasingFunction._EASINGMODE_EASEOUT = 1;
  52854. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52855. return EasingFunction;
  52856. }());
  52857. BABYLON.EasingFunction = EasingFunction;
  52858. var CircleEase = /** @class */ (function (_super) {
  52859. __extends(CircleEase, _super);
  52860. function CircleEase() {
  52861. return _super !== null && _super.apply(this, arguments) || this;
  52862. }
  52863. CircleEase.prototype.easeInCore = function (gradient) {
  52864. gradient = Math.max(0, Math.min(1, gradient));
  52865. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52866. };
  52867. return CircleEase;
  52868. }(EasingFunction));
  52869. BABYLON.CircleEase = CircleEase;
  52870. var BackEase = /** @class */ (function (_super) {
  52871. __extends(BackEase, _super);
  52872. function BackEase(amplitude) {
  52873. if (amplitude === void 0) { amplitude = 1; }
  52874. var _this = _super.call(this) || this;
  52875. _this.amplitude = amplitude;
  52876. return _this;
  52877. }
  52878. BackEase.prototype.easeInCore = function (gradient) {
  52879. var num = Math.max(0, this.amplitude);
  52880. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52881. };
  52882. return BackEase;
  52883. }(EasingFunction));
  52884. BABYLON.BackEase = BackEase;
  52885. var BounceEase = /** @class */ (function (_super) {
  52886. __extends(BounceEase, _super);
  52887. function BounceEase(bounces, bounciness) {
  52888. if (bounces === void 0) { bounces = 3; }
  52889. if (bounciness === void 0) { bounciness = 2; }
  52890. var _this = _super.call(this) || this;
  52891. _this.bounces = bounces;
  52892. _this.bounciness = bounciness;
  52893. return _this;
  52894. }
  52895. BounceEase.prototype.easeInCore = function (gradient) {
  52896. var y = Math.max(0.0, this.bounces);
  52897. var bounciness = this.bounciness;
  52898. if (bounciness <= 1.0) {
  52899. bounciness = 1.001;
  52900. }
  52901. var num9 = Math.pow(bounciness, y);
  52902. var num5 = 1.0 - bounciness;
  52903. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52904. var num15 = gradient * num4;
  52905. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52906. var num3 = Math.floor(num65);
  52907. var num13 = num3 + 1.0;
  52908. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52909. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52910. var num7 = (num8 + num12) * 0.5;
  52911. var num6 = gradient - num7;
  52912. var num2 = num7 - num8;
  52913. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52914. };
  52915. return BounceEase;
  52916. }(EasingFunction));
  52917. BABYLON.BounceEase = BounceEase;
  52918. var CubicEase = /** @class */ (function (_super) {
  52919. __extends(CubicEase, _super);
  52920. function CubicEase() {
  52921. return _super !== null && _super.apply(this, arguments) || this;
  52922. }
  52923. CubicEase.prototype.easeInCore = function (gradient) {
  52924. return (gradient * gradient * gradient);
  52925. };
  52926. return CubicEase;
  52927. }(EasingFunction));
  52928. BABYLON.CubicEase = CubicEase;
  52929. var ElasticEase = /** @class */ (function (_super) {
  52930. __extends(ElasticEase, _super);
  52931. function ElasticEase(oscillations, springiness) {
  52932. if (oscillations === void 0) { oscillations = 3; }
  52933. if (springiness === void 0) { springiness = 3; }
  52934. var _this = _super.call(this) || this;
  52935. _this.oscillations = oscillations;
  52936. _this.springiness = springiness;
  52937. return _this;
  52938. }
  52939. ElasticEase.prototype.easeInCore = function (gradient) {
  52940. var num2;
  52941. var num3 = Math.max(0.0, this.oscillations);
  52942. var num = Math.max(0.0, this.springiness);
  52943. if (num == 0) {
  52944. num2 = gradient;
  52945. }
  52946. else {
  52947. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52948. }
  52949. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52950. };
  52951. return ElasticEase;
  52952. }(EasingFunction));
  52953. BABYLON.ElasticEase = ElasticEase;
  52954. var ExponentialEase = /** @class */ (function (_super) {
  52955. __extends(ExponentialEase, _super);
  52956. function ExponentialEase(exponent) {
  52957. if (exponent === void 0) { exponent = 2; }
  52958. var _this = _super.call(this) || this;
  52959. _this.exponent = exponent;
  52960. return _this;
  52961. }
  52962. ExponentialEase.prototype.easeInCore = function (gradient) {
  52963. if (this.exponent <= 0) {
  52964. return gradient;
  52965. }
  52966. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52967. };
  52968. return ExponentialEase;
  52969. }(EasingFunction));
  52970. BABYLON.ExponentialEase = ExponentialEase;
  52971. var PowerEase = /** @class */ (function (_super) {
  52972. __extends(PowerEase, _super);
  52973. function PowerEase(power) {
  52974. if (power === void 0) { power = 2; }
  52975. var _this = _super.call(this) || this;
  52976. _this.power = power;
  52977. return _this;
  52978. }
  52979. PowerEase.prototype.easeInCore = function (gradient) {
  52980. var y = Math.max(0.0, this.power);
  52981. return Math.pow(gradient, y);
  52982. };
  52983. return PowerEase;
  52984. }(EasingFunction));
  52985. BABYLON.PowerEase = PowerEase;
  52986. var QuadraticEase = /** @class */ (function (_super) {
  52987. __extends(QuadraticEase, _super);
  52988. function QuadraticEase() {
  52989. return _super !== null && _super.apply(this, arguments) || this;
  52990. }
  52991. QuadraticEase.prototype.easeInCore = function (gradient) {
  52992. return (gradient * gradient);
  52993. };
  52994. return QuadraticEase;
  52995. }(EasingFunction));
  52996. BABYLON.QuadraticEase = QuadraticEase;
  52997. var QuarticEase = /** @class */ (function (_super) {
  52998. __extends(QuarticEase, _super);
  52999. function QuarticEase() {
  53000. return _super !== null && _super.apply(this, arguments) || this;
  53001. }
  53002. QuarticEase.prototype.easeInCore = function (gradient) {
  53003. return (gradient * gradient * gradient * gradient);
  53004. };
  53005. return QuarticEase;
  53006. }(EasingFunction));
  53007. BABYLON.QuarticEase = QuarticEase;
  53008. var QuinticEase = /** @class */ (function (_super) {
  53009. __extends(QuinticEase, _super);
  53010. function QuinticEase() {
  53011. return _super !== null && _super.apply(this, arguments) || this;
  53012. }
  53013. QuinticEase.prototype.easeInCore = function (gradient) {
  53014. return (gradient * gradient * gradient * gradient * gradient);
  53015. };
  53016. return QuinticEase;
  53017. }(EasingFunction));
  53018. BABYLON.QuinticEase = QuinticEase;
  53019. var SineEase = /** @class */ (function (_super) {
  53020. __extends(SineEase, _super);
  53021. function SineEase() {
  53022. return _super !== null && _super.apply(this, arguments) || this;
  53023. }
  53024. SineEase.prototype.easeInCore = function (gradient) {
  53025. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  53026. };
  53027. return SineEase;
  53028. }(EasingFunction));
  53029. BABYLON.SineEase = SineEase;
  53030. var BezierCurveEase = /** @class */ (function (_super) {
  53031. __extends(BezierCurveEase, _super);
  53032. function BezierCurveEase(x1, y1, x2, y2) {
  53033. if (x1 === void 0) { x1 = 0; }
  53034. if (y1 === void 0) { y1 = 0; }
  53035. if (x2 === void 0) { x2 = 1; }
  53036. if (y2 === void 0) { y2 = 1; }
  53037. var _this = _super.call(this) || this;
  53038. _this.x1 = x1;
  53039. _this.y1 = y1;
  53040. _this.x2 = x2;
  53041. _this.y2 = y2;
  53042. return _this;
  53043. }
  53044. BezierCurveEase.prototype.easeInCore = function (gradient) {
  53045. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  53046. };
  53047. return BezierCurveEase;
  53048. }(EasingFunction));
  53049. BABYLON.BezierCurveEase = BezierCurveEase;
  53050. })(BABYLON || (BABYLON = {}));
  53051. //# sourceMappingURL=babylon.easing.js.map
  53052. var BABYLON;
  53053. (function (BABYLON) {
  53054. /**
  53055. * A Condition applied to an Action
  53056. */
  53057. var Condition = /** @class */ (function () {
  53058. /**
  53059. * Creates a new Condition
  53060. * @param actionManager the manager of the action the condition is applied to
  53061. */
  53062. function Condition(actionManager) {
  53063. this._actionManager = actionManager;
  53064. }
  53065. /**
  53066. * Check if the current condition is valid
  53067. * @returns a boolean
  53068. */
  53069. Condition.prototype.isValid = function () {
  53070. return true;
  53071. };
  53072. /**
  53073. * Internal only
  53074. * @hidden
  53075. */
  53076. Condition.prototype._getProperty = function (propertyPath) {
  53077. return this._actionManager._getProperty(propertyPath);
  53078. };
  53079. /**
  53080. * Internal only
  53081. * @hidden
  53082. */
  53083. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  53084. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53085. };
  53086. /**
  53087. * Serialize placeholder for child classes
  53088. * @returns the serialized object
  53089. */
  53090. Condition.prototype.serialize = function () {
  53091. };
  53092. /**
  53093. * Internal only
  53094. * @hidden
  53095. */
  53096. Condition.prototype._serialize = function (serializedCondition) {
  53097. return {
  53098. type: 2,
  53099. children: [],
  53100. name: serializedCondition.name,
  53101. properties: serializedCondition.properties
  53102. };
  53103. };
  53104. return Condition;
  53105. }());
  53106. BABYLON.Condition = Condition;
  53107. /**
  53108. * Defines specific conditional operators as extensions of Condition
  53109. */
  53110. var ValueCondition = /** @class */ (function (_super) {
  53111. __extends(ValueCondition, _super);
  53112. /**
  53113. * Creates a new ValueCondition
  53114. * @param actionManager manager for the action the condition applies to
  53115. * @param target for the action
  53116. * @param propertyPath path to specify the property of the target the conditional operator uses
  53117. * @param value the value compared by the conditional operator against the current value of the property
  53118. * @param operator the conditional operator, default ValueCondition.IsEqual
  53119. */
  53120. function ValueCondition(actionManager, target,
  53121. /** path to specify the property of the target the conditional operator uses */
  53122. propertyPath,
  53123. /** the value compared by the conditional operator against the current value of the property */
  53124. value,
  53125. /** the conditional operator, default ValueCondition.IsEqual */
  53126. operator) {
  53127. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53128. var _this = _super.call(this, actionManager) || this;
  53129. _this.propertyPath = propertyPath;
  53130. _this.value = value;
  53131. _this.operator = operator;
  53132. _this._target = target;
  53133. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53134. _this._property = _this._getProperty(_this.propertyPath);
  53135. return _this;
  53136. }
  53137. Object.defineProperty(ValueCondition, "IsEqual", {
  53138. /**
  53139. * returns the number for IsEqual
  53140. */
  53141. get: function () {
  53142. return ValueCondition._IsEqual;
  53143. },
  53144. enumerable: true,
  53145. configurable: true
  53146. });
  53147. Object.defineProperty(ValueCondition, "IsDifferent", {
  53148. /**
  53149. * Returns the number for IsDifferent
  53150. */
  53151. get: function () {
  53152. return ValueCondition._IsDifferent;
  53153. },
  53154. enumerable: true,
  53155. configurable: true
  53156. });
  53157. Object.defineProperty(ValueCondition, "IsGreater", {
  53158. /**
  53159. * Returns the number for IsGreater
  53160. */
  53161. get: function () {
  53162. return ValueCondition._IsGreater;
  53163. },
  53164. enumerable: true,
  53165. configurable: true
  53166. });
  53167. Object.defineProperty(ValueCondition, "IsLesser", {
  53168. /**
  53169. * Returns the number for IsLesser
  53170. */
  53171. get: function () {
  53172. return ValueCondition._IsLesser;
  53173. },
  53174. enumerable: true,
  53175. configurable: true
  53176. });
  53177. /**
  53178. * Compares the given value with the property value for the specified conditional operator
  53179. * @returns the result of the comparison
  53180. */
  53181. ValueCondition.prototype.isValid = function () {
  53182. switch (this.operator) {
  53183. case ValueCondition.IsGreater:
  53184. return this._effectiveTarget[this._property] > this.value;
  53185. case ValueCondition.IsLesser:
  53186. return this._effectiveTarget[this._property] < this.value;
  53187. case ValueCondition.IsEqual:
  53188. case ValueCondition.IsDifferent:
  53189. var check;
  53190. if (this.value.equals) {
  53191. check = this.value.equals(this._effectiveTarget[this._property]);
  53192. }
  53193. else {
  53194. check = this.value === this._effectiveTarget[this._property];
  53195. }
  53196. return this.operator === ValueCondition.IsEqual ? check : !check;
  53197. }
  53198. return false;
  53199. };
  53200. /**
  53201. * Serialize the ValueCondition into a JSON compatible object
  53202. * @returns serialization object
  53203. */
  53204. ValueCondition.prototype.serialize = function () {
  53205. return this._serialize({
  53206. name: "ValueCondition",
  53207. properties: [
  53208. BABYLON.Action._GetTargetProperty(this._target),
  53209. { name: "propertyPath", value: this.propertyPath },
  53210. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53211. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53212. ]
  53213. });
  53214. };
  53215. /**
  53216. * Gets the name of the conditional operator for the ValueCondition
  53217. * @param operator the conditional operator
  53218. * @returns the name
  53219. */
  53220. ValueCondition.GetOperatorName = function (operator) {
  53221. switch (operator) {
  53222. case ValueCondition._IsEqual: return "IsEqual";
  53223. case ValueCondition._IsDifferent: return "IsDifferent";
  53224. case ValueCondition._IsGreater: return "IsGreater";
  53225. case ValueCondition._IsLesser: return "IsLesser";
  53226. default: return "";
  53227. }
  53228. };
  53229. /**
  53230. * Internal only
  53231. * @hidden
  53232. */
  53233. ValueCondition._IsEqual = 0;
  53234. /**
  53235. * Internal only
  53236. * @hidden
  53237. */
  53238. ValueCondition._IsDifferent = 1;
  53239. /**
  53240. * Internal only
  53241. * @hidden
  53242. */
  53243. ValueCondition._IsGreater = 2;
  53244. /**
  53245. * Internal only
  53246. * @hidden
  53247. */
  53248. ValueCondition._IsLesser = 3;
  53249. return ValueCondition;
  53250. }(Condition));
  53251. BABYLON.ValueCondition = ValueCondition;
  53252. /**
  53253. * Defines a predicate condition as an extension of Condition
  53254. */
  53255. var PredicateCondition = /** @class */ (function (_super) {
  53256. __extends(PredicateCondition, _super);
  53257. /**
  53258. * Creates a new PredicateCondition
  53259. * @param actionManager manager for the action the condition applies to
  53260. * @param predicate defines the predicate function used to validate the condition
  53261. */
  53262. function PredicateCondition(actionManager,
  53263. /** defines the predicate function used to validate the condition */
  53264. predicate) {
  53265. var _this = _super.call(this, actionManager) || this;
  53266. _this.predicate = predicate;
  53267. return _this;
  53268. }
  53269. /**
  53270. * @returns the validity of the predicate condition
  53271. */
  53272. PredicateCondition.prototype.isValid = function () {
  53273. return this.predicate();
  53274. };
  53275. return PredicateCondition;
  53276. }(Condition));
  53277. BABYLON.PredicateCondition = PredicateCondition;
  53278. /**
  53279. * Defines a state condition as an extension of Condition
  53280. */
  53281. var StateCondition = /** @class */ (function (_super) {
  53282. __extends(StateCondition, _super);
  53283. /**
  53284. * Creates a new StateCondition
  53285. * @param actionManager manager for the action the condition applies to
  53286. * @param target of the condition
  53287. * @param value to compare with target state
  53288. */
  53289. function StateCondition(actionManager, target, value) {
  53290. var _this = _super.call(this, actionManager) || this;
  53291. _this.value = value;
  53292. _this._target = target;
  53293. return _this;
  53294. }
  53295. /**
  53296. * @returns the validity of the state
  53297. */
  53298. StateCondition.prototype.isValid = function () {
  53299. return this._target.state === this.value;
  53300. };
  53301. /**
  53302. * Serialize the StateCondition into a JSON compatible object
  53303. * @returns serialization object
  53304. */
  53305. StateCondition.prototype.serialize = function () {
  53306. return this._serialize({
  53307. name: "StateCondition",
  53308. properties: [
  53309. BABYLON.Action._GetTargetProperty(this._target),
  53310. { name: "value", value: this.value }
  53311. ]
  53312. });
  53313. };
  53314. return StateCondition;
  53315. }(Condition));
  53316. BABYLON.StateCondition = StateCondition;
  53317. })(BABYLON || (BABYLON = {}));
  53318. //# sourceMappingURL=babylon.condition.js.map
  53319. var BABYLON;
  53320. (function (BABYLON) {
  53321. /**
  53322. * The action to be carried out following a trigger
  53323. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53324. */
  53325. var Action = /** @class */ (function () {
  53326. /**
  53327. * Creates a new Action
  53328. * @param triggerOptions the trigger, with or without parameters, for the action
  53329. * @param condition an optional determinant of action
  53330. */
  53331. function Action(
  53332. /** the trigger, with or without parameters, for the action */
  53333. triggerOptions, condition) {
  53334. this.triggerOptions = triggerOptions;
  53335. /**
  53336. * An event triggered prior to action being executed.
  53337. */
  53338. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53339. if (triggerOptions.parameter) {
  53340. this.trigger = triggerOptions.trigger;
  53341. this._triggerParameter = triggerOptions.parameter;
  53342. }
  53343. else {
  53344. this.trigger = triggerOptions;
  53345. }
  53346. this._nextActiveAction = this;
  53347. this._condition = condition;
  53348. }
  53349. /**
  53350. * Internal only
  53351. * @hidden
  53352. */
  53353. Action.prototype._prepare = function () {
  53354. };
  53355. /**
  53356. * Gets the trigger parameters
  53357. * @returns the trigger parameters
  53358. */
  53359. Action.prototype.getTriggerParameter = function () {
  53360. return this._triggerParameter;
  53361. };
  53362. /**
  53363. * Internal only - executes current action event
  53364. * @hidden
  53365. */
  53366. Action.prototype._executeCurrent = function (evt) {
  53367. if (this._nextActiveAction._condition) {
  53368. var condition = this._nextActiveAction._condition;
  53369. var currentRenderId = this._actionManager.getScene().getRenderId();
  53370. // We cache the current evaluation for the current frame
  53371. if (condition._evaluationId === currentRenderId) {
  53372. if (!condition._currentResult) {
  53373. return;
  53374. }
  53375. }
  53376. else {
  53377. condition._evaluationId = currentRenderId;
  53378. if (!condition.isValid()) {
  53379. condition._currentResult = false;
  53380. return;
  53381. }
  53382. condition._currentResult = true;
  53383. }
  53384. }
  53385. this.onBeforeExecuteObservable.notifyObservers(this);
  53386. this._nextActiveAction.execute(evt);
  53387. this.skipToNextActiveAction();
  53388. };
  53389. /**
  53390. * Execute placeholder for child classes
  53391. * @param evt optional action event
  53392. */
  53393. Action.prototype.execute = function (evt) {
  53394. };
  53395. /**
  53396. * Skips to next active action
  53397. */
  53398. Action.prototype.skipToNextActiveAction = function () {
  53399. if (this._nextActiveAction._child) {
  53400. if (!this._nextActiveAction._child._actionManager) {
  53401. this._nextActiveAction._child._actionManager = this._actionManager;
  53402. }
  53403. this._nextActiveAction = this._nextActiveAction._child;
  53404. }
  53405. else {
  53406. this._nextActiveAction = this;
  53407. }
  53408. };
  53409. /**
  53410. * Adds action to chain of actions, may be a DoNothingAction
  53411. * @param action defines the next action to execute
  53412. * @returns The action passed in
  53413. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53414. */
  53415. Action.prototype.then = function (action) {
  53416. this._child = action;
  53417. action._actionManager = this._actionManager;
  53418. action._prepare();
  53419. return action;
  53420. };
  53421. /**
  53422. * Internal only
  53423. * @hidden
  53424. */
  53425. Action.prototype._getProperty = function (propertyPath) {
  53426. return this._actionManager._getProperty(propertyPath);
  53427. };
  53428. /**
  53429. * Internal only
  53430. * @hidden
  53431. */
  53432. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53433. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53434. };
  53435. /**
  53436. * Serialize placeholder for child classes
  53437. * @param parent of child
  53438. * @returns the serialized object
  53439. */
  53440. Action.prototype.serialize = function (parent) {
  53441. };
  53442. /**
  53443. * Internal only called by serialize
  53444. * @hidden
  53445. */
  53446. Action.prototype._serialize = function (serializedAction, parent) {
  53447. var serializationObject = {
  53448. type: 1,
  53449. children: [],
  53450. name: serializedAction.name,
  53451. properties: serializedAction.properties || []
  53452. };
  53453. // Serialize child
  53454. if (this._child) {
  53455. this._child.serialize(serializationObject);
  53456. }
  53457. // Check if "this" has a condition
  53458. if (this._condition) {
  53459. var serializedCondition = this._condition.serialize();
  53460. serializedCondition.children.push(serializationObject);
  53461. if (parent) {
  53462. parent.children.push(serializedCondition);
  53463. }
  53464. return serializedCondition;
  53465. }
  53466. if (parent) {
  53467. parent.children.push(serializationObject);
  53468. }
  53469. return serializationObject;
  53470. };
  53471. /**
  53472. * Internal only
  53473. * @hidden
  53474. */
  53475. Action._SerializeValueAsString = function (value) {
  53476. if (typeof value === "number") {
  53477. return value.toString();
  53478. }
  53479. if (typeof value === "boolean") {
  53480. return value ? "true" : "false";
  53481. }
  53482. if (value instanceof BABYLON.Vector2) {
  53483. return value.x + ", " + value.y;
  53484. }
  53485. if (value instanceof BABYLON.Vector3) {
  53486. return value.x + ", " + value.y + ", " + value.z;
  53487. }
  53488. if (value instanceof BABYLON.Color3) {
  53489. return value.r + ", " + value.g + ", " + value.b;
  53490. }
  53491. if (value instanceof BABYLON.Color4) {
  53492. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53493. }
  53494. return value; // string
  53495. };
  53496. /**
  53497. * Internal only
  53498. * @hidden
  53499. */
  53500. Action._GetTargetProperty = function (target) {
  53501. return {
  53502. name: "target",
  53503. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53504. : target instanceof BABYLON.Light ? "LightProperties"
  53505. : target instanceof BABYLON.Camera ? "CameraProperties"
  53506. : "SceneProperties",
  53507. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53508. };
  53509. };
  53510. return Action;
  53511. }());
  53512. BABYLON.Action = Action;
  53513. })(BABYLON || (BABYLON = {}));
  53514. //# sourceMappingURL=babylon.action.js.map
  53515. var BABYLON;
  53516. (function (BABYLON) {
  53517. /**
  53518. * ActionEvent is the event being sent when an action is triggered.
  53519. */
  53520. var ActionEvent = /** @class */ (function () {
  53521. /**
  53522. * Creates a new ActionEvent
  53523. * @param source The mesh or sprite that triggered the action
  53524. * @param pointerX The X mouse cursor position at the time of the event
  53525. * @param pointerY The Y mouse cursor position at the time of the event
  53526. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53527. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53528. * @param additionalData additional data for the event
  53529. */
  53530. function ActionEvent(
  53531. /** The mesh or sprite that triggered the action */
  53532. source,
  53533. /** The X mouse cursor position at the time of the event */
  53534. pointerX,
  53535. /** The Y mouse cursor position at the time of the event */
  53536. pointerY,
  53537. /** The mesh that is currently pointed at (can be null) */
  53538. meshUnderPointer,
  53539. /** the original (browser) event that triggered the ActionEvent */
  53540. sourceEvent,
  53541. /** additional data for the event */
  53542. additionalData) {
  53543. this.source = source;
  53544. this.pointerX = pointerX;
  53545. this.pointerY = pointerY;
  53546. this.meshUnderPointer = meshUnderPointer;
  53547. this.sourceEvent = sourceEvent;
  53548. this.additionalData = additionalData;
  53549. }
  53550. /**
  53551. * Helper function to auto-create an ActionEvent from a source mesh.
  53552. * @param source The source mesh that triggered the event
  53553. * @param evt The original (browser) event
  53554. * @param additionalData additional data for the event
  53555. * @returns the new ActionEvent
  53556. */
  53557. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53558. var scene = source.getScene();
  53559. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53560. };
  53561. /**
  53562. * Helper function to auto-create an ActionEvent from a source sprite
  53563. * @param source The source sprite that triggered the event
  53564. * @param scene Scene associated with the sprite
  53565. * @param evt The original (browser) event
  53566. * @param additionalData additional data for the event
  53567. * @returns the new ActionEvent
  53568. */
  53569. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53570. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53571. };
  53572. /**
  53573. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53574. * @param scene the scene where the event occurred
  53575. * @param evt The original (browser) event
  53576. * @returns the new ActionEvent
  53577. */
  53578. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53579. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53580. };
  53581. /**
  53582. * Helper function to auto-create an ActionEvent from a primitive
  53583. * @param prim defines the target primitive
  53584. * @param pointerPos defines the pointer position
  53585. * @param evt The original (browser) event
  53586. * @param additionalData additional data for the event
  53587. * @returns the new ActionEvent
  53588. */
  53589. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53590. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53591. };
  53592. return ActionEvent;
  53593. }());
  53594. BABYLON.ActionEvent = ActionEvent;
  53595. /**
  53596. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53597. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53598. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53599. */
  53600. var ActionManager = /** @class */ (function () {
  53601. /**
  53602. * Creates a new action manager
  53603. * @param scene defines the hosting scene
  53604. */
  53605. function ActionManager(scene) {
  53606. // Members
  53607. /** Gets the list of actions */
  53608. this.actions = new Array();
  53609. /** Gets the cursor to use when hovering items */
  53610. this.hoverCursor = '';
  53611. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53612. scene._actionManagers.push(this);
  53613. }
  53614. Object.defineProperty(ActionManager, "NothingTrigger", {
  53615. /**
  53616. * Nothing
  53617. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53618. */
  53619. get: function () {
  53620. return ActionManager._NothingTrigger;
  53621. },
  53622. enumerable: true,
  53623. configurable: true
  53624. });
  53625. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53626. /**
  53627. * On pick
  53628. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53629. */
  53630. get: function () {
  53631. return ActionManager._OnPickTrigger;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53637. /**
  53638. * On left pick
  53639. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53640. */
  53641. get: function () {
  53642. return ActionManager._OnLeftPickTrigger;
  53643. },
  53644. enumerable: true,
  53645. configurable: true
  53646. });
  53647. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53648. /**
  53649. * On right pick
  53650. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53651. */
  53652. get: function () {
  53653. return ActionManager._OnRightPickTrigger;
  53654. },
  53655. enumerable: true,
  53656. configurable: true
  53657. });
  53658. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53659. /**
  53660. * On center pick
  53661. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53662. */
  53663. get: function () {
  53664. return ActionManager._OnCenterPickTrigger;
  53665. },
  53666. enumerable: true,
  53667. configurable: true
  53668. });
  53669. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53670. /**
  53671. * On pick down
  53672. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53673. */
  53674. get: function () {
  53675. return ActionManager._OnPickDownTrigger;
  53676. },
  53677. enumerable: true,
  53678. configurable: true
  53679. });
  53680. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53681. /**
  53682. * On double pick
  53683. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53684. */
  53685. get: function () {
  53686. return ActionManager._OnDoublePickTrigger;
  53687. },
  53688. enumerable: true,
  53689. configurable: true
  53690. });
  53691. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53692. /**
  53693. * On pick up
  53694. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53695. */
  53696. get: function () {
  53697. return ActionManager._OnPickUpTrigger;
  53698. },
  53699. enumerable: true,
  53700. configurable: true
  53701. });
  53702. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53703. /**
  53704. * On pick out.
  53705. * This trigger will only be raised if you also declared a OnPickDown
  53706. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53707. */
  53708. get: function () {
  53709. return ActionManager._OnPickOutTrigger;
  53710. },
  53711. enumerable: true,
  53712. configurable: true
  53713. });
  53714. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53715. /**
  53716. * On long press
  53717. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53718. */
  53719. get: function () {
  53720. return ActionManager._OnLongPressTrigger;
  53721. },
  53722. enumerable: true,
  53723. configurable: true
  53724. });
  53725. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53726. /**
  53727. * On pointer over
  53728. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53729. */
  53730. get: function () {
  53731. return ActionManager._OnPointerOverTrigger;
  53732. },
  53733. enumerable: true,
  53734. configurable: true
  53735. });
  53736. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53737. /**
  53738. * On pointer out
  53739. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53740. */
  53741. get: function () {
  53742. return ActionManager._OnPointerOutTrigger;
  53743. },
  53744. enumerable: true,
  53745. configurable: true
  53746. });
  53747. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53748. /**
  53749. * On every frame
  53750. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53751. */
  53752. get: function () {
  53753. return ActionManager._OnEveryFrameTrigger;
  53754. },
  53755. enumerable: true,
  53756. configurable: true
  53757. });
  53758. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53759. /**
  53760. * On intersection enter
  53761. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53762. */
  53763. get: function () {
  53764. return ActionManager._OnIntersectionEnterTrigger;
  53765. },
  53766. enumerable: true,
  53767. configurable: true
  53768. });
  53769. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53770. /**
  53771. * On intersection exit
  53772. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53773. */
  53774. get: function () {
  53775. return ActionManager._OnIntersectionExitTrigger;
  53776. },
  53777. enumerable: true,
  53778. configurable: true
  53779. });
  53780. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53781. /**
  53782. * On key down
  53783. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53784. */
  53785. get: function () {
  53786. return ActionManager._OnKeyDownTrigger;
  53787. },
  53788. enumerable: true,
  53789. configurable: true
  53790. });
  53791. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53792. /**
  53793. * On key up
  53794. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53795. */
  53796. get: function () {
  53797. return ActionManager._OnKeyUpTrigger;
  53798. },
  53799. enumerable: true,
  53800. configurable: true
  53801. });
  53802. // Methods
  53803. /**
  53804. * Releases all associated resources
  53805. */
  53806. ActionManager.prototype.dispose = function () {
  53807. var index = this._scene._actionManagers.indexOf(this);
  53808. for (var i = 0; i < this.actions.length; i++) {
  53809. var action = this.actions[i];
  53810. ActionManager.Triggers[action.trigger]--;
  53811. if (ActionManager.Triggers[action.trigger] === 0) {
  53812. delete ActionManager.Triggers[action.trigger];
  53813. }
  53814. }
  53815. if (index > -1) {
  53816. this._scene._actionManagers.splice(index, 1);
  53817. }
  53818. };
  53819. /**
  53820. * Gets hosting scene
  53821. * @returns the hosting scene
  53822. */
  53823. ActionManager.prototype.getScene = function () {
  53824. return this._scene;
  53825. };
  53826. /**
  53827. * Does this action manager handles actions of any of the given triggers
  53828. * @param triggers defines the triggers to be tested
  53829. * @return a boolean indicating whether one (or more) of the triggers is handled
  53830. */
  53831. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53832. for (var index = 0; index < this.actions.length; index++) {
  53833. var action = this.actions[index];
  53834. if (triggers.indexOf(action.trigger) > -1) {
  53835. return true;
  53836. }
  53837. }
  53838. return false;
  53839. };
  53840. /**
  53841. * Does this action manager handles actions of a given trigger
  53842. * @param trigger defines the trigger to be tested
  53843. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53844. * @return whether the trigger is handled
  53845. */
  53846. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53847. for (var index = 0; index < this.actions.length; index++) {
  53848. var action = this.actions[index];
  53849. if (action.trigger === trigger) {
  53850. if (parameterPredicate) {
  53851. if (parameterPredicate(action.getTriggerParameter())) {
  53852. return true;
  53853. }
  53854. }
  53855. else {
  53856. return true;
  53857. }
  53858. }
  53859. }
  53860. return false;
  53861. };
  53862. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53863. /**
  53864. * Does this action manager has pointer triggers
  53865. */
  53866. get: function () {
  53867. for (var index = 0; index < this.actions.length; index++) {
  53868. var action = this.actions[index];
  53869. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53870. return true;
  53871. }
  53872. }
  53873. return false;
  53874. },
  53875. enumerable: true,
  53876. configurable: true
  53877. });
  53878. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53879. /**
  53880. * Does this action manager has pick triggers
  53881. */
  53882. get: function () {
  53883. for (var index = 0; index < this.actions.length; index++) {
  53884. var action = this.actions[index];
  53885. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53886. return true;
  53887. }
  53888. }
  53889. return false;
  53890. },
  53891. enumerable: true,
  53892. configurable: true
  53893. });
  53894. Object.defineProperty(ActionManager, "HasTriggers", {
  53895. /**
  53896. * Does exist one action manager with at least one trigger
  53897. **/
  53898. get: function () {
  53899. for (var t in ActionManager.Triggers) {
  53900. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53901. return true;
  53902. }
  53903. }
  53904. return false;
  53905. },
  53906. enumerable: true,
  53907. configurable: true
  53908. });
  53909. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53910. /**
  53911. * Does exist one action manager with at least one pick trigger
  53912. **/
  53913. get: function () {
  53914. for (var t in ActionManager.Triggers) {
  53915. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53916. var t_int = parseInt(t);
  53917. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53918. return true;
  53919. }
  53920. }
  53921. }
  53922. return false;
  53923. },
  53924. enumerable: true,
  53925. configurable: true
  53926. });
  53927. /**
  53928. * Does exist one action manager that handles actions of a given trigger
  53929. * @param trigger defines the trigger to be tested
  53930. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53931. **/
  53932. ActionManager.HasSpecificTrigger = function (trigger) {
  53933. for (var t in ActionManager.Triggers) {
  53934. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53935. var t_int = parseInt(t);
  53936. if (t_int === trigger) {
  53937. return true;
  53938. }
  53939. }
  53940. }
  53941. return false;
  53942. };
  53943. /**
  53944. * Registers an action to this action manager
  53945. * @param action defines the action to be registered
  53946. * @return the action amended (prepared) after registration
  53947. */
  53948. ActionManager.prototype.registerAction = function (action) {
  53949. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53950. if (this.getScene().actionManager !== this) {
  53951. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53952. return null;
  53953. }
  53954. }
  53955. this.actions.push(action);
  53956. if (ActionManager.Triggers[action.trigger]) {
  53957. ActionManager.Triggers[action.trigger]++;
  53958. }
  53959. else {
  53960. ActionManager.Triggers[action.trigger] = 1;
  53961. }
  53962. action._actionManager = this;
  53963. action._prepare();
  53964. return action;
  53965. };
  53966. /**
  53967. * Unregisters an action to this action manager
  53968. * @param action defines the action to be unregistered
  53969. * @return a boolean indicating whether the action has been unregistered
  53970. */
  53971. ActionManager.prototype.unregisterAction = function (action) {
  53972. var index = this.actions.indexOf(action);
  53973. if (index !== -1) {
  53974. this.actions.splice(index, 1);
  53975. ActionManager.Triggers[action.trigger] -= 1;
  53976. if (ActionManager.Triggers[action.trigger] === 0) {
  53977. delete ActionManager.Triggers[action.trigger];
  53978. }
  53979. delete action._actionManager;
  53980. return true;
  53981. }
  53982. return false;
  53983. };
  53984. /**
  53985. * Process a specific trigger
  53986. * @param trigger defines the trigger to process
  53987. * @param evt defines the event details to be processed
  53988. */
  53989. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53990. for (var index = 0; index < this.actions.length; index++) {
  53991. var action = this.actions[index];
  53992. if (action.trigger === trigger) {
  53993. if (evt) {
  53994. if (trigger === ActionManager.OnKeyUpTrigger
  53995. || trigger === ActionManager.OnKeyDownTrigger) {
  53996. var parameter = action.getTriggerParameter();
  53997. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53998. if (!parameter.toLowerCase) {
  53999. continue;
  54000. }
  54001. var lowerCase = parameter.toLowerCase();
  54002. if (lowerCase !== evt.sourceEvent.key) {
  54003. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  54004. var actualkey = String.fromCharCode(unicode).toLowerCase();
  54005. if (actualkey !== lowerCase) {
  54006. continue;
  54007. }
  54008. }
  54009. }
  54010. }
  54011. }
  54012. action._executeCurrent(evt);
  54013. }
  54014. }
  54015. };
  54016. /** @hidden */
  54017. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  54018. var properties = propertyPath.split(".");
  54019. for (var index = 0; index < properties.length - 1; index++) {
  54020. target = target[properties[index]];
  54021. }
  54022. return target;
  54023. };
  54024. /** @hidden */
  54025. ActionManager.prototype._getProperty = function (propertyPath) {
  54026. var properties = propertyPath.split(".");
  54027. return properties[properties.length - 1];
  54028. };
  54029. /**
  54030. * Serialize this manager to a JSON object
  54031. * @param name defines the property name to store this manager
  54032. * @returns a JSON representation of this manager
  54033. */
  54034. ActionManager.prototype.serialize = function (name) {
  54035. var root = {
  54036. children: new Array(),
  54037. name: name,
  54038. type: 3,
  54039. properties: new Array() // Empty for root but required
  54040. };
  54041. for (var i = 0; i < this.actions.length; i++) {
  54042. var triggerObject = {
  54043. type: 0,
  54044. children: new Array(),
  54045. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  54046. properties: new Array()
  54047. };
  54048. var triggerOptions = this.actions[i].triggerOptions;
  54049. if (triggerOptions && typeof triggerOptions !== "number") {
  54050. if (triggerOptions.parameter instanceof BABYLON.Node) {
  54051. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  54052. }
  54053. else {
  54054. var parameter = {};
  54055. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  54056. if (triggerOptions.parameter.mesh) {
  54057. parameter._meshId = triggerOptions.parameter.mesh.id;
  54058. }
  54059. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  54060. }
  54061. }
  54062. // Serialize child action, recursively
  54063. this.actions[i].serialize(triggerObject);
  54064. // Add serialized trigger
  54065. root.children.push(triggerObject);
  54066. }
  54067. return root;
  54068. };
  54069. /**
  54070. * Creates a new ActionManager from a JSON data
  54071. * @param parsedActions defines the JSON data to read from
  54072. * @param object defines the hosting mesh
  54073. * @param scene defines the hosting scene
  54074. */
  54075. ActionManager.Parse = function (parsedActions, object, scene) {
  54076. var actionManager = new ActionManager(scene);
  54077. if (object === null)
  54078. scene.actionManager = actionManager;
  54079. else
  54080. object.actionManager = actionManager;
  54081. // instanciate a new object
  54082. var instanciate = function (name, params) {
  54083. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  54084. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  54085. newInstance.constructor.apply(newInstance, params);
  54086. return newInstance;
  54087. };
  54088. var parseParameter = function (name, value, target, propertyPath) {
  54089. if (propertyPath === null) {
  54090. // String, boolean or float
  54091. var floatValue = parseFloat(value);
  54092. if (value === "true" || value === "false")
  54093. return value === "true";
  54094. else
  54095. return isNaN(floatValue) ? value : floatValue;
  54096. }
  54097. var effectiveTarget = propertyPath.split(".");
  54098. var values = value.split(",");
  54099. // Get effective Target
  54100. for (var i = 0; i < effectiveTarget.length; i++) {
  54101. target = target[effectiveTarget[i]];
  54102. }
  54103. // Return appropriate value with its type
  54104. if (typeof (target) === "boolean")
  54105. return values[0] === "true";
  54106. if (typeof (target) === "string")
  54107. return values[0];
  54108. // Parameters with multiple values such as Vector3 etc.
  54109. var split = new Array();
  54110. for (var i = 0; i < values.length; i++)
  54111. split.push(parseFloat(values[i]));
  54112. if (target instanceof BABYLON.Vector3)
  54113. return BABYLON.Vector3.FromArray(split);
  54114. if (target instanceof BABYLON.Vector4)
  54115. return BABYLON.Vector4.FromArray(split);
  54116. if (target instanceof BABYLON.Color3)
  54117. return BABYLON.Color3.FromArray(split);
  54118. if (target instanceof BABYLON.Color4)
  54119. return BABYLON.Color4.FromArray(split);
  54120. return parseFloat(values[0]);
  54121. };
  54122. // traverse graph per trigger
  54123. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  54124. if (combineArray === void 0) { combineArray = null; }
  54125. if (parsedAction.detached)
  54126. return;
  54127. var parameters = new Array();
  54128. var target = null;
  54129. var propertyPath = null;
  54130. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  54131. // Parameters
  54132. if (parsedAction.type === 2)
  54133. parameters.push(actionManager);
  54134. else
  54135. parameters.push(trigger);
  54136. if (combine) {
  54137. var actions = new Array();
  54138. for (var j = 0; j < parsedAction.combine.length; j++) {
  54139. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  54140. }
  54141. parameters.push(actions);
  54142. }
  54143. else {
  54144. for (var i = 0; i < parsedAction.properties.length; i++) {
  54145. var value = parsedAction.properties[i].value;
  54146. var name = parsedAction.properties[i].name;
  54147. var targetType = parsedAction.properties[i].targetType;
  54148. if (name === "target")
  54149. if (targetType !== null && targetType === "SceneProperties")
  54150. value = target = scene;
  54151. else
  54152. value = target = scene.getNodeByName(value);
  54153. else if (name === "parent")
  54154. value = scene.getNodeByName(value);
  54155. else if (name === "sound")
  54156. value = scene.getSoundByName(value);
  54157. else if (name !== "propertyPath") {
  54158. if (parsedAction.type === 2 && name === "operator")
  54159. value = BABYLON.ValueCondition[value];
  54160. else
  54161. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  54162. }
  54163. else {
  54164. propertyPath = value;
  54165. }
  54166. parameters.push(value);
  54167. }
  54168. }
  54169. if (combineArray === null) {
  54170. parameters.push(condition);
  54171. }
  54172. else {
  54173. parameters.push(null);
  54174. }
  54175. // If interpolate value action
  54176. if (parsedAction.name === "InterpolateValueAction") {
  54177. var param = parameters[parameters.length - 2];
  54178. parameters[parameters.length - 1] = param;
  54179. parameters[parameters.length - 2] = condition;
  54180. }
  54181. // Action or condition(s) and not CombineAction
  54182. var newAction = instanciate(parsedAction.name, parameters);
  54183. if (newAction instanceof BABYLON.Condition && condition !== null) {
  54184. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  54185. if (action)
  54186. action.then(nothing);
  54187. else
  54188. actionManager.registerAction(nothing);
  54189. action = nothing;
  54190. }
  54191. if (combineArray === null) {
  54192. if (newAction instanceof BABYLON.Condition) {
  54193. condition = newAction;
  54194. newAction = action;
  54195. }
  54196. else {
  54197. condition = null;
  54198. if (action)
  54199. action.then(newAction);
  54200. else
  54201. actionManager.registerAction(newAction);
  54202. }
  54203. }
  54204. else {
  54205. combineArray.push(newAction);
  54206. }
  54207. for (var i = 0; i < parsedAction.children.length; i++)
  54208. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  54209. };
  54210. // triggers
  54211. for (var i = 0; i < parsedActions.children.length; i++) {
  54212. var triggerParams;
  54213. var trigger = parsedActions.children[i];
  54214. if (trigger.properties.length > 0) {
  54215. var param = trigger.properties[0].value;
  54216. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  54217. if (value._meshId) {
  54218. value.mesh = scene.getMeshByID(value._meshId);
  54219. }
  54220. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  54221. }
  54222. else
  54223. triggerParams = ActionManager[trigger.name];
  54224. for (var j = 0; j < trigger.children.length; j++) {
  54225. if (!trigger.detached)
  54226. traverse(trigger.children[j], triggerParams, null, null);
  54227. }
  54228. }
  54229. };
  54230. /**
  54231. * Get a trigger name by index
  54232. * @param trigger defines the trigger index
  54233. * @returns a trigger name
  54234. */
  54235. ActionManager.GetTriggerName = function (trigger) {
  54236. switch (trigger) {
  54237. case 0: return "NothingTrigger";
  54238. case 1: return "OnPickTrigger";
  54239. case 2: return "OnLeftPickTrigger";
  54240. case 3: return "OnRightPickTrigger";
  54241. case 4: return "OnCenterPickTrigger";
  54242. case 5: return "OnPickDownTrigger";
  54243. case 6: return "OnPickUpTrigger";
  54244. case 7: return "OnLongPressTrigger";
  54245. case 8: return "OnPointerOverTrigger";
  54246. case 9: return "OnPointerOutTrigger";
  54247. case 10: return "OnEveryFrameTrigger";
  54248. case 11: return "OnIntersectionEnterTrigger";
  54249. case 12: return "OnIntersectionExitTrigger";
  54250. case 13: return "OnKeyDownTrigger";
  54251. case 14: return "OnKeyUpTrigger";
  54252. case 15: return "OnPickOutTrigger";
  54253. default: return "";
  54254. }
  54255. };
  54256. // Statics
  54257. ActionManager._NothingTrigger = 0;
  54258. ActionManager._OnPickTrigger = 1;
  54259. ActionManager._OnLeftPickTrigger = 2;
  54260. ActionManager._OnRightPickTrigger = 3;
  54261. ActionManager._OnCenterPickTrigger = 4;
  54262. ActionManager._OnPickDownTrigger = 5;
  54263. ActionManager._OnDoublePickTrigger = 6;
  54264. ActionManager._OnPickUpTrigger = 7;
  54265. ActionManager._OnLongPressTrigger = 8;
  54266. ActionManager._OnPointerOverTrigger = 9;
  54267. ActionManager._OnPointerOutTrigger = 10;
  54268. ActionManager._OnEveryFrameTrigger = 11;
  54269. ActionManager._OnIntersectionEnterTrigger = 12;
  54270. ActionManager._OnIntersectionExitTrigger = 13;
  54271. ActionManager._OnKeyDownTrigger = 14;
  54272. ActionManager._OnKeyUpTrigger = 15;
  54273. ActionManager._OnPickOutTrigger = 16;
  54274. /** Gets the list of active triggers */
  54275. ActionManager.Triggers = {};
  54276. return ActionManager;
  54277. }());
  54278. BABYLON.ActionManager = ActionManager;
  54279. })(BABYLON || (BABYLON = {}));
  54280. //# sourceMappingURL=babylon.actionManager.js.map
  54281. var BABYLON;
  54282. (function (BABYLON) {
  54283. var InterpolateValueAction = /** @class */ (function (_super) {
  54284. __extends(InterpolateValueAction, _super);
  54285. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54286. if (duration === void 0) { duration = 1000; }
  54287. var _this = _super.call(this, triggerOptions, condition) || this;
  54288. _this.propertyPath = propertyPath;
  54289. _this.value = value;
  54290. _this.duration = duration;
  54291. _this.stopOtherAnimations = stopOtherAnimations;
  54292. _this.onInterpolationDone = onInterpolationDone;
  54293. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54294. _this._target = _this._effectiveTarget = target;
  54295. return _this;
  54296. }
  54297. InterpolateValueAction.prototype._prepare = function () {
  54298. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54299. this._property = this._getProperty(this.propertyPath);
  54300. };
  54301. InterpolateValueAction.prototype.execute = function () {
  54302. var _this = this;
  54303. var scene = this._actionManager.getScene();
  54304. var keys = [
  54305. {
  54306. frame: 0,
  54307. value: this._effectiveTarget[this._property]
  54308. }, {
  54309. frame: 100,
  54310. value: this.value
  54311. }
  54312. ];
  54313. var dataType;
  54314. if (typeof this.value === "number") {
  54315. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54316. }
  54317. else if (this.value instanceof BABYLON.Color3) {
  54318. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54319. }
  54320. else if (this.value instanceof BABYLON.Vector3) {
  54321. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54322. }
  54323. else if (this.value instanceof BABYLON.Matrix) {
  54324. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54325. }
  54326. else if (this.value instanceof BABYLON.Quaternion) {
  54327. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54328. }
  54329. else {
  54330. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54331. return;
  54332. }
  54333. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54334. animation.setKeys(keys);
  54335. if (this.stopOtherAnimations) {
  54336. scene.stopAnimation(this._effectiveTarget);
  54337. }
  54338. var wrapper = function () {
  54339. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54340. if (_this.onInterpolationDone) {
  54341. _this.onInterpolationDone();
  54342. }
  54343. };
  54344. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54345. };
  54346. InterpolateValueAction.prototype.serialize = function (parent) {
  54347. return _super.prototype._serialize.call(this, {
  54348. name: "InterpolateValueAction",
  54349. properties: [
  54350. BABYLON.Action._GetTargetProperty(this._target),
  54351. { name: "propertyPath", value: this.propertyPath },
  54352. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54353. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54354. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54355. ]
  54356. }, parent);
  54357. };
  54358. return InterpolateValueAction;
  54359. }(BABYLON.Action));
  54360. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54361. })(BABYLON || (BABYLON = {}));
  54362. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54363. var BABYLON;
  54364. (function (BABYLON) {
  54365. var SwitchBooleanAction = /** @class */ (function (_super) {
  54366. __extends(SwitchBooleanAction, _super);
  54367. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54368. var _this = _super.call(this, triggerOptions, condition) || this;
  54369. _this.propertyPath = propertyPath;
  54370. _this._target = _this._effectiveTarget = target;
  54371. return _this;
  54372. }
  54373. SwitchBooleanAction.prototype._prepare = function () {
  54374. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54375. this._property = this._getProperty(this.propertyPath);
  54376. };
  54377. SwitchBooleanAction.prototype.execute = function () {
  54378. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54379. };
  54380. SwitchBooleanAction.prototype.serialize = function (parent) {
  54381. return _super.prototype._serialize.call(this, {
  54382. name: "SwitchBooleanAction",
  54383. properties: [
  54384. BABYLON.Action._GetTargetProperty(this._target),
  54385. { name: "propertyPath", value: this.propertyPath }
  54386. ]
  54387. }, parent);
  54388. };
  54389. return SwitchBooleanAction;
  54390. }(BABYLON.Action));
  54391. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54392. var SetStateAction = /** @class */ (function (_super) {
  54393. __extends(SetStateAction, _super);
  54394. function SetStateAction(triggerOptions, target, value, condition) {
  54395. var _this = _super.call(this, triggerOptions, condition) || this;
  54396. _this.value = value;
  54397. _this._target = target;
  54398. return _this;
  54399. }
  54400. SetStateAction.prototype.execute = function () {
  54401. this._target.state = this.value;
  54402. };
  54403. SetStateAction.prototype.serialize = function (parent) {
  54404. return _super.prototype._serialize.call(this, {
  54405. name: "SetStateAction",
  54406. properties: [
  54407. BABYLON.Action._GetTargetProperty(this._target),
  54408. { name: "value", value: this.value }
  54409. ]
  54410. }, parent);
  54411. };
  54412. return SetStateAction;
  54413. }(BABYLON.Action));
  54414. BABYLON.SetStateAction = SetStateAction;
  54415. var SetValueAction = /** @class */ (function (_super) {
  54416. __extends(SetValueAction, _super);
  54417. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54418. var _this = _super.call(this, triggerOptions, condition) || this;
  54419. _this.propertyPath = propertyPath;
  54420. _this.value = value;
  54421. _this._target = _this._effectiveTarget = target;
  54422. return _this;
  54423. }
  54424. SetValueAction.prototype._prepare = function () {
  54425. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54426. this._property = this._getProperty(this.propertyPath);
  54427. };
  54428. SetValueAction.prototype.execute = function () {
  54429. this._effectiveTarget[this._property] = this.value;
  54430. if (this._target.markAsDirty) {
  54431. this._target.markAsDirty(this._property);
  54432. }
  54433. };
  54434. SetValueAction.prototype.serialize = function (parent) {
  54435. return _super.prototype._serialize.call(this, {
  54436. name: "SetValueAction",
  54437. properties: [
  54438. BABYLON.Action._GetTargetProperty(this._target),
  54439. { name: "propertyPath", value: this.propertyPath },
  54440. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54441. ]
  54442. }, parent);
  54443. };
  54444. return SetValueAction;
  54445. }(BABYLON.Action));
  54446. BABYLON.SetValueAction = SetValueAction;
  54447. var IncrementValueAction = /** @class */ (function (_super) {
  54448. __extends(IncrementValueAction, _super);
  54449. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54450. var _this = _super.call(this, triggerOptions, condition) || this;
  54451. _this.propertyPath = propertyPath;
  54452. _this.value = value;
  54453. _this._target = _this._effectiveTarget = target;
  54454. return _this;
  54455. }
  54456. IncrementValueAction.prototype._prepare = function () {
  54457. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54458. this._property = this._getProperty(this.propertyPath);
  54459. if (typeof this._effectiveTarget[this._property] !== "number") {
  54460. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54461. }
  54462. };
  54463. IncrementValueAction.prototype.execute = function () {
  54464. this._effectiveTarget[this._property] += this.value;
  54465. if (this._target.markAsDirty) {
  54466. this._target.markAsDirty(this._property);
  54467. }
  54468. };
  54469. IncrementValueAction.prototype.serialize = function (parent) {
  54470. return _super.prototype._serialize.call(this, {
  54471. name: "IncrementValueAction",
  54472. properties: [
  54473. BABYLON.Action._GetTargetProperty(this._target),
  54474. { name: "propertyPath", value: this.propertyPath },
  54475. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54476. ]
  54477. }, parent);
  54478. };
  54479. return IncrementValueAction;
  54480. }(BABYLON.Action));
  54481. BABYLON.IncrementValueAction = IncrementValueAction;
  54482. var PlayAnimationAction = /** @class */ (function (_super) {
  54483. __extends(PlayAnimationAction, _super);
  54484. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54485. var _this = _super.call(this, triggerOptions, condition) || this;
  54486. _this.from = from;
  54487. _this.to = to;
  54488. _this.loop = loop;
  54489. _this._target = target;
  54490. return _this;
  54491. }
  54492. PlayAnimationAction.prototype._prepare = function () {
  54493. };
  54494. PlayAnimationAction.prototype.execute = function () {
  54495. var scene = this._actionManager.getScene();
  54496. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54497. };
  54498. PlayAnimationAction.prototype.serialize = function (parent) {
  54499. return _super.prototype._serialize.call(this, {
  54500. name: "PlayAnimationAction",
  54501. properties: [
  54502. BABYLON.Action._GetTargetProperty(this._target),
  54503. { name: "from", value: String(this.from) },
  54504. { name: "to", value: String(this.to) },
  54505. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54506. ]
  54507. }, parent);
  54508. };
  54509. return PlayAnimationAction;
  54510. }(BABYLON.Action));
  54511. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54512. var StopAnimationAction = /** @class */ (function (_super) {
  54513. __extends(StopAnimationAction, _super);
  54514. function StopAnimationAction(triggerOptions, target, condition) {
  54515. var _this = _super.call(this, triggerOptions, condition) || this;
  54516. _this._target = target;
  54517. return _this;
  54518. }
  54519. StopAnimationAction.prototype._prepare = function () {
  54520. };
  54521. StopAnimationAction.prototype.execute = function () {
  54522. var scene = this._actionManager.getScene();
  54523. scene.stopAnimation(this._target);
  54524. };
  54525. StopAnimationAction.prototype.serialize = function (parent) {
  54526. return _super.prototype._serialize.call(this, {
  54527. name: "StopAnimationAction",
  54528. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54529. }, parent);
  54530. };
  54531. return StopAnimationAction;
  54532. }(BABYLON.Action));
  54533. BABYLON.StopAnimationAction = StopAnimationAction;
  54534. var DoNothingAction = /** @class */ (function (_super) {
  54535. __extends(DoNothingAction, _super);
  54536. function DoNothingAction(triggerOptions, condition) {
  54537. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54538. return _super.call(this, triggerOptions, condition) || this;
  54539. }
  54540. DoNothingAction.prototype.execute = function () {
  54541. };
  54542. DoNothingAction.prototype.serialize = function (parent) {
  54543. return _super.prototype._serialize.call(this, {
  54544. name: "DoNothingAction",
  54545. properties: []
  54546. }, parent);
  54547. };
  54548. return DoNothingAction;
  54549. }(BABYLON.Action));
  54550. BABYLON.DoNothingAction = DoNothingAction;
  54551. var CombineAction = /** @class */ (function (_super) {
  54552. __extends(CombineAction, _super);
  54553. function CombineAction(triggerOptions, children, condition) {
  54554. var _this = _super.call(this, triggerOptions, condition) || this;
  54555. _this.children = children;
  54556. return _this;
  54557. }
  54558. CombineAction.prototype._prepare = function () {
  54559. for (var index = 0; index < this.children.length; index++) {
  54560. this.children[index]._actionManager = this._actionManager;
  54561. this.children[index]._prepare();
  54562. }
  54563. };
  54564. CombineAction.prototype.execute = function (evt) {
  54565. for (var index = 0; index < this.children.length; index++) {
  54566. this.children[index].execute(evt);
  54567. }
  54568. };
  54569. CombineAction.prototype.serialize = function (parent) {
  54570. var serializationObject = _super.prototype._serialize.call(this, {
  54571. name: "CombineAction",
  54572. properties: [],
  54573. combine: []
  54574. }, parent);
  54575. for (var i = 0; i < this.children.length; i++) {
  54576. serializationObject.combine.push(this.children[i].serialize(null));
  54577. }
  54578. return serializationObject;
  54579. };
  54580. return CombineAction;
  54581. }(BABYLON.Action));
  54582. BABYLON.CombineAction = CombineAction;
  54583. var ExecuteCodeAction = /** @class */ (function (_super) {
  54584. __extends(ExecuteCodeAction, _super);
  54585. function ExecuteCodeAction(triggerOptions, func, condition) {
  54586. var _this = _super.call(this, triggerOptions, condition) || this;
  54587. _this.func = func;
  54588. return _this;
  54589. }
  54590. ExecuteCodeAction.prototype.execute = function (evt) {
  54591. this.func(evt);
  54592. };
  54593. return ExecuteCodeAction;
  54594. }(BABYLON.Action));
  54595. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54596. var SetParentAction = /** @class */ (function (_super) {
  54597. __extends(SetParentAction, _super);
  54598. function SetParentAction(triggerOptions, target, parent, condition) {
  54599. var _this = _super.call(this, triggerOptions, condition) || this;
  54600. _this._target = target;
  54601. _this._parent = parent;
  54602. return _this;
  54603. }
  54604. SetParentAction.prototype._prepare = function () {
  54605. };
  54606. SetParentAction.prototype.execute = function () {
  54607. if (this._target.parent === this._parent) {
  54608. return;
  54609. }
  54610. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54611. invertParentWorldMatrix.invert();
  54612. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54613. this._target.parent = this._parent;
  54614. };
  54615. SetParentAction.prototype.serialize = function (parent) {
  54616. return _super.prototype._serialize.call(this, {
  54617. name: "SetParentAction",
  54618. properties: [
  54619. BABYLON.Action._GetTargetProperty(this._target),
  54620. BABYLON.Action._GetTargetProperty(this._parent),
  54621. ]
  54622. }, parent);
  54623. };
  54624. return SetParentAction;
  54625. }(BABYLON.Action));
  54626. BABYLON.SetParentAction = SetParentAction;
  54627. var PlaySoundAction = /** @class */ (function (_super) {
  54628. __extends(PlaySoundAction, _super);
  54629. function PlaySoundAction(triggerOptions, sound, condition) {
  54630. var _this = _super.call(this, triggerOptions, condition) || this;
  54631. _this._sound = sound;
  54632. return _this;
  54633. }
  54634. PlaySoundAction.prototype._prepare = function () {
  54635. };
  54636. PlaySoundAction.prototype.execute = function () {
  54637. if (this._sound !== undefined)
  54638. this._sound.play();
  54639. };
  54640. PlaySoundAction.prototype.serialize = function (parent) {
  54641. return _super.prototype._serialize.call(this, {
  54642. name: "PlaySoundAction",
  54643. properties: [{ name: "sound", value: this._sound.name }]
  54644. }, parent);
  54645. };
  54646. return PlaySoundAction;
  54647. }(BABYLON.Action));
  54648. BABYLON.PlaySoundAction = PlaySoundAction;
  54649. var StopSoundAction = /** @class */ (function (_super) {
  54650. __extends(StopSoundAction, _super);
  54651. function StopSoundAction(triggerOptions, sound, condition) {
  54652. var _this = _super.call(this, triggerOptions, condition) || this;
  54653. _this._sound = sound;
  54654. return _this;
  54655. }
  54656. StopSoundAction.prototype._prepare = function () {
  54657. };
  54658. StopSoundAction.prototype.execute = function () {
  54659. if (this._sound !== undefined)
  54660. this._sound.stop();
  54661. };
  54662. StopSoundAction.prototype.serialize = function (parent) {
  54663. return _super.prototype._serialize.call(this, {
  54664. name: "StopSoundAction",
  54665. properties: [{ name: "sound", value: this._sound.name }]
  54666. }, parent);
  54667. };
  54668. return StopSoundAction;
  54669. }(BABYLON.Action));
  54670. BABYLON.StopSoundAction = StopSoundAction;
  54671. })(BABYLON || (BABYLON = {}));
  54672. //# sourceMappingURL=babylon.directActions.js.map
  54673. var BABYLON;
  54674. (function (BABYLON) {
  54675. var SpriteManager = /** @class */ (function () {
  54676. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54677. if (epsilon === void 0) { epsilon = 0.01; }
  54678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54679. this.name = name;
  54680. this.sprites = new Array();
  54681. this.renderingGroupId = 0;
  54682. this.layerMask = 0x0FFFFFFF;
  54683. this.fogEnabled = true;
  54684. this.isPickable = false;
  54685. /**
  54686. * An event triggered when the manager is disposed.
  54687. */
  54688. this.onDisposeObservable = new BABYLON.Observable();
  54689. this._vertexBuffers = {};
  54690. this._capacity = capacity;
  54691. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54692. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54693. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54694. if (cellSize.width && cellSize.height) {
  54695. this.cellWidth = cellSize.width;
  54696. this.cellHeight = cellSize.height;
  54697. }
  54698. else if (cellSize !== undefined) {
  54699. this.cellWidth = cellSize;
  54700. this.cellHeight = cellSize;
  54701. }
  54702. else {
  54703. return;
  54704. }
  54705. this._epsilon = epsilon;
  54706. this._scene = scene;
  54707. this._scene.spriteManagers.push(this);
  54708. var indices = [];
  54709. var index = 0;
  54710. for (var count = 0; count < capacity; count++) {
  54711. indices.push(index);
  54712. indices.push(index + 1);
  54713. indices.push(index + 2);
  54714. indices.push(index);
  54715. indices.push(index + 2);
  54716. indices.push(index + 3);
  54717. index += 4;
  54718. }
  54719. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54720. // VBO
  54721. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54722. this._vertexData = new Float32Array(capacity * 16 * 4);
  54723. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54724. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54725. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54726. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54727. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54728. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54729. this._vertexBuffers["options"] = options;
  54730. this._vertexBuffers["cellInfo"] = cellInfo;
  54731. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54732. // Effects
  54733. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54734. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54735. }
  54736. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54737. set: function (callback) {
  54738. if (this._onDisposeObserver) {
  54739. this.onDisposeObservable.remove(this._onDisposeObserver);
  54740. }
  54741. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54742. },
  54743. enumerable: true,
  54744. configurable: true
  54745. });
  54746. Object.defineProperty(SpriteManager.prototype, "texture", {
  54747. get: function () {
  54748. return this._spriteTexture;
  54749. },
  54750. set: function (value) {
  54751. this._spriteTexture = value;
  54752. },
  54753. enumerable: true,
  54754. configurable: true
  54755. });
  54756. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54757. var arrayOffset = index * 16;
  54758. if (offsetX === 0)
  54759. offsetX = this._epsilon;
  54760. else if (offsetX === 1)
  54761. offsetX = 1 - this._epsilon;
  54762. if (offsetY === 0)
  54763. offsetY = this._epsilon;
  54764. else if (offsetY === 1)
  54765. offsetY = 1 - this._epsilon;
  54766. this._vertexData[arrayOffset] = sprite.position.x;
  54767. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54768. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54769. this._vertexData[arrayOffset + 3] = sprite.angle;
  54770. this._vertexData[arrayOffset + 4] = sprite.width;
  54771. this._vertexData[arrayOffset + 5] = sprite.height;
  54772. this._vertexData[arrayOffset + 6] = offsetX;
  54773. this._vertexData[arrayOffset + 7] = offsetY;
  54774. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54775. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54776. var offset = (sprite.cellIndex / rowSize) >> 0;
  54777. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54778. this._vertexData[arrayOffset + 11] = offset;
  54779. // Color
  54780. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54781. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54782. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54783. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54784. };
  54785. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54786. var count = Math.min(this._capacity, this.sprites.length);
  54787. var min = BABYLON.Vector3.Zero();
  54788. var max = BABYLON.Vector3.Zero();
  54789. var distance = Number.MAX_VALUE;
  54790. var currentSprite = null;
  54791. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54792. var cameraView = camera.getViewMatrix();
  54793. for (var index = 0; index < count; index++) {
  54794. var sprite = this.sprites[index];
  54795. if (!sprite) {
  54796. continue;
  54797. }
  54798. if (predicate) {
  54799. if (!predicate(sprite)) {
  54800. continue;
  54801. }
  54802. }
  54803. else if (!sprite.isPickable) {
  54804. continue;
  54805. }
  54806. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54807. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54808. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54809. if (ray.intersectsBoxMinMax(min, max)) {
  54810. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54811. if (distance > currentDistance) {
  54812. distance = currentDistance;
  54813. currentSprite = sprite;
  54814. if (fastCheck) {
  54815. break;
  54816. }
  54817. }
  54818. }
  54819. }
  54820. if (currentSprite) {
  54821. var result = new BABYLON.PickingInfo();
  54822. result.hit = true;
  54823. result.pickedSprite = currentSprite;
  54824. result.distance = distance;
  54825. return result;
  54826. }
  54827. return null;
  54828. };
  54829. SpriteManager.prototype.render = function () {
  54830. // Check
  54831. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54832. return;
  54833. var engine = this._scene.getEngine();
  54834. var baseSize = this._spriteTexture.getBaseSize();
  54835. // Sprites
  54836. var deltaTime = engine.getDeltaTime();
  54837. var max = Math.min(this._capacity, this.sprites.length);
  54838. var rowSize = baseSize.width / this.cellWidth;
  54839. var offset = 0;
  54840. for (var index = 0; index < max; index++) {
  54841. var sprite = this.sprites[index];
  54842. if (!sprite) {
  54843. continue;
  54844. }
  54845. sprite._animate(deltaTime);
  54846. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54847. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54848. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54849. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54850. }
  54851. this._buffer.update(this._vertexData);
  54852. // Render
  54853. var effect = this._effectBase;
  54854. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54855. effect = this._effectFog;
  54856. }
  54857. engine.enableEffect(effect);
  54858. var viewMatrix = this._scene.getViewMatrix();
  54859. effect.setTexture("diffuseSampler", this._spriteTexture);
  54860. effect.setMatrix("view", viewMatrix);
  54861. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54862. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54863. // Fog
  54864. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54865. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54866. effect.setColor3("vFogColor", this._scene.fogColor);
  54867. }
  54868. // VBOs
  54869. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54870. // Draw order
  54871. engine.setDepthFunctionToLessOrEqual();
  54872. effect.setBool("alphaTest", true);
  54873. engine.setColorWrite(false);
  54874. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54875. engine.setColorWrite(true);
  54876. effect.setBool("alphaTest", false);
  54877. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54878. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54879. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54880. };
  54881. SpriteManager.prototype.dispose = function () {
  54882. if (this._buffer) {
  54883. this._buffer.dispose();
  54884. this._buffer = null;
  54885. }
  54886. if (this._indexBuffer) {
  54887. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54888. this._indexBuffer = null;
  54889. }
  54890. if (this._spriteTexture) {
  54891. this._spriteTexture.dispose();
  54892. this._spriteTexture = null;
  54893. }
  54894. // Remove from scene
  54895. var index = this._scene.spriteManagers.indexOf(this);
  54896. this._scene.spriteManagers.splice(index, 1);
  54897. // Callback
  54898. this.onDisposeObservable.notifyObservers(this);
  54899. this.onDisposeObservable.clear();
  54900. };
  54901. return SpriteManager;
  54902. }());
  54903. BABYLON.SpriteManager = SpriteManager;
  54904. })(BABYLON || (BABYLON = {}));
  54905. //# sourceMappingURL=babylon.spriteManager.js.map
  54906. var BABYLON;
  54907. (function (BABYLON) {
  54908. var Sprite = /** @class */ (function () {
  54909. function Sprite(name, manager) {
  54910. this.name = name;
  54911. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54912. this.width = 1.0;
  54913. this.height = 1.0;
  54914. this.angle = 0;
  54915. this.cellIndex = 0;
  54916. this.invertU = 0;
  54917. this.invertV = 0;
  54918. this.animations = new Array();
  54919. this.isPickable = false;
  54920. this._animationStarted = false;
  54921. this._loopAnimation = false;
  54922. this._fromIndex = 0;
  54923. this._toIndex = 0;
  54924. this._delay = 0;
  54925. this._direction = 1;
  54926. this._time = 0;
  54927. this._manager = manager;
  54928. this._manager.sprites.push(this);
  54929. this.position = BABYLON.Vector3.Zero();
  54930. }
  54931. Object.defineProperty(Sprite.prototype, "size", {
  54932. get: function () {
  54933. return this.width;
  54934. },
  54935. set: function (value) {
  54936. this.width = value;
  54937. this.height = value;
  54938. },
  54939. enumerable: true,
  54940. configurable: true
  54941. });
  54942. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54943. this._fromIndex = from;
  54944. this._toIndex = to;
  54945. this._loopAnimation = loop;
  54946. this._delay = delay;
  54947. this._animationStarted = true;
  54948. this._direction = from < to ? 1 : -1;
  54949. this.cellIndex = from;
  54950. this._time = 0;
  54951. this._onAnimationEnd = onAnimationEnd;
  54952. };
  54953. Sprite.prototype.stopAnimation = function () {
  54954. this._animationStarted = false;
  54955. };
  54956. Sprite.prototype._animate = function (deltaTime) {
  54957. if (!this._animationStarted)
  54958. return;
  54959. this._time += deltaTime;
  54960. if (this._time > this._delay) {
  54961. this._time = this._time % this._delay;
  54962. this.cellIndex += this._direction;
  54963. if (this.cellIndex > this._toIndex) {
  54964. if (this._loopAnimation) {
  54965. this.cellIndex = this._fromIndex;
  54966. }
  54967. else {
  54968. this.cellIndex = this._toIndex;
  54969. this._animationStarted = false;
  54970. if (this._onAnimationEnd) {
  54971. this._onAnimationEnd();
  54972. }
  54973. if (this.disposeWhenFinishedAnimating) {
  54974. this.dispose();
  54975. }
  54976. }
  54977. }
  54978. }
  54979. };
  54980. Sprite.prototype.dispose = function () {
  54981. for (var i = 0; i < this._manager.sprites.length; i++) {
  54982. if (this._manager.sprites[i] == this) {
  54983. this._manager.sprites.splice(i, 1);
  54984. }
  54985. }
  54986. };
  54987. return Sprite;
  54988. }());
  54989. BABYLON.Sprite = Sprite;
  54990. })(BABYLON || (BABYLON = {}));
  54991. //# sourceMappingURL=babylon.sprite.js.map
  54992. var BABYLON;
  54993. (function (BABYLON) {
  54994. var IntersectionInfo = /** @class */ (function () {
  54995. function IntersectionInfo(bu, bv, distance) {
  54996. this.bu = bu;
  54997. this.bv = bv;
  54998. this.distance = distance;
  54999. this.faceId = 0;
  55000. this.subMeshId = 0;
  55001. }
  55002. return IntersectionInfo;
  55003. }());
  55004. BABYLON.IntersectionInfo = IntersectionInfo;
  55005. /**
  55006. * Information about the result of picking within a scene
  55007. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55008. */
  55009. var PickingInfo = /** @class */ (function () {
  55010. function PickingInfo() {
  55011. /**
  55012. * If the pick collided with an object
  55013. */
  55014. this.hit = false;
  55015. /**
  55016. * Distance away where the pick collided
  55017. */
  55018. this.distance = 0;
  55019. /**
  55020. * The location of pick collision
  55021. */
  55022. this.pickedPoint = null;
  55023. /**
  55024. * The mesh corrisponding the the pick collision
  55025. */
  55026. this.pickedMesh = null;
  55027. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55028. this.bu = 0;
  55029. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55030. this.bv = 0;
  55031. /** The id of the face on the mesh that was picked */
  55032. this.faceId = -1;
  55033. /** Id of the the submesh that was picked */
  55034. this.subMeshId = 0;
  55035. /** If a sprite was picked, this will be the sprite the pick collided with */
  55036. this.pickedSprite = null;
  55037. /**
  55038. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55039. */
  55040. this.originMesh = null;
  55041. /**
  55042. * The ray that was used to perform the picking.
  55043. */
  55044. this.ray = null;
  55045. }
  55046. /**
  55047. * Gets the normal corrispodning to the face the pick collided with
  55048. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55049. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55050. * @returns The normal corrispodning to the face the pick collided with
  55051. */
  55052. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55053. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55054. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55055. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55056. return null;
  55057. }
  55058. var indices = this.pickedMesh.getIndices();
  55059. if (!indices) {
  55060. return null;
  55061. }
  55062. var result;
  55063. if (useVerticesNormals) {
  55064. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55065. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55066. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55067. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55068. normal0 = normal0.scale(this.bu);
  55069. normal1 = normal1.scale(this.bv);
  55070. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55071. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55072. }
  55073. else {
  55074. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55075. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55076. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55077. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55078. var p1p2 = vertex1.subtract(vertex2);
  55079. var p3p2 = vertex3.subtract(vertex2);
  55080. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55081. }
  55082. if (useWorldCoordinates) {
  55083. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  55084. }
  55085. return BABYLON.Vector3.Normalize(result);
  55086. };
  55087. /**
  55088. * Gets the texture coordinates of where the pick occured
  55089. * @returns the vector containing the coordnates of the texture
  55090. */
  55091. PickingInfo.prototype.getTextureCoordinates = function () {
  55092. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55093. return null;
  55094. }
  55095. var indices = this.pickedMesh.getIndices();
  55096. if (!indices) {
  55097. return null;
  55098. }
  55099. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55100. if (!uvs) {
  55101. return null;
  55102. }
  55103. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55104. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55105. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55106. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55107. uv1 = uv1.scale(this.bu);
  55108. uv2 = uv2.scale(this.bv);
  55109. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55110. };
  55111. return PickingInfo;
  55112. }());
  55113. BABYLON.PickingInfo = PickingInfo;
  55114. })(BABYLON || (BABYLON = {}));
  55115. //# sourceMappingURL=babylon.pickingInfo.js.map
  55116. var BABYLON;
  55117. (function (BABYLON) {
  55118. var Ray = /** @class */ (function () {
  55119. function Ray(origin, direction, length) {
  55120. if (length === void 0) { length = Number.MAX_VALUE; }
  55121. this.origin = origin;
  55122. this.direction = direction;
  55123. this.length = length;
  55124. }
  55125. // Methods
  55126. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55127. var d = 0.0;
  55128. var maxValue = Number.MAX_VALUE;
  55129. var inv;
  55130. var min;
  55131. var max;
  55132. var temp;
  55133. if (Math.abs(this.direction.x) < 0.0000001) {
  55134. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55135. return false;
  55136. }
  55137. }
  55138. else {
  55139. inv = 1.0 / this.direction.x;
  55140. min = (minimum.x - this.origin.x) * inv;
  55141. max = (maximum.x - this.origin.x) * inv;
  55142. if (max === -Infinity) {
  55143. max = Infinity;
  55144. }
  55145. if (min > max) {
  55146. temp = min;
  55147. min = max;
  55148. max = temp;
  55149. }
  55150. d = Math.max(min, d);
  55151. maxValue = Math.min(max, maxValue);
  55152. if (d > maxValue) {
  55153. return false;
  55154. }
  55155. }
  55156. if (Math.abs(this.direction.y) < 0.0000001) {
  55157. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55158. return false;
  55159. }
  55160. }
  55161. else {
  55162. inv = 1.0 / this.direction.y;
  55163. min = (minimum.y - this.origin.y) * inv;
  55164. max = (maximum.y - this.origin.y) * inv;
  55165. if (max === -Infinity) {
  55166. max = Infinity;
  55167. }
  55168. if (min > max) {
  55169. temp = min;
  55170. min = max;
  55171. max = temp;
  55172. }
  55173. d = Math.max(min, d);
  55174. maxValue = Math.min(max, maxValue);
  55175. if (d > maxValue) {
  55176. return false;
  55177. }
  55178. }
  55179. if (Math.abs(this.direction.z) < 0.0000001) {
  55180. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55181. return false;
  55182. }
  55183. }
  55184. else {
  55185. inv = 1.0 / this.direction.z;
  55186. min = (minimum.z - this.origin.z) * inv;
  55187. max = (maximum.z - this.origin.z) * inv;
  55188. if (max === -Infinity) {
  55189. max = Infinity;
  55190. }
  55191. if (min > max) {
  55192. temp = min;
  55193. min = max;
  55194. max = temp;
  55195. }
  55196. d = Math.max(min, d);
  55197. maxValue = Math.min(max, maxValue);
  55198. if (d > maxValue) {
  55199. return false;
  55200. }
  55201. }
  55202. return true;
  55203. };
  55204. Ray.prototype.intersectsBox = function (box) {
  55205. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55206. };
  55207. Ray.prototype.intersectsSphere = function (sphere) {
  55208. var x = sphere.center.x - this.origin.x;
  55209. var y = sphere.center.y - this.origin.y;
  55210. var z = sphere.center.z - this.origin.z;
  55211. var pyth = (x * x) + (y * y) + (z * z);
  55212. var rr = sphere.radius * sphere.radius;
  55213. if (pyth <= rr) {
  55214. return true;
  55215. }
  55216. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55217. if (dot < 0.0) {
  55218. return false;
  55219. }
  55220. var temp = pyth - (dot * dot);
  55221. return temp <= rr;
  55222. };
  55223. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55224. if (!this._edge1) {
  55225. this._edge1 = BABYLON.Vector3.Zero();
  55226. this._edge2 = BABYLON.Vector3.Zero();
  55227. this._pvec = BABYLON.Vector3.Zero();
  55228. this._tvec = BABYLON.Vector3.Zero();
  55229. this._qvec = BABYLON.Vector3.Zero();
  55230. }
  55231. vertex1.subtractToRef(vertex0, this._edge1);
  55232. vertex2.subtractToRef(vertex0, this._edge2);
  55233. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55234. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55235. if (det === 0) {
  55236. return null;
  55237. }
  55238. var invdet = 1 / det;
  55239. this.origin.subtractToRef(vertex0, this._tvec);
  55240. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55241. if (bu < 0 || bu > 1.0) {
  55242. return null;
  55243. }
  55244. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55245. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55246. if (bv < 0 || bu + bv > 1.0) {
  55247. return null;
  55248. }
  55249. //check if the distance is longer than the predefined length.
  55250. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55251. if (distance > this.length) {
  55252. return null;
  55253. }
  55254. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55255. };
  55256. Ray.prototype.intersectsPlane = function (plane) {
  55257. var distance;
  55258. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55259. if (Math.abs(result1) < 9.99999997475243E-07) {
  55260. return null;
  55261. }
  55262. else {
  55263. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55264. distance = (-plane.d - result2) / result1;
  55265. if (distance < 0.0) {
  55266. if (distance < -9.99999997475243E-07) {
  55267. return null;
  55268. }
  55269. else {
  55270. return 0;
  55271. }
  55272. }
  55273. return distance;
  55274. }
  55275. };
  55276. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55277. var tm = BABYLON.Tmp.Matrix[0];
  55278. mesh.getWorldMatrix().invertToRef(tm);
  55279. if (this._tmpRay) {
  55280. Ray.TransformToRef(this, tm, this._tmpRay);
  55281. }
  55282. else {
  55283. this._tmpRay = Ray.Transform(this, tm);
  55284. }
  55285. return mesh.intersects(this._tmpRay, fastCheck);
  55286. };
  55287. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55288. if (results) {
  55289. results.length = 0;
  55290. }
  55291. else {
  55292. results = [];
  55293. }
  55294. for (var i = 0; i < meshes.length; i++) {
  55295. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55296. if (pickInfo.hit) {
  55297. results.push(pickInfo);
  55298. }
  55299. }
  55300. results.sort(this._comparePickingInfo);
  55301. return results;
  55302. };
  55303. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55304. if (pickingInfoA.distance < pickingInfoB.distance) {
  55305. return -1;
  55306. }
  55307. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55308. return 1;
  55309. }
  55310. else {
  55311. return 0;
  55312. }
  55313. };
  55314. /**
  55315. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55316. * @param sega the first point of the segment to test the intersection against
  55317. * @param segb the second point of the segment to test the intersection against
  55318. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55319. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55320. */
  55321. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55322. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55323. var u = segb.subtract(sega);
  55324. var v = rsegb.subtract(this.origin);
  55325. var w = sega.subtract(this.origin);
  55326. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55327. var b = BABYLON.Vector3.Dot(u, v);
  55328. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55329. var d = BABYLON.Vector3.Dot(u, w);
  55330. var e = BABYLON.Vector3.Dot(v, w);
  55331. var D = a * c - b * b; // always >= 0
  55332. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55333. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55334. // compute the line parameters of the two closest points
  55335. if (D < Ray.smallnum) { // the lines are almost parallel
  55336. sN = 0.0; // force using point P0 on segment S1
  55337. sD = 1.0; // to prevent possible division by 0.0 later
  55338. tN = e;
  55339. tD = c;
  55340. }
  55341. else { // get the closest points on the infinite lines
  55342. sN = (b * e - c * d);
  55343. tN = (a * e - b * d);
  55344. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55345. sN = 0.0;
  55346. tN = e;
  55347. tD = c;
  55348. }
  55349. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55350. sN = sD;
  55351. tN = e + b;
  55352. tD = c;
  55353. }
  55354. }
  55355. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55356. tN = 0.0;
  55357. // recompute sc for this edge
  55358. if (-d < 0.0) {
  55359. sN = 0.0;
  55360. }
  55361. else if (-d > a)
  55362. sN = sD;
  55363. else {
  55364. sN = -d;
  55365. sD = a;
  55366. }
  55367. }
  55368. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55369. tN = tD;
  55370. // recompute sc for this edge
  55371. if ((-d + b) < 0.0) {
  55372. sN = 0;
  55373. }
  55374. else if ((-d + b) > a) {
  55375. sN = sD;
  55376. }
  55377. else {
  55378. sN = (-d + b);
  55379. sD = a;
  55380. }
  55381. }
  55382. // finally do the division to get sc and tc
  55383. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55384. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55385. // get the difference of the two closest points
  55386. var qtc = v.multiplyByFloats(tc, tc, tc);
  55387. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55388. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55389. if (isIntersected) {
  55390. return qtc.length();
  55391. }
  55392. return -1;
  55393. };
  55394. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55395. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55396. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55397. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55398. this.direction.normalize();
  55399. return this;
  55400. };
  55401. // Statics
  55402. Ray.Zero = function () {
  55403. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55404. };
  55405. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55406. var result = Ray.Zero();
  55407. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55408. };
  55409. /**
  55410. * 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
  55411. * transformed to the given world matrix.
  55412. * @param origin The origin point
  55413. * @param end The end point
  55414. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55415. */
  55416. Ray.CreateNewFromTo = function (origin, end, world) {
  55417. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55418. var direction = end.subtract(origin);
  55419. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55420. direction.normalize();
  55421. return Ray.Transform(new Ray(origin, direction, length), world);
  55422. };
  55423. Ray.Transform = function (ray, matrix) {
  55424. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55425. Ray.TransformToRef(ray, matrix, result);
  55426. return result;
  55427. };
  55428. Ray.TransformToRef = function (ray, matrix, result) {
  55429. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55430. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55431. result.length = ray.length;
  55432. var dir = result.direction;
  55433. var len = dir.length();
  55434. if (!(len === 0 || len === 1)) {
  55435. var num = 1.0 / len;
  55436. dir.x *= num;
  55437. dir.y *= num;
  55438. dir.z *= num;
  55439. result.length *= len;
  55440. }
  55441. };
  55442. Ray.smallnum = 0.00000001;
  55443. Ray.rayl = 10e8;
  55444. return Ray;
  55445. }());
  55446. BABYLON.Ray = Ray;
  55447. })(BABYLON || (BABYLON = {}));
  55448. //# sourceMappingURL=babylon.ray.js.map
  55449. var BABYLON;
  55450. (function (BABYLON) {
  55451. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55452. if (boxMin.x > sphereCenter.x + sphereRadius)
  55453. return false;
  55454. if (sphereCenter.x - sphereRadius > boxMax.x)
  55455. return false;
  55456. if (boxMin.y > sphereCenter.y + sphereRadius)
  55457. return false;
  55458. if (sphereCenter.y - sphereRadius > boxMax.y)
  55459. return false;
  55460. if (boxMin.z > sphereCenter.z + sphereRadius)
  55461. return false;
  55462. if (sphereCenter.z - sphereRadius > boxMax.z)
  55463. return false;
  55464. return true;
  55465. };
  55466. var getLowestRoot = (function () {
  55467. var result = { root: 0, found: false };
  55468. return function (a, b, c, maxR) {
  55469. result.root = 0;
  55470. result.found = false;
  55471. var determinant = b * b - 4.0 * a * c;
  55472. if (determinant < 0)
  55473. return result;
  55474. var sqrtD = Math.sqrt(determinant);
  55475. var r1 = (-b - sqrtD) / (2.0 * a);
  55476. var r2 = (-b + sqrtD) / (2.0 * a);
  55477. if (r1 > r2) {
  55478. var temp = r2;
  55479. r2 = r1;
  55480. r1 = temp;
  55481. }
  55482. if (r1 > 0 && r1 < maxR) {
  55483. result.root = r1;
  55484. result.found = true;
  55485. return result;
  55486. }
  55487. if (r2 > 0 && r2 < maxR) {
  55488. result.root = r2;
  55489. result.found = true;
  55490. return result;
  55491. }
  55492. return result;
  55493. };
  55494. })();
  55495. var Collider = /** @class */ (function () {
  55496. function Collider() {
  55497. this._collisionPoint = BABYLON.Vector3.Zero();
  55498. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55499. this._tempVector = BABYLON.Vector3.Zero();
  55500. this._tempVector2 = BABYLON.Vector3.Zero();
  55501. this._tempVector3 = BABYLON.Vector3.Zero();
  55502. this._tempVector4 = BABYLON.Vector3.Zero();
  55503. this._edge = BABYLON.Vector3.Zero();
  55504. this._baseToVertex = BABYLON.Vector3.Zero();
  55505. this._destinationPoint = BABYLON.Vector3.Zero();
  55506. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55507. this._displacementVector = BABYLON.Vector3.Zero();
  55508. this._radius = BABYLON.Vector3.One();
  55509. this._retry = 0;
  55510. this._basePointWorld = BABYLON.Vector3.Zero();
  55511. this._velocityWorld = BABYLON.Vector3.Zero();
  55512. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55513. this._collisionMask = -1;
  55514. }
  55515. Object.defineProperty(Collider.prototype, "collisionMask", {
  55516. get: function () {
  55517. return this._collisionMask;
  55518. },
  55519. set: function (mask) {
  55520. this._collisionMask = !isNaN(mask) ? mask : -1;
  55521. },
  55522. enumerable: true,
  55523. configurable: true
  55524. });
  55525. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55526. /**
  55527. * Gets the plane normal used to compute the sliding response (in local space)
  55528. */
  55529. get: function () {
  55530. return this._slidePlaneNormal;
  55531. },
  55532. enumerable: true,
  55533. configurable: true
  55534. });
  55535. // Methods
  55536. Collider.prototype._initialize = function (source, dir, e) {
  55537. this._velocity = dir;
  55538. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55539. this._basePoint = source;
  55540. source.multiplyToRef(this._radius, this._basePointWorld);
  55541. dir.multiplyToRef(this._radius, this._velocityWorld);
  55542. this._velocityWorldLength = this._velocityWorld.length();
  55543. this._epsilon = e;
  55544. this.collisionFound = false;
  55545. };
  55546. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55547. pa.subtractToRef(point, this._tempVector);
  55548. pb.subtractToRef(point, this._tempVector2);
  55549. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55550. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55551. if (d < 0)
  55552. return false;
  55553. pc.subtractToRef(point, this._tempVector3);
  55554. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55555. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55556. if (d < 0)
  55557. return false;
  55558. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55559. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55560. return d >= 0;
  55561. };
  55562. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55563. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55564. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55565. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55566. return false;
  55567. }
  55568. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55569. return false;
  55570. return true;
  55571. };
  55572. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55573. var t0;
  55574. var embeddedInPlane = false;
  55575. //defensive programming, actually not needed.
  55576. if (!trianglePlaneArray) {
  55577. trianglePlaneArray = [];
  55578. }
  55579. if (!trianglePlaneArray[faceIndex]) {
  55580. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55581. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55582. }
  55583. var trianglePlane = trianglePlaneArray[faceIndex];
  55584. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55585. return;
  55586. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55587. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55588. if (normalDotVelocity == 0) {
  55589. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55590. return;
  55591. embeddedInPlane = true;
  55592. t0 = 0;
  55593. }
  55594. else {
  55595. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55596. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55597. if (t0 > t1) {
  55598. var temp = t1;
  55599. t1 = t0;
  55600. t0 = temp;
  55601. }
  55602. if (t0 > 1.0 || t1 < 0.0)
  55603. return;
  55604. if (t0 < 0)
  55605. t0 = 0;
  55606. if (t0 > 1.0)
  55607. t0 = 1.0;
  55608. }
  55609. this._collisionPoint.copyFromFloats(0, 0, 0);
  55610. var found = false;
  55611. var t = 1.0;
  55612. if (!embeddedInPlane) {
  55613. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55614. this._velocity.scaleToRef(t0, this._tempVector);
  55615. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55616. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55617. found = true;
  55618. t = t0;
  55619. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55620. }
  55621. }
  55622. if (!found) {
  55623. var velocitySquaredLength = this._velocity.lengthSquared();
  55624. var a = velocitySquaredLength;
  55625. this._basePoint.subtractToRef(p1, this._tempVector);
  55626. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55627. var c = this._tempVector.lengthSquared() - 1.0;
  55628. var lowestRoot = getLowestRoot(a, b, c, t);
  55629. if (lowestRoot.found) {
  55630. t = lowestRoot.root;
  55631. found = true;
  55632. this._collisionPoint.copyFrom(p1);
  55633. }
  55634. this._basePoint.subtractToRef(p2, this._tempVector);
  55635. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55636. c = this._tempVector.lengthSquared() - 1.0;
  55637. lowestRoot = getLowestRoot(a, b, c, t);
  55638. if (lowestRoot.found) {
  55639. t = lowestRoot.root;
  55640. found = true;
  55641. this._collisionPoint.copyFrom(p2);
  55642. }
  55643. this._basePoint.subtractToRef(p3, this._tempVector);
  55644. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55645. c = this._tempVector.lengthSquared() - 1.0;
  55646. lowestRoot = getLowestRoot(a, b, c, t);
  55647. if (lowestRoot.found) {
  55648. t = lowestRoot.root;
  55649. found = true;
  55650. this._collisionPoint.copyFrom(p3);
  55651. }
  55652. p2.subtractToRef(p1, this._edge);
  55653. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55654. var edgeSquaredLength = this._edge.lengthSquared();
  55655. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55656. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55657. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55658. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55659. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55660. lowestRoot = getLowestRoot(a, b, c, t);
  55661. if (lowestRoot.found) {
  55662. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55663. if (f >= 0.0 && f <= 1.0) {
  55664. t = lowestRoot.root;
  55665. found = true;
  55666. this._edge.scaleInPlace(f);
  55667. p1.addToRef(this._edge, this._collisionPoint);
  55668. }
  55669. }
  55670. p3.subtractToRef(p2, this._edge);
  55671. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55672. edgeSquaredLength = this._edge.lengthSquared();
  55673. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55674. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55675. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55676. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55677. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55678. lowestRoot = getLowestRoot(a, b, c, t);
  55679. if (lowestRoot.found) {
  55680. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55681. if (f >= 0.0 && f <= 1.0) {
  55682. t = lowestRoot.root;
  55683. found = true;
  55684. this._edge.scaleInPlace(f);
  55685. p2.addToRef(this._edge, this._collisionPoint);
  55686. }
  55687. }
  55688. p1.subtractToRef(p3, this._edge);
  55689. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55690. edgeSquaredLength = this._edge.lengthSquared();
  55691. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55692. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55693. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55694. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55695. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55696. lowestRoot = getLowestRoot(a, b, c, t);
  55697. if (lowestRoot.found) {
  55698. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55699. if (f >= 0.0 && f <= 1.0) {
  55700. t = lowestRoot.root;
  55701. found = true;
  55702. this._edge.scaleInPlace(f);
  55703. p3.addToRef(this._edge, this._collisionPoint);
  55704. }
  55705. }
  55706. }
  55707. if (found) {
  55708. var distToCollision = t * this._velocity.length();
  55709. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55710. if (!this.intersectionPoint) {
  55711. this.intersectionPoint = this._collisionPoint.clone();
  55712. }
  55713. else {
  55714. this.intersectionPoint.copyFrom(this._collisionPoint);
  55715. }
  55716. this._nearestDistance = distToCollision;
  55717. this.collisionFound = true;
  55718. }
  55719. }
  55720. };
  55721. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55722. for (var i = indexStart; i < indexEnd; i += 3) {
  55723. var p1 = pts[indices[i] - decal];
  55724. var p2 = pts[indices[i + 1] - decal];
  55725. var p3 = pts[indices[i + 2] - decal];
  55726. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55727. }
  55728. };
  55729. Collider.prototype._getResponse = function (pos, vel) {
  55730. pos.addToRef(vel, this._destinationPoint);
  55731. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55732. this._basePoint.addToRef(vel, pos);
  55733. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55734. this._slidePlaneNormal.normalize();
  55735. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55736. pos.addInPlace(this._displacementVector);
  55737. this.intersectionPoint.addInPlace(this._displacementVector);
  55738. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55739. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55740. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55741. };
  55742. return Collider;
  55743. }());
  55744. BABYLON.Collider = Collider;
  55745. })(BABYLON || (BABYLON = {}));
  55746. //# sourceMappingURL=babylon.collider.js.map
  55747. var BABYLON;
  55748. (function (BABYLON) {
  55749. //WebWorker code will be inserted to this variable.
  55750. BABYLON.CollisionWorker = "";
  55751. /** Defines supported task for worker process */
  55752. var WorkerTaskType;
  55753. (function (WorkerTaskType) {
  55754. /** Initialization */
  55755. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55756. /** Update of geometry */
  55757. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55758. /** Evaluate collision */
  55759. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55760. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55761. /** Defines kind of replies returned by worker */
  55762. var WorkerReplyType;
  55763. (function (WorkerReplyType) {
  55764. /** Success */
  55765. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55766. /** Unkown error */
  55767. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55768. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55769. var CollisionCoordinatorWorker = /** @class */ (function () {
  55770. function CollisionCoordinatorWorker() {
  55771. var _this = this;
  55772. this._scaledPosition = BABYLON.Vector3.Zero();
  55773. this._scaledVelocity = BABYLON.Vector3.Zero();
  55774. this.onMeshUpdated = function (transformNode) {
  55775. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55776. };
  55777. this.onGeometryUpdated = function (geometry) {
  55778. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55779. };
  55780. this._afterRender = function () {
  55781. if (!_this._init)
  55782. return;
  55783. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55784. return;
  55785. }
  55786. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55787. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55788. if (_this._runningUpdated > 4) {
  55789. return;
  55790. }
  55791. ++_this._runningUpdated;
  55792. var payload = {
  55793. updatedMeshes: _this._addUpdateMeshesList,
  55794. updatedGeometries: _this._addUpdateGeometriesList,
  55795. removedGeometries: _this._toRemoveGeometryArray,
  55796. removedMeshes: _this._toRemoveMeshesArray
  55797. };
  55798. var message = {
  55799. payload: payload,
  55800. taskType: WorkerTaskType.UPDATE
  55801. };
  55802. var serializable = [];
  55803. for (var id in payload.updatedGeometries) {
  55804. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55805. //prepare transferables
  55806. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55807. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55808. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55809. }
  55810. }
  55811. _this._worker.postMessage(message, serializable);
  55812. _this._addUpdateMeshesList = {};
  55813. _this._addUpdateGeometriesList = {};
  55814. _this._toRemoveGeometryArray = [];
  55815. _this._toRemoveMeshesArray = [];
  55816. };
  55817. this._onMessageFromWorker = function (e) {
  55818. var returnData = e.data;
  55819. if (returnData.error != WorkerReplyType.SUCCESS) {
  55820. //TODO what errors can be returned from the worker?
  55821. BABYLON.Tools.Warn("error returned from worker!");
  55822. return;
  55823. }
  55824. switch (returnData.taskType) {
  55825. case WorkerTaskType.INIT:
  55826. _this._init = true;
  55827. //Update the worked with ALL of the scene's current state
  55828. _this._scene.meshes.forEach(function (mesh) {
  55829. _this.onMeshAdded(mesh);
  55830. });
  55831. _this._scene.getGeometries().forEach(function (geometry) {
  55832. _this.onGeometryAdded(geometry);
  55833. });
  55834. break;
  55835. case WorkerTaskType.UPDATE:
  55836. _this._runningUpdated--;
  55837. break;
  55838. case WorkerTaskType.COLLIDE:
  55839. var returnPayload = returnData.payload;
  55840. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55841. return;
  55842. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55843. if (callback) {
  55844. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55845. if (mesh) {
  55846. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55847. }
  55848. }
  55849. //cleanup
  55850. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55851. break;
  55852. }
  55853. };
  55854. this._collisionsCallbackArray = [];
  55855. this._init = false;
  55856. this._runningUpdated = 0;
  55857. this._addUpdateMeshesList = {};
  55858. this._addUpdateGeometriesList = {};
  55859. this._toRemoveGeometryArray = [];
  55860. this._toRemoveMeshesArray = [];
  55861. }
  55862. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55863. if (!this._init)
  55864. return;
  55865. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55866. return;
  55867. position.divideToRef(collider._radius, this._scaledPosition);
  55868. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55869. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55870. var payload = {
  55871. collider: {
  55872. position: this._scaledPosition.asArray(),
  55873. velocity: this._scaledVelocity.asArray(),
  55874. radius: collider._radius.asArray()
  55875. },
  55876. collisionId: collisionIndex,
  55877. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55878. maximumRetry: maximumRetry
  55879. };
  55880. var message = {
  55881. payload: payload,
  55882. taskType: WorkerTaskType.COLLIDE
  55883. };
  55884. this._worker.postMessage(message);
  55885. };
  55886. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55887. this._scene = scene;
  55888. this._scene.registerAfterRender(this._afterRender);
  55889. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55890. this._worker = new Worker(workerUrl);
  55891. this._worker.onmessage = this._onMessageFromWorker;
  55892. var message = {
  55893. payload: {},
  55894. taskType: WorkerTaskType.INIT
  55895. };
  55896. this._worker.postMessage(message);
  55897. };
  55898. CollisionCoordinatorWorker.prototype.destroy = function () {
  55899. this._scene.unregisterAfterRender(this._afterRender);
  55900. this._worker.terminate();
  55901. };
  55902. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55903. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55904. this.onMeshUpdated(mesh);
  55905. };
  55906. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55907. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55908. };
  55909. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55910. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55911. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55912. this.onGeometryUpdated(geometry);
  55913. };
  55914. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55915. this._toRemoveGeometryArray.push(geometry.id);
  55916. };
  55917. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55918. var submeshes = [];
  55919. if (mesh.subMeshes) {
  55920. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55921. var boundingInfo = sm.getBoundingInfo();
  55922. return {
  55923. position: idx,
  55924. verticesStart: sm.verticesStart,
  55925. verticesCount: sm.verticesCount,
  55926. indexStart: sm.indexStart,
  55927. indexCount: sm.indexCount,
  55928. hasMaterial: !!sm.getMaterial(),
  55929. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55930. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55931. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55932. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55933. };
  55934. });
  55935. }
  55936. var geometryId = null;
  55937. if (mesh instanceof BABYLON.Mesh) {
  55938. var geometry = mesh.geometry;
  55939. geometryId = geometry ? geometry.id : null;
  55940. }
  55941. else if (mesh instanceof BABYLON.InstancedMesh) {
  55942. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55943. geometryId = geometry ? geometry.id : null;
  55944. }
  55945. var boundingInfo = mesh.getBoundingInfo();
  55946. return {
  55947. uniqueId: mesh.uniqueId,
  55948. id: mesh.id,
  55949. name: mesh.name,
  55950. geometryId: geometryId,
  55951. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55952. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55953. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55954. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55955. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55956. subMeshes: submeshes,
  55957. checkCollisions: mesh.checkCollisions
  55958. };
  55959. };
  55960. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55961. return {
  55962. id: geometry.id,
  55963. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55964. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55965. indices: new Uint32Array(geometry.getIndices() || []),
  55966. };
  55967. };
  55968. return CollisionCoordinatorWorker;
  55969. }());
  55970. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55971. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55972. function CollisionCoordinatorLegacy() {
  55973. this._scaledPosition = BABYLON.Vector3.Zero();
  55974. this._scaledVelocity = BABYLON.Vector3.Zero();
  55975. this._finalPosition = BABYLON.Vector3.Zero();
  55976. }
  55977. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55978. position.divideToRef(collider._radius, this._scaledPosition);
  55979. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55980. collider.collidedMesh = null;
  55981. collider._retry = 0;
  55982. collider._initialVelocity = this._scaledVelocity;
  55983. collider._initialPosition = this._scaledPosition;
  55984. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55985. this._finalPosition.multiplyInPlace(collider._radius);
  55986. //run the callback
  55987. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55988. };
  55989. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55990. this._scene = scene;
  55991. };
  55992. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55993. //Legacy need no destruction method.
  55994. };
  55995. //No update in legacy mode
  55996. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55997. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55998. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55999. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56000. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56001. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56002. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56003. if (excludedMesh === void 0) { excludedMesh = null; }
  56004. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56005. if (collider._retry >= maximumRetry) {
  56006. finalPosition.copyFrom(position);
  56007. return;
  56008. }
  56009. // Check if this is a mesh else camera or -1
  56010. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56011. collider._initialize(position, velocity, closeDistance);
  56012. // Check all meshes
  56013. for (var index = 0; index < this._scene.meshes.length; index++) {
  56014. var mesh = this._scene.meshes[index];
  56015. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56016. mesh._checkCollision(collider);
  56017. }
  56018. }
  56019. if (!collider.collisionFound) {
  56020. position.addToRef(velocity, finalPosition);
  56021. return;
  56022. }
  56023. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56024. collider._getResponse(position, velocity);
  56025. }
  56026. if (velocity.length() <= closeDistance) {
  56027. finalPosition.copyFrom(position);
  56028. return;
  56029. }
  56030. collider._retry++;
  56031. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56032. };
  56033. return CollisionCoordinatorLegacy;
  56034. }());
  56035. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56036. })(BABYLON || (BABYLON = {}));
  56037. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56038. var BABYLON;
  56039. (function (BABYLON) {
  56040. /**
  56041. * A particle represents one of the element emitted by a particle system.
  56042. * This is mainly define by its coordinates, direction, velocity and age.
  56043. */
  56044. var Particle = /** @class */ (function () {
  56045. /**
  56046. * Creates a new instance Particle
  56047. * @param particleSystem the particle system the particle belongs to
  56048. */
  56049. function Particle(
  56050. /**
  56051. * particleSystem the particle system the particle belongs to.
  56052. */
  56053. particleSystem) {
  56054. this.particleSystem = particleSystem;
  56055. /**
  56056. * The world position of the particle in the scene.
  56057. */
  56058. this.position = BABYLON.Vector3.Zero();
  56059. /**
  56060. * The world direction of the particle in the scene.
  56061. */
  56062. this.direction = BABYLON.Vector3.Zero();
  56063. /**
  56064. * The color of the particle.
  56065. */
  56066. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56067. /**
  56068. * The color change of the particle per step.
  56069. */
  56070. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56071. /**
  56072. * Defines how long will the life of the particle be.
  56073. */
  56074. this.lifeTime = 1.0;
  56075. /**
  56076. * The current age of the particle.
  56077. */
  56078. this.age = 0;
  56079. /**
  56080. * The current size of the particle.
  56081. */
  56082. this.size = 0;
  56083. /**
  56084. * The current angle of the particle.
  56085. */
  56086. this.angle = 0;
  56087. /**
  56088. * Defines how fast is the angle changing.
  56089. */
  56090. this.angularSpeed = 0;
  56091. /**
  56092. * Defines the cell index used by the particle to be rendered from a sprite.
  56093. */
  56094. this.cellIndex = 0;
  56095. this._currentFrameCounter = 0;
  56096. if (!this.particleSystem.isAnimationSheetEnabled) {
  56097. return;
  56098. }
  56099. this.updateCellInfoFromSystem();
  56100. }
  56101. Particle.prototype.updateCellInfoFromSystem = function () {
  56102. this.cellIndex = this.particleSystem.startSpriteCellID;
  56103. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  56104. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  56105. }
  56106. else {
  56107. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  56108. }
  56109. };
  56110. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  56111. // (ageOffset / scaledUpdateSpeed) / available cells
  56112. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  56113. this._currentFrameCounter += scaledUpdateSpeed;
  56114. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  56115. this._currentFrameCounter = 0;
  56116. this.cellIndex++;
  56117. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56118. this.cellIndex = this.particleSystem.endSpriteCellID;
  56119. }
  56120. }
  56121. };
  56122. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  56123. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  56124. this.cellIndex++;
  56125. this._currentFrameCounter = 0;
  56126. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  56127. if (this.particleSystem.spriteCellLoop) {
  56128. this.cellIndex = this.particleSystem.startSpriteCellID;
  56129. }
  56130. else {
  56131. this.cellIndex = this.particleSystem.endSpriteCellID;
  56132. }
  56133. }
  56134. }
  56135. else {
  56136. this._currentFrameCounter++;
  56137. }
  56138. };
  56139. /**
  56140. * Copy the properties of particle to another one.
  56141. * @param other the particle to copy the information to.
  56142. */
  56143. Particle.prototype.copyTo = function (other) {
  56144. other.position.copyFrom(this.position);
  56145. other.direction.copyFrom(this.direction);
  56146. other.color.copyFrom(this.color);
  56147. other.colorStep.copyFrom(this.colorStep);
  56148. other.lifeTime = this.lifeTime;
  56149. other.age = this.age;
  56150. other.size = this.size;
  56151. other.angle = this.angle;
  56152. other.angularSpeed = this.angularSpeed;
  56153. other.particleSystem = this.particleSystem;
  56154. other.cellIndex = this.cellIndex;
  56155. };
  56156. return Particle;
  56157. }());
  56158. BABYLON.Particle = Particle;
  56159. })(BABYLON || (BABYLON = {}));
  56160. //# sourceMappingURL=babylon.particle.js.map
  56161. var BABYLON;
  56162. (function (BABYLON) {
  56163. /**
  56164. * This represents a particle system in Babylon.
  56165. * 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.
  56166. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56167. * @example https://doc.babylonjs.com/babylon101/particles
  56168. */
  56169. var ParticleSystem = /** @class */ (function () {
  56170. /**
  56171. * Instantiates a particle system.
  56172. * 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.
  56173. * @param name The name of the particle system
  56174. * @param capacity The max number of particles alive at the same time
  56175. * @param scene The scene the particle system belongs to
  56176. * @param customEffect a custom effect used to change the way particles are rendered by default
  56177. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56178. * @param epsilon Offset used to render the particles
  56179. */
  56180. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56181. if (customEffect === void 0) { customEffect = null; }
  56182. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56183. if (epsilon === void 0) { epsilon = 0.01; }
  56184. var _this = this;
  56185. /**
  56186. * List of animations used by the particle system.
  56187. */
  56188. this.animations = [];
  56189. /**
  56190. * The rendering group used by the Particle system to chose when to render.
  56191. */
  56192. this.renderingGroupId = 0;
  56193. /**
  56194. * The emitter represents the Mesh or position we are attaching the particle system to.
  56195. */
  56196. this.emitter = null;
  56197. /**
  56198. * The maximum number of particles to emit per frame
  56199. */
  56200. this.emitRate = 10;
  56201. /**
  56202. * If you want to launch only a few particles at once, that can be done, as well.
  56203. */
  56204. this.manualEmitCount = -1;
  56205. /**
  56206. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56207. */
  56208. this.updateSpeed = 0.01;
  56209. /**
  56210. * The amount of time the particle system is running (depends of the overall update speed).
  56211. */
  56212. this.targetStopDuration = 0;
  56213. /**
  56214. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56215. */
  56216. this.disposeOnStop = false;
  56217. /**
  56218. * Minimum power of emitting particles.
  56219. */
  56220. this.minEmitPower = 1;
  56221. /**
  56222. * Maximum power of emitting particles.
  56223. */
  56224. this.maxEmitPower = 1;
  56225. /**
  56226. * Minimum life time of emitting particles.
  56227. */
  56228. this.minLifeTime = 1;
  56229. /**
  56230. * Maximum life time of emitting particles.
  56231. */
  56232. this.maxLifeTime = 1;
  56233. /**
  56234. * Minimum Size of emitting particles.
  56235. */
  56236. this.minSize = 1;
  56237. /**
  56238. * Maximum Size of emitting particles.
  56239. */
  56240. this.maxSize = 1;
  56241. /**
  56242. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56243. */
  56244. this.minAngularSpeed = 0;
  56245. /**
  56246. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56247. */
  56248. this.maxAngularSpeed = 0;
  56249. /**
  56250. * The layer mask we are rendering the particles through.
  56251. */
  56252. this.layerMask = 0x0FFFFFFF;
  56253. /**
  56254. * This can help using your own shader to render the particle system.
  56255. * The according effect will be created
  56256. */
  56257. this.customShader = null;
  56258. /**
  56259. * By default particle system starts as soon as they are created. This prevents the
  56260. * automatic start to happen and let you decide when to start emitting particles.
  56261. */
  56262. this.preventAutoStart = false;
  56263. /**
  56264. * Callback triggered when the particle animation is ending.
  56265. */
  56266. this.onAnimationEnd = null;
  56267. /**
  56268. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56269. */
  56270. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  56271. /**
  56272. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56273. * to override the particles.
  56274. */
  56275. this.forceDepthWrite = false;
  56276. /**
  56277. * You can use gravity if you want to give an orientation to your particles.
  56278. */
  56279. this.gravity = BABYLON.Vector3.Zero();
  56280. /**
  56281. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56282. */
  56283. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56284. /**
  56285. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56286. */
  56287. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56288. /**
  56289. * Color the particle will have at the end of its lifetime.
  56290. */
  56291. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56292. /**
  56293. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  56294. */
  56295. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56296. /**
  56297. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  56298. */
  56299. this.spriteCellLoop = true;
  56300. /**
  56301. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  56302. */
  56303. this.spriteCellChangeSpeed = 0;
  56304. /**
  56305. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  56306. */
  56307. this.startSpriteCellID = 0;
  56308. /**
  56309. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  56310. */
  56311. this.endSpriteCellID = 0;
  56312. /**
  56313. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  56314. */
  56315. this.spriteCellWidth = 0;
  56316. /**
  56317. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  56318. */
  56319. this.spriteCellHeight = 0;
  56320. /**
  56321. * An event triggered when the system is disposed.
  56322. */
  56323. this.onDisposeObservable = new BABYLON.Observable();
  56324. this._particles = new Array();
  56325. this._stockParticles = new Array();
  56326. this._newPartsExcess = 0;
  56327. this._vertexBuffers = {};
  56328. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56329. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56330. this._scaledDirection = BABYLON.Vector3.Zero();
  56331. this._scaledGravity = BABYLON.Vector3.Zero();
  56332. this._currentRenderId = -1;
  56333. this._started = false;
  56334. this._stopped = false;
  56335. this._actualFrame = 0;
  56336. this._vertexBufferSize = 11;
  56337. // start of sub system methods
  56338. /**
  56339. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56340. * Its lifetime will start back at 0.
  56341. */
  56342. this.recycleParticle = function (particle) {
  56343. var lastParticle = _this._particles.pop();
  56344. if (lastParticle !== particle) {
  56345. lastParticle.copyTo(particle);
  56346. }
  56347. _this._stockParticles.push(lastParticle);
  56348. };
  56349. this._createParticle = function () {
  56350. var particle;
  56351. if (_this._stockParticles.length !== 0) {
  56352. particle = _this._stockParticles.pop();
  56353. particle.age = 0;
  56354. particle.cellIndex = _this.startSpriteCellID;
  56355. }
  56356. else {
  56357. particle = new BABYLON.Particle(_this);
  56358. }
  56359. return particle;
  56360. };
  56361. this._emitFromParticle = function (particle) {
  56362. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56363. return;
  56364. }
  56365. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56366. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56367. subSystem._rootParticleSystem = _this;
  56368. _this.activeSubSystems.push(subSystem);
  56369. subSystem.start();
  56370. };
  56371. this._appendParticleVertexes = null;
  56372. this.id = name;
  56373. this.name = name;
  56374. this._capacity = capacity;
  56375. this._epsilon = epsilon;
  56376. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56377. if (isAnimationSheetEnabled) {
  56378. this._vertexBufferSize = 12;
  56379. }
  56380. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56381. this._customEffect = customEffect;
  56382. scene.particleSystems.push(this);
  56383. this._createIndexBuffer();
  56384. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  56385. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  56386. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  56387. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  56388. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  56389. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  56390. if (this._isAnimationSheetEnabled) {
  56391. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56392. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56393. }
  56394. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56395. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56396. this._vertexBuffers["options"] = options;
  56397. // Default emitter type
  56398. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56399. this.updateFunction = function (particles) {
  56400. for (var index = 0; index < particles.length; index++) {
  56401. var particle = particles[index];
  56402. particle.age += _this._scaledUpdateSpeed;
  56403. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56404. _this._emitFromParticle(particle);
  56405. _this.recycleParticle(particle);
  56406. index--;
  56407. continue;
  56408. }
  56409. else {
  56410. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56411. particle.color.addInPlace(_this._scaledColorStep);
  56412. if (particle.color.a < 0)
  56413. particle.color.a = 0;
  56414. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56415. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56416. particle.position.addInPlace(_this._scaledDirection);
  56417. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56418. particle.direction.addInPlace(_this._scaledGravity);
  56419. if (_this._isAnimationSheetEnabled) {
  56420. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56421. }
  56422. }
  56423. }
  56424. };
  56425. }
  56426. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56427. /**
  56428. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56429. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56430. */
  56431. get: function () {
  56432. if (this.particleEmitterType.direction1) {
  56433. return this.particleEmitterType.direction1;
  56434. }
  56435. return BABYLON.Vector3.Zero();
  56436. },
  56437. set: function (value) {
  56438. if (this.particleEmitterType.direction1) {
  56439. this.particleEmitterType.direction1 = value;
  56440. }
  56441. },
  56442. enumerable: true,
  56443. configurable: true
  56444. });
  56445. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56446. /**
  56447. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56448. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56449. */
  56450. get: function () {
  56451. if (this.particleEmitterType.direction2) {
  56452. return this.particleEmitterType.direction2;
  56453. }
  56454. return BABYLON.Vector3.Zero();
  56455. },
  56456. set: function (value) {
  56457. if (this.particleEmitterType.direction2) {
  56458. this.particleEmitterType.direction2 = value;
  56459. }
  56460. },
  56461. enumerable: true,
  56462. configurable: true
  56463. });
  56464. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56465. /**
  56466. * 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.
  56467. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56468. */
  56469. get: function () {
  56470. if (this.particleEmitterType.minEmitBox) {
  56471. return this.particleEmitterType.minEmitBox;
  56472. }
  56473. return BABYLON.Vector3.Zero();
  56474. },
  56475. set: function (value) {
  56476. if (this.particleEmitterType.minEmitBox) {
  56477. this.particleEmitterType.minEmitBox = value;
  56478. }
  56479. },
  56480. enumerable: true,
  56481. configurable: true
  56482. });
  56483. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56484. /**
  56485. * 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.
  56486. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56487. */
  56488. get: function () {
  56489. if (this.particleEmitterType.maxEmitBox) {
  56490. return this.particleEmitterType.maxEmitBox;
  56491. }
  56492. return BABYLON.Vector3.Zero();
  56493. },
  56494. set: function (value) {
  56495. if (this.particleEmitterType.maxEmitBox) {
  56496. this.particleEmitterType.maxEmitBox = value;
  56497. }
  56498. },
  56499. enumerable: true,
  56500. configurable: true
  56501. });
  56502. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56503. /**
  56504. * Sets a callback that will be triggered when the system is disposed.
  56505. */
  56506. set: function (callback) {
  56507. if (this._onDisposeObserver) {
  56508. this.onDisposeObservable.remove(this._onDisposeObserver);
  56509. }
  56510. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56511. },
  56512. enumerable: true,
  56513. configurable: true
  56514. });
  56515. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56516. /**
  56517. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56518. */
  56519. get: function () {
  56520. return this._isAnimationSheetEnabled;
  56521. },
  56522. enumerable: true,
  56523. configurable: true
  56524. });
  56525. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56526. //end of Sub-emitter
  56527. /**
  56528. * Gets the current list of active particles
  56529. */
  56530. get: function () {
  56531. return this._particles;
  56532. },
  56533. enumerable: true,
  56534. configurable: true
  56535. });
  56536. /**
  56537. * Returns the string "ParticleSystem"
  56538. * @returns a string containing the class name
  56539. */
  56540. ParticleSystem.prototype.getClassName = function () {
  56541. return "ParticleSystem";
  56542. };
  56543. ParticleSystem.prototype._createIndexBuffer = function () {
  56544. var indices = [];
  56545. var index = 0;
  56546. for (var count = 0; count < this._capacity; count++) {
  56547. indices.push(index);
  56548. indices.push(index + 1);
  56549. indices.push(index + 2);
  56550. indices.push(index);
  56551. indices.push(index + 2);
  56552. indices.push(index + 3);
  56553. index += 4;
  56554. }
  56555. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56556. };
  56557. /**
  56558. * Gets the maximum number of particles active at the same time.
  56559. * @returns The max number of active particles.
  56560. */
  56561. ParticleSystem.prototype.getCapacity = function () {
  56562. return this._capacity;
  56563. };
  56564. /**
  56565. * Gets Wether there are still active particles in the system.
  56566. * @returns True if it is alive, otherwise false.
  56567. */
  56568. ParticleSystem.prototype.isAlive = function () {
  56569. return this._alive;
  56570. };
  56571. /**
  56572. * Gets Wether the system has been started.
  56573. * @returns True if it has been started, otherwise false.
  56574. */
  56575. ParticleSystem.prototype.isStarted = function () {
  56576. return this._started;
  56577. };
  56578. /**
  56579. * Starts the particle system and begins to emit.
  56580. */
  56581. ParticleSystem.prototype.start = function () {
  56582. this._started = true;
  56583. this._stopped = false;
  56584. this._actualFrame = 0;
  56585. if (this.subEmitters && this.subEmitters.length != 0) {
  56586. this.activeSubSystems = new Array();
  56587. }
  56588. };
  56589. /**
  56590. * Stops the particle system.
  56591. * @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.
  56592. */
  56593. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56594. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56595. this._stopped = true;
  56596. if (stopSubEmitters) {
  56597. this._stopSubEmitters();
  56598. }
  56599. };
  56600. // animation sheet
  56601. /**
  56602. * Remove all active particles
  56603. */
  56604. ParticleSystem.prototype.reset = function () {
  56605. this._stockParticles = [];
  56606. this._particles = [];
  56607. };
  56608. /**
  56609. * @hidden (for internal use only)
  56610. */
  56611. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56612. var offset = index * this._vertexBufferSize;
  56613. this._vertexData[offset] = particle.position.x;
  56614. this._vertexData[offset + 1] = particle.position.y;
  56615. this._vertexData[offset + 2] = particle.position.z;
  56616. this._vertexData[offset + 3] = particle.color.r;
  56617. this._vertexData[offset + 4] = particle.color.g;
  56618. this._vertexData[offset + 5] = particle.color.b;
  56619. this._vertexData[offset + 6] = particle.color.a;
  56620. this._vertexData[offset + 7] = particle.angle;
  56621. this._vertexData[offset + 8] = particle.size;
  56622. this._vertexData[offset + 9] = offsetX;
  56623. this._vertexData[offset + 10] = offsetY;
  56624. };
  56625. /**
  56626. * @hidden (for internal use only)
  56627. */
  56628. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56629. if (offsetX === 0)
  56630. offsetX = this._epsilon;
  56631. else if (offsetX === 1)
  56632. offsetX = 1 - this._epsilon;
  56633. if (offsetY === 0)
  56634. offsetY = this._epsilon;
  56635. else if (offsetY === 1)
  56636. offsetY = 1 - this._epsilon;
  56637. var offset = index * this._vertexBufferSize;
  56638. this._vertexData[offset] = particle.position.x;
  56639. this._vertexData[offset + 1] = particle.position.y;
  56640. this._vertexData[offset + 2] = particle.position.z;
  56641. this._vertexData[offset + 3] = particle.color.r;
  56642. this._vertexData[offset + 4] = particle.color.g;
  56643. this._vertexData[offset + 5] = particle.color.b;
  56644. this._vertexData[offset + 6] = particle.color.a;
  56645. this._vertexData[offset + 7] = particle.angle;
  56646. this._vertexData[offset + 8] = particle.size;
  56647. this._vertexData[offset + 9] = offsetX;
  56648. this._vertexData[offset + 10] = offsetY;
  56649. this._vertexData[offset + 11] = particle.cellIndex;
  56650. };
  56651. ParticleSystem.prototype._stopSubEmitters = function () {
  56652. if (!this.activeSubSystems) {
  56653. return;
  56654. }
  56655. this.activeSubSystems.forEach(function (subSystem) {
  56656. subSystem.stop(true);
  56657. });
  56658. this.activeSubSystems = new Array();
  56659. };
  56660. ParticleSystem.prototype._removeFromRoot = function () {
  56661. if (!this._rootParticleSystem) {
  56662. return;
  56663. }
  56664. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56665. if (index !== -1) {
  56666. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56667. }
  56668. };
  56669. // end of sub system methods
  56670. ParticleSystem.prototype._update = function (newParticles) {
  56671. // Update current
  56672. this._alive = this._particles.length > 0;
  56673. this.updateFunction(this._particles);
  56674. // Add new ones
  56675. var worldMatrix;
  56676. if (this.emitter.position) {
  56677. var emitterMesh = this.emitter;
  56678. worldMatrix = emitterMesh.getWorldMatrix();
  56679. }
  56680. else {
  56681. var emitterPosition = this.emitter;
  56682. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56683. }
  56684. var particle;
  56685. for (var index = 0; index < newParticles; index++) {
  56686. if (this._particles.length === this._capacity) {
  56687. break;
  56688. }
  56689. particle = this._createParticle();
  56690. this._particles.push(particle);
  56691. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56692. if (this.startPositionFunction) {
  56693. this.startPositionFunction(worldMatrix, particle.position, particle);
  56694. }
  56695. else {
  56696. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56697. }
  56698. if (this.startDirectionFunction) {
  56699. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56700. }
  56701. else {
  56702. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56703. }
  56704. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56705. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56706. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56707. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56708. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56709. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56710. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56711. }
  56712. };
  56713. ParticleSystem.prototype._getEffect = function () {
  56714. if (this._customEffect) {
  56715. return this._customEffect;
  56716. }
  56717. ;
  56718. var defines = [];
  56719. if (this._scene.clipPlane) {
  56720. defines.push("#define CLIPPLANE");
  56721. }
  56722. if (this._isAnimationSheetEnabled) {
  56723. defines.push("#define ANIMATESHEET");
  56724. }
  56725. // Effect
  56726. var join = defines.join("\n");
  56727. if (this._cachedDefines !== join) {
  56728. this._cachedDefines = join;
  56729. var attributesNamesOrOptions;
  56730. var effectCreationOption;
  56731. if (this._isAnimationSheetEnabled) {
  56732. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56733. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56734. }
  56735. else {
  56736. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56737. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56738. }
  56739. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56740. }
  56741. return this._effect;
  56742. };
  56743. /**
  56744. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56745. */
  56746. ParticleSystem.prototype.animate = function () {
  56747. if (!this._started)
  56748. return;
  56749. var effect = this._getEffect();
  56750. // Check
  56751. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56752. return;
  56753. if (this._currentRenderId === this._scene.getRenderId()) {
  56754. return;
  56755. }
  56756. this._currentRenderId = this._scene.getRenderId();
  56757. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56758. // determine the number of particles we need to create
  56759. var newParticles;
  56760. if (this.manualEmitCount > -1) {
  56761. newParticles = this.manualEmitCount;
  56762. this._newPartsExcess = 0;
  56763. this.manualEmitCount = 0;
  56764. }
  56765. else {
  56766. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56767. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56768. }
  56769. if (this._newPartsExcess > 1.0) {
  56770. newParticles += this._newPartsExcess >> 0;
  56771. this._newPartsExcess -= this._newPartsExcess >> 0;
  56772. }
  56773. this._alive = false;
  56774. if (!this._stopped) {
  56775. this._actualFrame += this._scaledUpdateSpeed;
  56776. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56777. this.stop();
  56778. }
  56779. else {
  56780. newParticles = 0;
  56781. }
  56782. this._update(newParticles);
  56783. // Stopped?
  56784. if (this._stopped) {
  56785. if (!this._alive) {
  56786. this._started = false;
  56787. if (this.onAnimationEnd) {
  56788. this.onAnimationEnd();
  56789. }
  56790. if (this.disposeOnStop) {
  56791. this._scene._toBeDisposed.push(this);
  56792. }
  56793. }
  56794. }
  56795. // Animation sheet
  56796. if (this._isAnimationSheetEnabled) {
  56797. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56798. }
  56799. else {
  56800. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56801. }
  56802. // Update VBO
  56803. var offset = 0;
  56804. for (var index = 0; index < this._particles.length; index++) {
  56805. var particle = this._particles[index];
  56806. this._appendParticleVertexes(offset, particle);
  56807. offset += 4;
  56808. }
  56809. if (this._vertexBuffer) {
  56810. this._vertexBuffer.update(this._vertexData);
  56811. }
  56812. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56813. this.stop();
  56814. }
  56815. };
  56816. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56817. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56818. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56819. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56820. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56821. };
  56822. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56823. this._appendParticleVertex(offset++, particle, 0, 0);
  56824. this._appendParticleVertex(offset++, particle, 1, 0);
  56825. this._appendParticleVertex(offset++, particle, 1, 1);
  56826. this._appendParticleVertex(offset++, particle, 0, 1);
  56827. };
  56828. /**
  56829. * Rebuilds the particle system.
  56830. */
  56831. ParticleSystem.prototype.rebuild = function () {
  56832. this._createIndexBuffer();
  56833. if (this._vertexBuffer) {
  56834. this._vertexBuffer._rebuild();
  56835. }
  56836. };
  56837. /**
  56838. * Is this system ready to be used/rendered
  56839. * @return true if the system is ready
  56840. */
  56841. ParticleSystem.prototype.isReady = function () {
  56842. var effect = this._getEffect();
  56843. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56844. return false;
  56845. }
  56846. return true;
  56847. };
  56848. /**
  56849. * Renders the particle system in its current state.
  56850. * @returns the current number of particles
  56851. */
  56852. ParticleSystem.prototype.render = function () {
  56853. var effect = this._getEffect();
  56854. // Check
  56855. if (!this.isReady() || !this._particles.length) {
  56856. return 0;
  56857. }
  56858. var engine = this._scene.getEngine();
  56859. // Render
  56860. engine.enableEffect(effect);
  56861. engine.setState(false);
  56862. var viewMatrix = this._scene.getViewMatrix();
  56863. effect.setTexture("diffuseSampler", this.particleTexture);
  56864. effect.setMatrix("view", viewMatrix);
  56865. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56866. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56867. var baseSize = this.particleTexture.getBaseSize();
  56868. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56869. }
  56870. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56871. if (this._scene.clipPlane) {
  56872. var clipPlane = this._scene.clipPlane;
  56873. var invView = viewMatrix.clone();
  56874. invView.invert();
  56875. effect.setMatrix("invView", invView);
  56876. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56877. }
  56878. // VBOs
  56879. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56880. // Draw order
  56881. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56882. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56883. }
  56884. else {
  56885. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56886. }
  56887. if (this.forceDepthWrite) {
  56888. engine.setDepthWrite(true);
  56889. }
  56890. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56891. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56892. return this._particles.length;
  56893. };
  56894. /**
  56895. * Disposes the particle system and free the associated resources
  56896. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56897. */
  56898. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56899. if (disposeTexture === void 0) { disposeTexture = true; }
  56900. if (this._vertexBuffer) {
  56901. this._vertexBuffer.dispose();
  56902. this._vertexBuffer = null;
  56903. }
  56904. if (this._indexBuffer) {
  56905. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56906. this._indexBuffer = null;
  56907. }
  56908. if (disposeTexture && this.particleTexture) {
  56909. this.particleTexture.dispose();
  56910. this.particleTexture = null;
  56911. }
  56912. this._removeFromRoot();
  56913. // Remove from scene
  56914. var index = this._scene.particleSystems.indexOf(this);
  56915. if (index > -1) {
  56916. this._scene.particleSystems.splice(index, 1);
  56917. }
  56918. // Callback
  56919. this.onDisposeObservable.notifyObservers(this);
  56920. this.onDisposeObservable.clear();
  56921. };
  56922. /**
  56923. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56924. * @param radius The radius of the sphere to emit from
  56925. * @returns the emitter
  56926. */
  56927. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56928. if (radius === void 0) { radius = 1; }
  56929. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56930. this.particleEmitterType = particleEmitter;
  56931. return particleEmitter;
  56932. };
  56933. /**
  56934. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56935. * @param radius The radius of the sphere to emit from
  56936. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56937. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56938. * @returns the emitter
  56939. */
  56940. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56941. if (radius === void 0) { radius = 1; }
  56942. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56943. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56944. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56945. this.particleEmitterType = particleEmitter;
  56946. return particleEmitter;
  56947. };
  56948. /**
  56949. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56950. * @param radius The radius of the cone to emit from
  56951. * @param angle The base angle of the cone
  56952. * @returns the emitter
  56953. */
  56954. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56955. if (radius === void 0) { radius = 1; }
  56956. if (angle === void 0) { angle = Math.PI / 4; }
  56957. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56958. this.particleEmitterType = particleEmitter;
  56959. return particleEmitter;
  56960. };
  56961. // 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.
  56962. /**
  56963. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56964. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56965. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56966. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56967. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56968. * @returns the emitter
  56969. */
  56970. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56971. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56972. this.particleEmitterType = particleEmitter;
  56973. this.direction1 = direction1;
  56974. this.direction2 = direction2;
  56975. this.minEmitBox = minEmitBox;
  56976. this.maxEmitBox = maxEmitBox;
  56977. return particleEmitter;
  56978. };
  56979. // Clone
  56980. /**
  56981. * Clones the particle system.
  56982. * @param name The name of the cloned object
  56983. * @param newEmitter The new emitter to use
  56984. * @returns the cloned particle system
  56985. */
  56986. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56987. var custom = null;
  56988. var program = null;
  56989. if (this.customShader != null) {
  56990. program = this.customShader;
  56991. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56992. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56993. }
  56994. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56995. result.customShader = program;
  56996. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56997. if (newEmitter === undefined) {
  56998. newEmitter = this.emitter;
  56999. }
  57000. result.emitter = newEmitter;
  57001. if (this.particleTexture) {
  57002. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57003. }
  57004. if (!this.preventAutoStart) {
  57005. result.start();
  57006. }
  57007. return result;
  57008. };
  57009. /**
  57010. * Serializes the particle system to a JSON object.
  57011. * @returns the JSON object
  57012. */
  57013. ParticleSystem.prototype.serialize = function () {
  57014. var serializationObject = {};
  57015. serializationObject.name = this.name;
  57016. serializationObject.id = this.id;
  57017. // Emitter
  57018. if (this.emitter.position) {
  57019. var emitterMesh = this.emitter;
  57020. serializationObject.emitterId = emitterMesh.id;
  57021. }
  57022. else {
  57023. var emitterPosition = this.emitter;
  57024. serializationObject.emitter = emitterPosition.asArray();
  57025. }
  57026. serializationObject.capacity = this.getCapacity();
  57027. if (this.particleTexture) {
  57028. serializationObject.textureName = this.particleTexture.name;
  57029. }
  57030. // Animations
  57031. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57032. // Particle system
  57033. serializationObject.minAngularSpeed = this.minAngularSpeed;
  57034. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  57035. serializationObject.minSize = this.minSize;
  57036. serializationObject.maxSize = this.maxSize;
  57037. serializationObject.minEmitPower = this.minEmitPower;
  57038. serializationObject.maxEmitPower = this.maxEmitPower;
  57039. serializationObject.minLifeTime = this.minLifeTime;
  57040. serializationObject.maxLifeTime = this.maxLifeTime;
  57041. serializationObject.emitRate = this.emitRate;
  57042. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57043. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57044. serializationObject.gravity = this.gravity.asArray();
  57045. serializationObject.direction1 = this.direction1.asArray();
  57046. serializationObject.direction2 = this.direction2.asArray();
  57047. serializationObject.color1 = this.color1.asArray();
  57048. serializationObject.color2 = this.color2.asArray();
  57049. serializationObject.colorDead = this.colorDead.asArray();
  57050. serializationObject.updateSpeed = this.updateSpeed;
  57051. serializationObject.targetStopDuration = this.targetStopDuration;
  57052. serializationObject.textureMask = this.textureMask.asArray();
  57053. serializationObject.blendMode = this.blendMode;
  57054. serializationObject.customShader = this.customShader;
  57055. serializationObject.preventAutoStart = this.preventAutoStart;
  57056. serializationObject.startSpriteCellID = this.startSpriteCellID;
  57057. serializationObject.endSpriteCellID = this.endSpriteCellID;
  57058. serializationObject.spriteCellLoop = this.spriteCellLoop;
  57059. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  57060. serializationObject.spriteCellWidth = this.spriteCellWidth;
  57061. serializationObject.spriteCellHeight = this.spriteCellHeight;
  57062. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57063. // Emitter
  57064. if (this.particleEmitterType) {
  57065. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57066. }
  57067. return serializationObject;
  57068. };
  57069. /**
  57070. * Parses a JSON object to create a particle system.
  57071. * @param parsedParticleSystem The JSON object to parse
  57072. * @param scene The scene to create the particle system in
  57073. * @param rootUrl The root url to use to load external dependencies like texture
  57074. * @returns the Parsed particle system
  57075. */
  57076. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57077. var name = parsedParticleSystem.name;
  57078. var custom = null;
  57079. var program = null;
  57080. if (parsedParticleSystem.customShader) {
  57081. program = parsedParticleSystem.customShader;
  57082. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57083. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57084. }
  57085. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57086. particleSystem.customShader = program;
  57087. if (parsedParticleSystem.id) {
  57088. particleSystem.id = parsedParticleSystem.id;
  57089. }
  57090. // Auto start
  57091. if (parsedParticleSystem.preventAutoStart) {
  57092. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57093. }
  57094. // Texture
  57095. if (parsedParticleSystem.textureName) {
  57096. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57097. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57098. }
  57099. // Emitter
  57100. if (parsedParticleSystem.emitterId) {
  57101. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57102. }
  57103. else {
  57104. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57105. }
  57106. // Animations
  57107. if (parsedParticleSystem.animations) {
  57108. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57109. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57110. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57111. }
  57112. }
  57113. if (parsedParticleSystem.autoAnimate) {
  57114. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57115. }
  57116. // Particle system
  57117. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57118. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57119. particleSystem.minSize = parsedParticleSystem.minSize;
  57120. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57121. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57122. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57123. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57124. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57125. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57126. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  57127. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  57128. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57129. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  57130. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  57131. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57132. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57133. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57134. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57135. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57136. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57137. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57138. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57139. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57140. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  57141. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57142. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57143. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57144. if (!particleSystem.preventAutoStart) {
  57145. particleSystem.start();
  57146. }
  57147. return particleSystem;
  57148. };
  57149. /**
  57150. * Source color is added to the destination color without alpha affecting the result.
  57151. */
  57152. ParticleSystem.BLENDMODE_ONEONE = 0;
  57153. /**
  57154. * Blend current color and particle color using particle’s alpha.
  57155. */
  57156. ParticleSystem.BLENDMODE_STANDARD = 1;
  57157. return ParticleSystem;
  57158. }());
  57159. BABYLON.ParticleSystem = ParticleSystem;
  57160. })(BABYLON || (BABYLON = {}));
  57161. //# sourceMappingURL=babylon.particleSystem.js.map
  57162. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  57163. var BABYLON;
  57164. (function (BABYLON) {
  57165. /**
  57166. * Particle emitter emitting particles from the inside of a box.
  57167. * It emits the particles randomly between 2 given directions.
  57168. */
  57169. var BoxParticleEmitter = /** @class */ (function () {
  57170. /**
  57171. * Creates a new instance BoxParticleEmitter
  57172. */
  57173. function BoxParticleEmitter() {
  57174. /**
  57175. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57176. */
  57177. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57178. /**
  57179. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57180. */
  57181. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57182. /**
  57183. * 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.
  57184. */
  57185. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57186. /**
  57187. * 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.
  57188. */
  57189. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57190. }
  57191. /**
  57192. * Called by the particle System when the direction is computed for the created particle.
  57193. * @param emitPower is the power of the particle (speed)
  57194. * @param worldMatrix is the world matrix of the particle system
  57195. * @param directionToUpdate is the direction vector to update with the result
  57196. * @param particle is the particle we are computed the direction for
  57197. */
  57198. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57199. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57200. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57201. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57202. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57203. };
  57204. /**
  57205. * Called by the particle System when the position is computed for the created particle.
  57206. * @param worldMatrix is the world matrix of the particle system
  57207. * @param positionToUpdate is the position vector to update with the result
  57208. * @param particle is the particle we are computed the position for
  57209. */
  57210. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57211. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57212. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57213. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57214. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57215. };
  57216. /**
  57217. * Clones the current emitter and returns a copy of it
  57218. * @returns the new emitter
  57219. */
  57220. BoxParticleEmitter.prototype.clone = function () {
  57221. var newOne = new BoxParticleEmitter();
  57222. BABYLON.Tools.DeepCopy(this, newOne);
  57223. return newOne;
  57224. };
  57225. /**
  57226. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57227. * @param effect defines the update shader
  57228. */
  57229. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57230. effect.setVector3("direction1", this.direction1);
  57231. effect.setVector3("direction2", this.direction2);
  57232. effect.setVector3("minEmitBox", this.minEmitBox);
  57233. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57234. };
  57235. /**
  57236. * Returns a string to use to update the GPU particles update shader
  57237. * @returns a string containng the defines string
  57238. */
  57239. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57240. return "#define BOXEMITTER";
  57241. };
  57242. /**
  57243. * Returns the string "BoxEmitter"
  57244. * @returns a string containing the class name
  57245. */
  57246. BoxParticleEmitter.prototype.getClassName = function () {
  57247. return "BoxEmitter";
  57248. };
  57249. /**
  57250. * Serializes the particle system to a JSON object.
  57251. * @returns the JSON object
  57252. */
  57253. BoxParticleEmitter.prototype.serialize = function () {
  57254. var serializationObject = {};
  57255. serializationObject.type = this.getClassName();
  57256. serializationObject.direction1 = this.direction1.asArray();
  57257. serializationObject.direction2 = this.direction2.asArray();
  57258. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57259. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57260. return serializationObject;
  57261. };
  57262. /**
  57263. * Parse properties from a JSON object
  57264. * @param serializationObject defines the JSON object
  57265. */
  57266. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57267. this.direction1.copyFrom(serializationObject.direction1);
  57268. this.direction2.copyFrom(serializationObject.direction2);
  57269. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  57270. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  57271. };
  57272. return BoxParticleEmitter;
  57273. }());
  57274. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57275. })(BABYLON || (BABYLON = {}));
  57276. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57277. var BABYLON;
  57278. (function (BABYLON) {
  57279. /**
  57280. * Particle emitter emitting particles from the inside of a cone.
  57281. * It emits the particles alongside the cone volume from the base to the particle.
  57282. * The emission direction might be randomized.
  57283. */
  57284. var ConeParticleEmitter = /** @class */ (function () {
  57285. /**
  57286. * Creates a new instance ConeParticleEmitter
  57287. * @param radius the radius of the emission cone (1 by default)
  57288. * @param angles the cone base angle (PI by default)
  57289. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57290. */
  57291. function ConeParticleEmitter(radius,
  57292. /**
  57293. * The radius of the emission cone.
  57294. */
  57295. angle,
  57296. /**
  57297. * The cone base angle.
  57298. */
  57299. directionRandomizer) {
  57300. if (radius === void 0) { radius = 1; }
  57301. if (angle === void 0) { angle = Math.PI; }
  57302. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57303. this.angle = angle;
  57304. this.directionRandomizer = directionRandomizer;
  57305. this.radius = radius;
  57306. }
  57307. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57308. /**
  57309. * Gets the radius of the emission cone.
  57310. */
  57311. get: function () {
  57312. return this._radius;
  57313. },
  57314. /**
  57315. * Sets the radius of the emission cone.
  57316. */
  57317. set: function (value) {
  57318. this._radius = value;
  57319. if (this.angle !== 0) {
  57320. this._height = value / Math.tan(this.angle / 2);
  57321. }
  57322. else {
  57323. this._height = 1;
  57324. }
  57325. },
  57326. enumerable: true,
  57327. configurable: true
  57328. });
  57329. /**
  57330. * Called by the particle System when the direction is computed for the created particle.
  57331. * @param emitPower is the power of the particle (speed)
  57332. * @param worldMatrix is the world matrix of the particle system
  57333. * @param directionToUpdate is the direction vector to update with the result
  57334. * @param particle is the particle we are computed the direction for
  57335. */
  57336. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57337. if (this.angle === 0) {
  57338. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  57339. }
  57340. else {
  57341. // measure the direction Vector from the emitter to the particle.
  57342. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57343. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57344. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57345. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57346. direction.x += randX;
  57347. direction.y += randY;
  57348. direction.z += randZ;
  57349. direction.normalize();
  57350. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57351. }
  57352. };
  57353. /**
  57354. * Called by the particle System when the position is computed for the created particle.
  57355. * @param worldMatrix is the world matrix of the particle system
  57356. * @param positionToUpdate is the position vector to update with the result
  57357. * @param particle is the particle we are computed the position for
  57358. */
  57359. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57360. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57361. var h = BABYLON.Scalar.RandomRange(0, 1);
  57362. // Better distribution in a cone at normal angles.
  57363. h = 1 - h * h;
  57364. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  57365. radius = radius * h;
  57366. var randX = radius * Math.sin(s);
  57367. var randZ = radius * Math.cos(s);
  57368. var randY = h * this._height;
  57369. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57370. };
  57371. /**
  57372. * Clones the current emitter and returns a copy of it
  57373. * @returns the new emitter
  57374. */
  57375. ConeParticleEmitter.prototype.clone = function () {
  57376. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  57377. BABYLON.Tools.DeepCopy(this, newOne);
  57378. return newOne;
  57379. };
  57380. /**
  57381. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57382. * @param effect defines the update shader
  57383. */
  57384. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57385. effect.setFloat("radius", this.radius);
  57386. effect.setFloat("coneAngle", this.angle);
  57387. effect.setFloat("height", this._height);
  57388. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57389. };
  57390. /**
  57391. * Returns a string to use to update the GPU particles update shader
  57392. * @returns a string containng the defines string
  57393. */
  57394. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57395. return "#define CONEEMITTER";
  57396. };
  57397. /**
  57398. * Returns the string "BoxEmitter"
  57399. * @returns a string containing the class name
  57400. */
  57401. ConeParticleEmitter.prototype.getClassName = function () {
  57402. return "ConeEmitter";
  57403. };
  57404. /**
  57405. * Serializes the particle system to a JSON object.
  57406. * @returns the JSON object
  57407. */
  57408. ConeParticleEmitter.prototype.serialize = function () {
  57409. var serializationObject = {};
  57410. serializationObject.type = this.getClassName();
  57411. serializationObject.radius = this.radius;
  57412. serializationObject.angle = this.angle;
  57413. serializationObject.directionRandomizer = this.directionRandomizer;
  57414. return serializationObject;
  57415. };
  57416. /**
  57417. * Parse properties from a JSON object
  57418. * @param serializationObject defines the JSON object
  57419. */
  57420. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57421. this.radius = serializationObject.radius;
  57422. this.angle = serializationObject.angle;
  57423. this.directionRandomizer = serializationObject.directionRandomizer;
  57424. };
  57425. return ConeParticleEmitter;
  57426. }());
  57427. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57428. })(BABYLON || (BABYLON = {}));
  57429. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57430. var BABYLON;
  57431. (function (BABYLON) {
  57432. /**
  57433. * Particle emitter emitting particles from the inside of a sphere.
  57434. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57435. */
  57436. var SphereParticleEmitter = /** @class */ (function () {
  57437. /**
  57438. * Creates a new instance SphereParticleEmitter
  57439. * @param radius the radius of the emission sphere (1 by default)
  57440. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57441. */
  57442. function SphereParticleEmitter(
  57443. /**
  57444. * The radius of the emission sphere.
  57445. */
  57446. radius,
  57447. /**
  57448. * How much to randomize the particle direction [0-1].
  57449. */
  57450. directionRandomizer) {
  57451. if (radius === void 0) { radius = 1; }
  57452. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57453. this.radius = radius;
  57454. this.directionRandomizer = directionRandomizer;
  57455. }
  57456. /**
  57457. * Called by the particle System when the direction is computed for the created particle.
  57458. * @param emitPower is the power of the particle (speed)
  57459. * @param worldMatrix is the world matrix of the particle system
  57460. * @param directionToUpdate is the direction vector to update with the result
  57461. * @param particle is the particle we are computed the direction for
  57462. */
  57463. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57464. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57465. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57466. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57467. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57468. direction.x += randX;
  57469. direction.y += randY;
  57470. direction.z += randZ;
  57471. direction.normalize();
  57472. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57473. };
  57474. /**
  57475. * Called by the particle System when the position is computed for the created particle.
  57476. * @param worldMatrix is the world matrix of the particle system
  57477. * @param positionToUpdate is the position vector to update with the result
  57478. * @param particle is the particle we are computed the position for
  57479. */
  57480. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57481. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57482. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57483. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57484. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57485. var randY = randRadius * Math.cos(theta);
  57486. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57487. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57488. };
  57489. /**
  57490. * Clones the current emitter and returns a copy of it
  57491. * @returns the new emitter
  57492. */
  57493. SphereParticleEmitter.prototype.clone = function () {
  57494. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57495. BABYLON.Tools.DeepCopy(this, newOne);
  57496. return newOne;
  57497. };
  57498. /**
  57499. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57500. * @param effect defines the update shader
  57501. */
  57502. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57503. effect.setFloat("radius", this.radius);
  57504. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57505. };
  57506. /**
  57507. * Returns a string to use to update the GPU particles update shader
  57508. * @returns a string containng the defines string
  57509. */
  57510. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57511. return "#define SPHEREEMITTER";
  57512. };
  57513. /**
  57514. * Returns the string "SphereParticleEmitter"
  57515. * @returns a string containing the class name
  57516. */
  57517. SphereParticleEmitter.prototype.getClassName = function () {
  57518. return "SphereParticleEmitter";
  57519. };
  57520. /**
  57521. * Serializes the particle system to a JSON object.
  57522. * @returns the JSON object
  57523. */
  57524. SphereParticleEmitter.prototype.serialize = function () {
  57525. var serializationObject = {};
  57526. serializationObject.type = this.getClassName();
  57527. serializationObject.radius = this.radius;
  57528. serializationObject.directionRandomizer = this.directionRandomizer;
  57529. return serializationObject;
  57530. };
  57531. /**
  57532. * Parse properties from a JSON object
  57533. * @param serializationObject defines the JSON object
  57534. */
  57535. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57536. this.radius = serializationObject.radius;
  57537. this.directionRandomizer = serializationObject.directionRandomizer;
  57538. };
  57539. return SphereParticleEmitter;
  57540. }());
  57541. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57542. /**
  57543. * Particle emitter emitting particles from the inside of a sphere.
  57544. * It emits the particles randomly between two vectors.
  57545. */
  57546. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57547. __extends(SphereDirectedParticleEmitter, _super);
  57548. /**
  57549. * Creates a new instance SphereDirectedParticleEmitter
  57550. * @param radius the radius of the emission sphere (1 by default)
  57551. * @param direction1 the min limit of the emission direction (up vector by default)
  57552. * @param direction2 the max limit of the emission direction (up vector by default)
  57553. */
  57554. function SphereDirectedParticleEmitter(radius,
  57555. /**
  57556. * The min limit of the emission direction.
  57557. */
  57558. direction1,
  57559. /**
  57560. * The max limit of the emission direction.
  57561. */
  57562. direction2) {
  57563. if (radius === void 0) { radius = 1; }
  57564. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57565. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57566. var _this = _super.call(this, radius) || this;
  57567. _this.direction1 = direction1;
  57568. _this.direction2 = direction2;
  57569. return _this;
  57570. }
  57571. /**
  57572. * Called by the particle System when the direction is computed for the created particle.
  57573. * @param emitPower is the power of the particle (speed)
  57574. * @param worldMatrix is the world matrix of the particle system
  57575. * @param directionToUpdate is the direction vector to update with the result
  57576. * @param particle is the particle we are computed the direction for
  57577. */
  57578. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57579. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57580. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57581. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57582. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57583. };
  57584. /**
  57585. * Clones the current emitter and returns a copy of it
  57586. * @returns the new emitter
  57587. */
  57588. SphereDirectedParticleEmitter.prototype.clone = function () {
  57589. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57590. BABYLON.Tools.DeepCopy(this, newOne);
  57591. return newOne;
  57592. };
  57593. /**
  57594. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57595. * @param effect defines the update shader
  57596. */
  57597. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57598. effect.setFloat("radius", this.radius);
  57599. effect.setVector3("direction1", this.direction1);
  57600. effect.setVector3("direction2", this.direction2);
  57601. };
  57602. /**
  57603. * Returns a string to use to update the GPU particles update shader
  57604. * @returns a string containng the defines string
  57605. */
  57606. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57607. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57608. };
  57609. /**
  57610. * Returns the string "SphereDirectedParticleEmitter"
  57611. * @returns a string containing the class name
  57612. */
  57613. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57614. return "SphereDirectedParticleEmitter";
  57615. };
  57616. /**
  57617. * Serializes the particle system to a JSON object.
  57618. * @returns the JSON object
  57619. */
  57620. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57621. var serializationObject = _super.prototype.serialize.call(this);
  57622. serializationObject.direction1 = this.direction1.asArray();
  57623. serializationObject.direction2 = this.direction2.asArray();
  57624. return serializationObject;
  57625. };
  57626. /**
  57627. * Parse properties from a JSON object
  57628. * @param serializationObject defines the JSON object
  57629. */
  57630. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57631. _super.prototype.parse.call(this, serializationObject);
  57632. this.direction1.copyFrom(serializationObject.direction1);
  57633. this.direction2.copyFrom(serializationObject.direction2);
  57634. };
  57635. return SphereDirectedParticleEmitter;
  57636. }(SphereParticleEmitter));
  57637. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57638. })(BABYLON || (BABYLON = {}));
  57639. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57640. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57641. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57642. s = arguments[i];
  57643. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57644. t[p] = s[p];
  57645. }
  57646. return t;
  57647. };
  57648. var BABYLON;
  57649. (function (BABYLON) {
  57650. /**
  57651. * This represents a GPU particle system in Babylon
  57652. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57653. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57654. */
  57655. var GPUParticleSystem = /** @class */ (function () {
  57656. /**
  57657. * Instantiates a GPU particle system.
  57658. * 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.
  57659. * @param name The name of the particle system
  57660. * @param capacity The max number of particles alive at the same time
  57661. * @param scene The scene the particle system belongs to
  57662. */
  57663. function GPUParticleSystem(name, options, scene) {
  57664. /**
  57665. * The emitter represents the Mesh or position we are attaching the particle system to.
  57666. */
  57667. this.emitter = null;
  57668. /**
  57669. * The rendering group used by the Particle system to chose when to render.
  57670. */
  57671. this.renderingGroupId = 0;
  57672. /**
  57673. * The layer mask we are rendering the particles through.
  57674. */
  57675. this.layerMask = 0x0FFFFFFF;
  57676. this._targetIndex = 0;
  57677. this._currentRenderId = -1;
  57678. this._started = false;
  57679. this._stopped = false;
  57680. this._timeDelta = 0;
  57681. this._attributesStrideSize = 16;
  57682. this._actualFrame = 0;
  57683. /**
  57684. * List of animations used by the particle system.
  57685. */
  57686. this.animations = [];
  57687. /**
  57688. * An event triggered when the system is disposed.
  57689. */
  57690. this.onDisposeObservable = new BABYLON.Observable();
  57691. /**
  57692. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57693. */
  57694. this.updateSpeed = 0.01;
  57695. /**
  57696. * The amount of time the particle system is running (depends of the overall update speed).
  57697. */
  57698. this.targetStopDuration = 0;
  57699. /**
  57700. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57701. */
  57702. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57703. /**
  57704. * Minimum life time of emitting particles.
  57705. */
  57706. this.minLifeTime = 1;
  57707. /**
  57708. * Maximum life time of emitting particles.
  57709. */
  57710. this.maxLifeTime = 1;
  57711. /**
  57712. * Minimum Size of emitting particles.
  57713. */
  57714. this.minSize = 1;
  57715. /**
  57716. * Maximum Size of emitting particles.
  57717. */
  57718. this.maxSize = 1;
  57719. /**
  57720. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57721. */
  57722. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57723. /**
  57724. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57725. */
  57726. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57727. /**
  57728. * Color the particle will have at the end of its lifetime.
  57729. */
  57730. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57731. /**
  57732. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57733. */
  57734. this.emitRate = 100;
  57735. /**
  57736. * You can use gravity if you want to give an orientation to your particles.
  57737. */
  57738. this.gravity = BABYLON.Vector3.Zero();
  57739. /**
  57740. * Minimum power of emitting particles.
  57741. */
  57742. this.minEmitPower = 1;
  57743. /**
  57744. * Maximum power of emitting particles.
  57745. */
  57746. this.maxEmitPower = 1;
  57747. /**
  57748. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57749. */
  57750. this.minAngularSpeed = 0;
  57751. /**
  57752. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57753. */
  57754. this.maxAngularSpeed = 0;
  57755. /**
  57756. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57757. * to override the particles.
  57758. */
  57759. this.forceDepthWrite = false;
  57760. this.id = name;
  57761. this.name = name;
  57762. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57763. this._engine = this._scene.getEngine();
  57764. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57765. this._capacity = fullOptions.capacity;
  57766. this._activeCount = fullOptions.capacity;
  57767. this._currentActiveCount = 0;
  57768. this._scene.particleSystems.push(this);
  57769. this._updateEffectOptions = {
  57770. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "angle"],
  57771. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57772. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57773. "angleRange"],
  57774. uniformBuffersNames: [],
  57775. samplers: ["randomSampler"],
  57776. defines: "",
  57777. fallbacks: null,
  57778. onCompiled: null,
  57779. onError: null,
  57780. indexParameters: null,
  57781. maxSimultaneousLights: 0,
  57782. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection", "outAngle"]
  57783. };
  57784. // Random data
  57785. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57786. var d = [];
  57787. for (var i = 0; i < maxTextureSize; ++i) {
  57788. d.push(Math.random());
  57789. d.push(Math.random());
  57790. d.push(Math.random());
  57791. d.push(Math.random());
  57792. }
  57793. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57794. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57795. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57796. this._randomTextureSize = maxTextureSize;
  57797. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57798. }
  57799. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57800. /**
  57801. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57802. */
  57803. get: function () {
  57804. if (!BABYLON.Engine.LastCreatedEngine) {
  57805. return false;
  57806. }
  57807. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57808. },
  57809. enumerable: true,
  57810. configurable: true
  57811. });
  57812. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57813. /**
  57814. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57815. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57816. */
  57817. get: function () {
  57818. if (this.particleEmitterType.direction1) {
  57819. return this.particleEmitterType.direction1;
  57820. }
  57821. return BABYLON.Vector3.Zero();
  57822. },
  57823. set: function (value) {
  57824. if (this.particleEmitterType.direction1) {
  57825. this.particleEmitterType.direction1 = value;
  57826. }
  57827. },
  57828. enumerable: true,
  57829. configurable: true
  57830. });
  57831. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57832. /**
  57833. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57834. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57835. */
  57836. get: function () {
  57837. if (this.particleEmitterType.direction2) {
  57838. return this.particleEmitterType.direction2;
  57839. }
  57840. return BABYLON.Vector3.Zero();
  57841. },
  57842. set: function (value) {
  57843. if (this.particleEmitterType.direction2) {
  57844. this.particleEmitterType.direction2 = value;
  57845. }
  57846. },
  57847. enumerable: true,
  57848. configurable: true
  57849. });
  57850. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57851. /**
  57852. * 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.
  57853. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57854. */
  57855. get: function () {
  57856. if (this.particleEmitterType.minEmitBox) {
  57857. return this.particleEmitterType.minEmitBox;
  57858. }
  57859. return BABYLON.Vector3.Zero();
  57860. },
  57861. set: function (value) {
  57862. if (this.particleEmitterType.minEmitBox) {
  57863. this.particleEmitterType.minEmitBox = value;
  57864. }
  57865. },
  57866. enumerable: true,
  57867. configurable: true
  57868. });
  57869. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57870. /**
  57871. * 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.
  57872. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57873. */
  57874. get: function () {
  57875. if (this.particleEmitterType.maxEmitBox) {
  57876. return this.particleEmitterType.maxEmitBox;
  57877. }
  57878. return BABYLON.Vector3.Zero();
  57879. },
  57880. set: function (value) {
  57881. if (this.particleEmitterType.maxEmitBox) {
  57882. this.particleEmitterType.maxEmitBox = value;
  57883. }
  57884. },
  57885. enumerable: true,
  57886. configurable: true
  57887. });
  57888. /**
  57889. * Gets the maximum number of particles active at the same time.
  57890. * @returns The max number of active particles.
  57891. */
  57892. GPUParticleSystem.prototype.getCapacity = function () {
  57893. return this._capacity;
  57894. };
  57895. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57896. /**
  57897. * Gets or set the number of active particles
  57898. */
  57899. get: function () {
  57900. return this._activeCount;
  57901. },
  57902. set: function (value) {
  57903. this._activeCount = Math.min(value, this._capacity);
  57904. },
  57905. enumerable: true,
  57906. configurable: true
  57907. });
  57908. /**
  57909. * Is this system ready to be used/rendered
  57910. * @return true if the system is ready
  57911. */
  57912. GPUParticleSystem.prototype.isReady = function () {
  57913. if (!this._updateEffect) {
  57914. this._recreateUpdateEffect();
  57915. this._recreateRenderEffect();
  57916. return false;
  57917. }
  57918. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57919. return false;
  57920. }
  57921. return true;
  57922. };
  57923. /**
  57924. * Gets Wether the system has been started.
  57925. * @returns True if it has been started, otherwise false.
  57926. */
  57927. GPUParticleSystem.prototype.isStarted = function () {
  57928. return this._started;
  57929. };
  57930. /**
  57931. * Starts the particle system and begins to emit.
  57932. */
  57933. GPUParticleSystem.prototype.start = function () {
  57934. this._started = true;
  57935. this._stopped = false;
  57936. };
  57937. /**
  57938. * Stops the particle system.
  57939. */
  57940. GPUParticleSystem.prototype.stop = function () {
  57941. this._stopped = true;
  57942. };
  57943. /**
  57944. * Remove all active particles
  57945. */
  57946. GPUParticleSystem.prototype.reset = function () {
  57947. this._releaseBuffers();
  57948. this._releaseVAOs();
  57949. this._currentActiveCount = 0;
  57950. this._targetIndex = 0;
  57951. };
  57952. /**
  57953. * Returns the string "GPUParticleSystem"
  57954. * @returns a string containing the class name
  57955. */
  57956. GPUParticleSystem.prototype.getClassName = function () {
  57957. return "GPUParticleSystem";
  57958. };
  57959. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57960. var updateVertexBuffers = {};
  57961. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57962. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57963. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57964. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57965. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57966. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57967. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57968. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2);
  57969. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57970. this._engine.bindArrayBuffer(null);
  57971. return vao;
  57972. };
  57973. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57974. var renderVertexBuffers = {};
  57975. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57976. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57977. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57978. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57979. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57980. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", 14, 2, this._attributesStrideSize, true);
  57981. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57982. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57983. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57984. this._engine.bindArrayBuffer(null);
  57985. return vao;
  57986. };
  57987. GPUParticleSystem.prototype._initialize = function (force) {
  57988. if (force === void 0) { force = false; }
  57989. if (this._buffer0 && !force) {
  57990. return;
  57991. }
  57992. var engine = this._scene.getEngine();
  57993. var data = new Array();
  57994. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57995. // position
  57996. data.push(0.0);
  57997. data.push(0.0);
  57998. data.push(0.0);
  57999. // Age and life
  58000. data.push(0.0); // create the particle as a dead one to create a new one at start
  58001. data.push(0.0);
  58002. // Seed
  58003. data.push(Math.random());
  58004. // Size
  58005. data.push(0.0);
  58006. // color
  58007. data.push(0.0);
  58008. data.push(0.0);
  58009. data.push(0.0);
  58010. data.push(0.0);
  58011. // direction
  58012. data.push(0.0);
  58013. data.push(0.0);
  58014. data.push(0.0);
  58015. // angle
  58016. data.push(0.0);
  58017. data.push(0.0);
  58018. }
  58019. // Sprite data
  58020. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  58021. -0.5, 0.5, 0, 1,
  58022. -0.5, -0.5, 0, 0,
  58023. 0.5, -0.5, 1, 0]);
  58024. // Buffers
  58025. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58026. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  58027. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  58028. // Update VAO
  58029. this._updateVAO = [];
  58030. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  58031. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  58032. // Render VAO
  58033. this._renderVAO = [];
  58034. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  58035. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  58036. // Links
  58037. this._sourceBuffer = this._buffer0;
  58038. this._targetBuffer = this._buffer1;
  58039. };
  58040. /** @hidden */
  58041. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  58042. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  58043. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  58044. return;
  58045. }
  58046. this._updateEffectOptions.defines = defines;
  58047. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  58048. };
  58049. /** @hidden */
  58050. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  58051. var defines = "";
  58052. if (this._scene.clipPlane) {
  58053. defines = "\n#define CLIPPLANE";
  58054. }
  58055. if (this._renderEffect && this._renderEffect.defines === defines) {
  58056. return;
  58057. }
  58058. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  58059. };
  58060. /**
  58061. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58062. */
  58063. GPUParticleSystem.prototype.animate = function () {
  58064. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  58065. this._actualFrame += this._timeDelta;
  58066. if (!this._stopped) {
  58067. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  58068. this.stop();
  58069. }
  58070. }
  58071. };
  58072. /**
  58073. * Renders the particle system in its current state.
  58074. * @returns the current number of particles
  58075. */
  58076. GPUParticleSystem.prototype.render = function () {
  58077. if (!this._started) {
  58078. return 0;
  58079. }
  58080. this._recreateUpdateEffect();
  58081. this._recreateRenderEffect();
  58082. if (!this.isReady()) {
  58083. return 0;
  58084. }
  58085. if (this._currentRenderId === this._scene.getRenderId()) {
  58086. return 0;
  58087. }
  58088. this._currentRenderId = this._scene.getRenderId();
  58089. // Get everything ready to render
  58090. this._initialize();
  58091. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  58092. // Enable update effect
  58093. this._engine.enableEffect(this._updateEffect);
  58094. this._engine.setState(false);
  58095. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58096. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58097. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58098. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  58099. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58100. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58101. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58102. this._updateEffect.setDirectColor4("color1", this.color1);
  58103. this._updateEffect.setDirectColor4("color2", this.color2);
  58104. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58105. this._updateEffect.setFloat2("angleRange", this.minAngularSpeed, this.maxAngularSpeed);
  58106. this._updateEffect.setVector3("gravity", this.gravity);
  58107. if (this.particleEmitterType) {
  58108. this.particleEmitterType.applyToShader(this._updateEffect);
  58109. }
  58110. var emitterWM;
  58111. if (this.emitter.position) {
  58112. var emitterMesh = this.emitter;
  58113. emitterWM = emitterMesh.getWorldMatrix();
  58114. }
  58115. else {
  58116. var emitterPosition = this.emitter;
  58117. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58118. }
  58119. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58120. // Bind source VAO
  58121. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58122. // Update
  58123. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58124. this._engine.setRasterizerState(false);
  58125. this._engine.beginTransformFeedback();
  58126. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58127. this._engine.endTransformFeedback();
  58128. this._engine.setRasterizerState(true);
  58129. this._engine.bindTransformFeedbackBuffer(null);
  58130. // Enable render effect
  58131. this._engine.enableEffect(this._renderEffect);
  58132. var viewMatrix = this._scene.getViewMatrix();
  58133. this._renderEffect.setMatrix("view", viewMatrix);
  58134. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58135. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58136. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58137. if (this._scene.clipPlane) {
  58138. var clipPlane = this._scene.clipPlane;
  58139. var invView = viewMatrix.clone();
  58140. invView.invert();
  58141. this._renderEffect.setMatrix("invView", invView);
  58142. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58143. }
  58144. // Draw order
  58145. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  58146. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58147. }
  58148. else {
  58149. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58150. }
  58151. if (this.forceDepthWrite) {
  58152. this._engine.setDepthWrite(true);
  58153. }
  58154. // Bind source VAO
  58155. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58156. // Render
  58157. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58158. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58159. // Switch VAOs
  58160. this._targetIndex++;
  58161. if (this._targetIndex === 2) {
  58162. this._targetIndex = 0;
  58163. }
  58164. // Switch buffers
  58165. var tmpBuffer = this._sourceBuffer;
  58166. this._sourceBuffer = this._targetBuffer;
  58167. this._targetBuffer = tmpBuffer;
  58168. return this._currentActiveCount;
  58169. };
  58170. /**
  58171. * Rebuilds the particle system
  58172. */
  58173. GPUParticleSystem.prototype.rebuild = function () {
  58174. this._initialize(true);
  58175. };
  58176. GPUParticleSystem.prototype._releaseBuffers = function () {
  58177. if (this._buffer0) {
  58178. this._buffer0.dispose();
  58179. this._buffer0 = null;
  58180. }
  58181. if (this._buffer1) {
  58182. this._buffer1.dispose();
  58183. this._buffer1 = null;
  58184. }
  58185. if (this._spriteBuffer) {
  58186. this._spriteBuffer.dispose();
  58187. this._spriteBuffer = null;
  58188. }
  58189. };
  58190. GPUParticleSystem.prototype._releaseVAOs = function () {
  58191. if (!this._updateVAO) {
  58192. return;
  58193. }
  58194. for (var index = 0; index < this._updateVAO.length; index++) {
  58195. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58196. }
  58197. this._updateVAO = [];
  58198. for (var index = 0; index < this._renderVAO.length; index++) {
  58199. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58200. }
  58201. this._renderVAO = [];
  58202. };
  58203. /**
  58204. * Disposes the particle system and free the associated resources
  58205. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58206. */
  58207. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58208. if (disposeTexture === void 0) { disposeTexture = true; }
  58209. var index = this._scene.particleSystems.indexOf(this);
  58210. if (index > -1) {
  58211. this._scene.particleSystems.splice(index, 1);
  58212. }
  58213. this._releaseBuffers();
  58214. this._releaseVAOs();
  58215. if (this._randomTexture) {
  58216. this._randomTexture.dispose();
  58217. this._randomTexture = null;
  58218. }
  58219. if (disposeTexture && this.particleTexture) {
  58220. this.particleTexture.dispose();
  58221. this.particleTexture = null;
  58222. }
  58223. // Callback
  58224. this.onDisposeObservable.notifyObservers(this);
  58225. this.onDisposeObservable.clear();
  58226. };
  58227. /**
  58228. * Clones the particle system.
  58229. * @param name The name of the cloned object
  58230. * @param newEmitter The new emitter to use
  58231. * @returns the cloned particle system
  58232. */
  58233. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58234. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58235. BABYLON.Tools.DeepCopy(this, result);
  58236. if (newEmitter === undefined) {
  58237. newEmitter = this.emitter;
  58238. }
  58239. result.emitter = newEmitter;
  58240. if (this.particleTexture) {
  58241. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58242. }
  58243. return result;
  58244. };
  58245. /**
  58246. * Serializes the particle system to a JSON object.
  58247. * @returns the JSON object
  58248. */
  58249. GPUParticleSystem.prototype.serialize = function () {
  58250. var serializationObject = {};
  58251. serializationObject.name = this.name;
  58252. serializationObject.id = this.id;
  58253. // Emitter
  58254. if (this.emitter.position) {
  58255. var emitterMesh = this.emitter;
  58256. serializationObject.emitterId = emitterMesh.id;
  58257. }
  58258. else {
  58259. var emitterPosition = this.emitter;
  58260. serializationObject.emitter = emitterPosition.asArray();
  58261. }
  58262. serializationObject.capacity = this.getCapacity();
  58263. if (this.particleTexture) {
  58264. serializationObject.textureName = this.particleTexture.name;
  58265. }
  58266. // Animations
  58267. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  58268. // Particle system
  58269. serializationObject.activeParticleCount = this.activeParticleCount;
  58270. serializationObject.randomTextureSize = this._randomTextureSize;
  58271. serializationObject.minSize = this.minSize;
  58272. serializationObject.maxSize = this.maxSize;
  58273. serializationObject.minEmitPower = this.minEmitPower;
  58274. serializationObject.maxEmitPower = this.maxEmitPower;
  58275. serializationObject.minLifeTime = this.minLifeTime;
  58276. serializationObject.maxLifeTime = this.maxLifeTime;
  58277. serializationObject.minAngularSpeed = this.minAngularSpeed;
  58278. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  58279. serializationObject.emitRate = this.emitRate;
  58280. serializationObject.gravity = this.gravity.asArray();
  58281. serializationObject.color1 = this.color1.asArray();
  58282. serializationObject.color2 = this.color2.asArray();
  58283. serializationObject.colorDead = this.colorDead.asArray();
  58284. serializationObject.updateSpeed = this.updateSpeed;
  58285. serializationObject.targetStopDuration = this.targetStopDuration;
  58286. serializationObject.blendMode = this.blendMode;
  58287. // Emitter
  58288. if (this.particleEmitterType) {
  58289. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  58290. }
  58291. return serializationObject;
  58292. };
  58293. /**
  58294. * Parses a JSON object to create a GPU particle system.
  58295. * @param parsedParticleSystem The JSON object to parse
  58296. * @param scene The scene to create the particle system in
  58297. * @param rootUrl The root url to use to load external dependencies like texture
  58298. * @returns the parsed GPU particle system
  58299. */
  58300. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58301. var name = parsedParticleSystem.name;
  58302. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58303. if (parsedParticleSystem.id) {
  58304. particleSystem.id = parsedParticleSystem.id;
  58305. }
  58306. // Texture
  58307. if (parsedParticleSystem.textureName) {
  58308. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58309. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58310. }
  58311. // Emitter
  58312. if (parsedParticleSystem.emitterId) {
  58313. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58314. }
  58315. else {
  58316. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58317. }
  58318. // Animations
  58319. if (parsedParticleSystem.animations) {
  58320. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58321. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58322. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58323. }
  58324. }
  58325. // Particle system
  58326. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58327. particleSystem.minSize = parsedParticleSystem.minSize;
  58328. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58329. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  58330. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  58331. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58332. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58333. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  58334. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  58335. particleSystem.emitRate = parsedParticleSystem.emitRate;
  58336. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  58337. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  58338. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  58339. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  58340. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  58341. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  58342. particleSystem.blendMode = parsedParticleSystem.blendMode;
  58343. // Emitter
  58344. if (parsedParticleSystem.particleEmitterType) {
  58345. var emitterType = void 0;
  58346. switch (parsedParticleSystem.particleEmitterType.type) {
  58347. case "SphereEmitter":
  58348. emitterType = new BABYLON.SphereParticleEmitter();
  58349. break;
  58350. case "SphereDirectedParticleEmitter":
  58351. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  58352. break;
  58353. case "ConeEmitter":
  58354. emitterType = new BABYLON.ConeParticleEmitter();
  58355. break;
  58356. case "BoxEmitter":
  58357. default:
  58358. emitterType = new BABYLON.BoxParticleEmitter();
  58359. break;
  58360. }
  58361. emitterType.parse(parsedParticleSystem.particleEmitterType);
  58362. particleSystem.particleEmitterType = emitterType;
  58363. }
  58364. return particleSystem;
  58365. };
  58366. return GPUParticleSystem;
  58367. }());
  58368. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58369. })(BABYLON || (BABYLON = {}));
  58370. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58371. var BABYLON;
  58372. (function (BABYLON) {
  58373. /**
  58374. * Represents one particle of a solid particle system.
  58375. */
  58376. var SolidParticle = /** @class */ (function () {
  58377. /**
  58378. * Creates a Solid Particle object.
  58379. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58380. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58381. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58382. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58383. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58384. * @param shapeId (integer) is the model shape identifier in the SPS.
  58385. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58386. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58387. */
  58388. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58389. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58390. /**
  58391. * particle global index
  58392. */
  58393. this.idx = 0;
  58394. /**
  58395. * The color of the particle
  58396. */
  58397. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58398. /**
  58399. * The world space position of the particle.
  58400. */
  58401. this.position = BABYLON.Vector3.Zero();
  58402. /**
  58403. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58404. */
  58405. this.rotation = BABYLON.Vector3.Zero();
  58406. /**
  58407. * The scaling of the particle.
  58408. */
  58409. this.scaling = BABYLON.Vector3.One();
  58410. /**
  58411. * The uvs of the particle.
  58412. */
  58413. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58414. /**
  58415. * The current speed of the particle.
  58416. */
  58417. this.velocity = BABYLON.Vector3.Zero();
  58418. /**
  58419. * The pivot point in the particle local space.
  58420. */
  58421. this.pivot = BABYLON.Vector3.Zero();
  58422. /**
  58423. * Must the particle be translated from its pivot point in its local space ?
  58424. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58425. * Default : false
  58426. */
  58427. this.translateFromPivot = false;
  58428. /**
  58429. * Is the particle active or not ?
  58430. */
  58431. this.alive = true;
  58432. /**
  58433. * Is the particle visible or not ?
  58434. */
  58435. this.isVisible = true;
  58436. /**
  58437. * Index of this particle in the global "positions" array (Internal use)
  58438. */
  58439. this._pos = 0;
  58440. /**
  58441. * Index of this particle in the global "indices" array (Internal use)
  58442. */
  58443. this._ind = 0;
  58444. /**
  58445. * ModelShape id of this particle
  58446. */
  58447. this.shapeId = 0;
  58448. /**
  58449. * Index of the particle in its shape id (Internal use)
  58450. */
  58451. this.idxInShape = 0;
  58452. /**
  58453. * Still set as invisible in order to skip useless computations (Internal use)
  58454. */
  58455. this._stillInvisible = false;
  58456. /**
  58457. * Last computed particle rotation matrix
  58458. */
  58459. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58460. /**
  58461. * Parent particle Id, if any.
  58462. * Default null.
  58463. */
  58464. this.parentId = null;
  58465. /**
  58466. * Internal global position in the SPS.
  58467. */
  58468. this._globalPosition = BABYLON.Vector3.Zero();
  58469. this.idx = particleIndex;
  58470. this._pos = positionIndex;
  58471. this._ind = indiceIndex;
  58472. this._model = model;
  58473. this.shapeId = shapeId;
  58474. this.idxInShape = idxInShape;
  58475. this._sps = sps;
  58476. if (modelBoundingInfo) {
  58477. this._modelBoundingInfo = modelBoundingInfo;
  58478. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58479. }
  58480. }
  58481. Object.defineProperty(SolidParticle.prototype, "scale", {
  58482. /**
  58483. * Legacy support, changed scale to scaling
  58484. */
  58485. get: function () {
  58486. return this.scaling;
  58487. },
  58488. /**
  58489. * Legacy support, changed scale to scaling
  58490. */
  58491. set: function (scale) {
  58492. this.scaling = scale;
  58493. },
  58494. enumerable: true,
  58495. configurable: true
  58496. });
  58497. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58498. /**
  58499. * Legacy support, changed quaternion to rotationQuaternion
  58500. */
  58501. get: function () {
  58502. return this.rotationQuaternion;
  58503. },
  58504. /**
  58505. * Legacy support, changed quaternion to rotationQuaternion
  58506. */
  58507. set: function (q) {
  58508. this.rotationQuaternion = q;
  58509. },
  58510. enumerable: true,
  58511. configurable: true
  58512. });
  58513. /**
  58514. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58515. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58516. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58517. * @returns true if it intersects
  58518. */
  58519. SolidParticle.prototype.intersectsMesh = function (target) {
  58520. if (!this._boundingInfo || !target._boundingInfo) {
  58521. return false;
  58522. }
  58523. if (this._sps._bSphereOnly) {
  58524. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58525. }
  58526. return this._boundingInfo.intersects(target._boundingInfo, false);
  58527. };
  58528. return SolidParticle;
  58529. }());
  58530. BABYLON.SolidParticle = SolidParticle;
  58531. /**
  58532. * Represents the shape of the model used by one particle of a solid particle system.
  58533. * SPS internal tool, don't use it manually.
  58534. */
  58535. var ModelShape = /** @class */ (function () {
  58536. /**
  58537. * 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.
  58538. * SPS internal tool, don't use it manually.
  58539. * @hidden
  58540. */
  58541. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58542. /**
  58543. * length of the shape in the model indices array (internal use)
  58544. */
  58545. this._indicesLength = 0;
  58546. this.shapeID = id;
  58547. this._shape = shape;
  58548. this._indicesLength = indicesLength;
  58549. this._shapeUV = shapeUV;
  58550. this._positionFunction = posFunction;
  58551. this._vertexFunction = vtxFunction;
  58552. }
  58553. return ModelShape;
  58554. }());
  58555. BABYLON.ModelShape = ModelShape;
  58556. /**
  58557. * Represents a Depth Sorted Particle in the solid particle system.
  58558. */
  58559. var DepthSortedParticle = /** @class */ (function () {
  58560. function DepthSortedParticle() {
  58561. /**
  58562. * Index of the particle in the "indices" array
  58563. */
  58564. this.ind = 0;
  58565. /**
  58566. * Length of the particle shape in the "indices" array
  58567. */
  58568. this.indicesLength = 0;
  58569. /**
  58570. * Squared distance from the particle to the camera
  58571. */
  58572. this.sqDistance = 0.0;
  58573. }
  58574. return DepthSortedParticle;
  58575. }());
  58576. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58577. })(BABYLON || (BABYLON = {}));
  58578. //# sourceMappingURL=babylon.solidParticle.js.map
  58579. var BABYLON;
  58580. (function (BABYLON) {
  58581. /**
  58582. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58583. *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.
  58584. * The SPS is also a particle system. It provides some methods to manage the particles.
  58585. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58586. *
  58587. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58588. */
  58589. var SolidParticleSystem = /** @class */ (function () {
  58590. /**
  58591. * Creates a SPS (Solid Particle System) object.
  58592. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58593. * @param scene (Scene) is the scene in which the SPS is added.
  58594. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58595. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58596. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58597. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58598. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58599. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58600. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58601. */
  58602. function SolidParticleSystem(name, scene, options) {
  58603. /**
  58604. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58605. * Example : var p = SPS.particles[i];
  58606. */
  58607. this.particles = new Array();
  58608. /**
  58609. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58610. */
  58611. this.nbParticles = 0;
  58612. /**
  58613. * If the particles must ever face the camera (default false). Useful for planar particles.
  58614. */
  58615. this.billboard = false;
  58616. /**
  58617. * Recompute normals when adding a shape
  58618. */
  58619. this.recomputeNormals = true;
  58620. /**
  58621. * This a counter ofr your own usage. It's not set by any SPS functions.
  58622. */
  58623. this.counter = 0;
  58624. /**
  58625. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58626. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58627. */
  58628. this.vars = {};
  58629. /**
  58630. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58631. */
  58632. this._bSphereOnly = false;
  58633. /**
  58634. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58635. */
  58636. this._bSphereRadiusFactor = 1.0;
  58637. this._positions = new Array();
  58638. this._indices = new Array();
  58639. this._normals = new Array();
  58640. this._colors = new Array();
  58641. this._uvs = new Array();
  58642. this._index = 0; // indices index
  58643. this._updatable = true;
  58644. this._pickable = false;
  58645. this._isVisibilityBoxLocked = false;
  58646. this._alwaysVisible = false;
  58647. this._depthSort = false;
  58648. this._shapeCounter = 0;
  58649. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58650. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58651. this._computeParticleColor = true;
  58652. this._computeParticleTexture = true;
  58653. this._computeParticleRotation = true;
  58654. this._computeParticleVertex = false;
  58655. this._computeBoundingBox = false;
  58656. this._depthSortParticles = true;
  58657. this._cam_axisZ = BABYLON.Vector3.Zero();
  58658. this._cam_axisY = BABYLON.Vector3.Zero();
  58659. this._cam_axisX = BABYLON.Vector3.Zero();
  58660. this._axisZ = BABYLON.Axis.Z;
  58661. this._camDir = BABYLON.Vector3.Zero();
  58662. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58663. this._rotMatrix = new BABYLON.Matrix();
  58664. this._invertMatrix = new BABYLON.Matrix();
  58665. this._rotated = BABYLON.Vector3.Zero();
  58666. this._quaternion = new BABYLON.Quaternion();
  58667. this._vertex = BABYLON.Vector3.Zero();
  58668. this._normal = BABYLON.Vector3.Zero();
  58669. this._yaw = 0.0;
  58670. this._pitch = 0.0;
  58671. this._roll = 0.0;
  58672. this._halfroll = 0.0;
  58673. this._halfpitch = 0.0;
  58674. this._halfyaw = 0.0;
  58675. this._sinRoll = 0.0;
  58676. this._cosRoll = 0.0;
  58677. this._sinPitch = 0.0;
  58678. this._cosPitch = 0.0;
  58679. this._sinYaw = 0.0;
  58680. this._cosYaw = 0.0;
  58681. this._mustUnrotateFixedNormals = false;
  58682. this._minimum = BABYLON.Vector3.Zero();
  58683. this._maximum = BABYLON.Vector3.Zero();
  58684. this._minBbox = BABYLON.Vector3.Zero();
  58685. this._maxBbox = BABYLON.Vector3.Zero();
  58686. this._particlesIntersect = false;
  58687. this._depthSortFunction = function (p1, p2) {
  58688. return (p2.sqDistance - p1.sqDistance);
  58689. };
  58690. this._needs32Bits = false;
  58691. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58692. this._scaledPivot = BABYLON.Vector3.Zero();
  58693. this._particleHasParent = false;
  58694. this.name = name;
  58695. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58696. this._camera = scene.activeCamera;
  58697. this._pickable = options ? options.isPickable : false;
  58698. this._depthSort = options ? options.enableDepthSort : false;
  58699. this._particlesIntersect = options ? options.particleIntersection : false;
  58700. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58701. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58702. if (options && options.updatable) {
  58703. this._updatable = options.updatable;
  58704. }
  58705. else {
  58706. this._updatable = true;
  58707. }
  58708. if (this._pickable) {
  58709. this.pickedParticles = [];
  58710. }
  58711. if (this._depthSort) {
  58712. this.depthSortedParticles = [];
  58713. }
  58714. }
  58715. /**
  58716. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58717. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58718. * @returns the created mesh
  58719. */
  58720. SolidParticleSystem.prototype.buildMesh = function () {
  58721. if (this.nbParticles === 0) {
  58722. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58723. this.addShape(triangle, 1);
  58724. triangle.dispose();
  58725. }
  58726. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58727. this._positions32 = new Float32Array(this._positions);
  58728. this._uvs32 = new Float32Array(this._uvs);
  58729. this._colors32 = new Float32Array(this._colors);
  58730. if (this.recomputeNormals) {
  58731. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58732. }
  58733. this._normals32 = new Float32Array(this._normals);
  58734. this._fixedNormal32 = new Float32Array(this._normals);
  58735. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58736. this._unrotateFixedNormals();
  58737. }
  58738. var vertexData = new BABYLON.VertexData();
  58739. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58740. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58741. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58742. if (this._uvs32.length > 0) {
  58743. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58744. }
  58745. if (this._colors32.length > 0) {
  58746. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58747. }
  58748. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58749. vertexData.applyToMesh(mesh, this._updatable);
  58750. this.mesh = mesh;
  58751. this.mesh.isPickable = this._pickable;
  58752. // free memory
  58753. if (!this._depthSort) {
  58754. this._indices = null;
  58755. }
  58756. this._positions = null;
  58757. this._normals = null;
  58758. this._uvs = null;
  58759. this._colors = null;
  58760. if (!this._updatable) {
  58761. this.particles.length = 0;
  58762. }
  58763. return mesh;
  58764. };
  58765. /**
  58766. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58767. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58768. * Thus the particles generated from `digest()` have their property `position` set yet.
  58769. * @param mesh ( Mesh ) is the mesh to be digested
  58770. * @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
  58771. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58772. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58773. * @returns the current SPS
  58774. */
  58775. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58776. var size = (options && options.facetNb) || 1;
  58777. var number = (options && options.number) || 0;
  58778. var delta = (options && options.delta) || 0;
  58779. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58780. var meshInd = mesh.getIndices();
  58781. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58782. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58783. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58784. var f = 0; // facet counter
  58785. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58786. // compute size from number
  58787. if (number) {
  58788. number = (number > totalFacets) ? totalFacets : number;
  58789. size = Math.round(totalFacets / number);
  58790. delta = 0;
  58791. }
  58792. else {
  58793. size = (size > totalFacets) ? totalFacets : size;
  58794. }
  58795. var facetPos = []; // submesh positions
  58796. var facetInd = []; // submesh indices
  58797. var facetUV = []; // submesh UV
  58798. var facetCol = []; // submesh colors
  58799. var barycenter = BABYLON.Vector3.Zero();
  58800. var sizeO = size;
  58801. while (f < totalFacets) {
  58802. size = sizeO + Math.floor((1 + delta) * Math.random());
  58803. if (f > totalFacets - size) {
  58804. size = totalFacets - f;
  58805. }
  58806. // reset temp arrays
  58807. facetPos.length = 0;
  58808. facetInd.length = 0;
  58809. facetUV.length = 0;
  58810. facetCol.length = 0;
  58811. // iterate over "size" facets
  58812. var fi = 0;
  58813. for (var j = f * 3; j < (f + size) * 3; j++) {
  58814. facetInd.push(fi);
  58815. var i = meshInd[j];
  58816. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58817. if (meshUV) {
  58818. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58819. }
  58820. if (meshCol) {
  58821. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58822. }
  58823. fi++;
  58824. }
  58825. // create a model shape for each single particle
  58826. var idx = this.nbParticles;
  58827. var shape = this._posToShape(facetPos);
  58828. var shapeUV = this._uvsToShapeUV(facetUV);
  58829. // compute the barycenter of the shape
  58830. var v;
  58831. for (v = 0; v < shape.length; v++) {
  58832. barycenter.addInPlace(shape[v]);
  58833. }
  58834. barycenter.scaleInPlace(1 / shape.length);
  58835. // shift the shape from its barycenter to the origin
  58836. for (v = 0; v < shape.length; v++) {
  58837. shape[v].subtractInPlace(barycenter);
  58838. }
  58839. var bInfo;
  58840. if (this._particlesIntersect) {
  58841. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58842. }
  58843. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58844. // add the particle in the SPS
  58845. var currentPos = this._positions.length;
  58846. var currentInd = this._indices.length;
  58847. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58848. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58849. // initialize the particle position
  58850. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58851. this._index += shape.length;
  58852. idx++;
  58853. this.nbParticles++;
  58854. this._shapeCounter++;
  58855. f += size;
  58856. }
  58857. return this;
  58858. };
  58859. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58860. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58861. var index = 0;
  58862. var idx = 0;
  58863. for (var p = 0; p < this.particles.length; p++) {
  58864. this._particle = this.particles[p];
  58865. this._shape = this._particle._model._shape;
  58866. if (this._particle.rotationQuaternion) {
  58867. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58868. }
  58869. else {
  58870. this._yaw = this._particle.rotation.y;
  58871. this._pitch = this._particle.rotation.x;
  58872. this._roll = this._particle.rotation.z;
  58873. this._quaternionRotationYPR();
  58874. }
  58875. this._quaternionToRotationMatrix();
  58876. this._rotMatrix.invertToRef(this._invertMatrix);
  58877. for (var pt = 0; pt < this._shape.length; pt++) {
  58878. idx = index + pt * 3;
  58879. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58880. this._fixedNormal32[idx] = this._normal.x;
  58881. this._fixedNormal32[idx + 1] = this._normal.y;
  58882. this._fixedNormal32[idx + 2] = this._normal.z;
  58883. }
  58884. index = idx + 3;
  58885. }
  58886. };
  58887. //reset copy
  58888. SolidParticleSystem.prototype._resetCopy = function () {
  58889. this._copy.position.x = 0;
  58890. this._copy.position.y = 0;
  58891. this._copy.position.z = 0;
  58892. this._copy.rotation.x = 0;
  58893. this._copy.rotation.y = 0;
  58894. this._copy.rotation.z = 0;
  58895. this._copy.rotationQuaternion = null;
  58896. this._copy.scaling.x = 1.0;
  58897. this._copy.scaling.y = 1.0;
  58898. this._copy.scaling.z = 1.0;
  58899. this._copy.uvs.x = 0;
  58900. this._copy.uvs.y = 0;
  58901. this._copy.uvs.z = 1.0;
  58902. this._copy.uvs.w = 1.0;
  58903. this._copy.color = null;
  58904. this._copy.translateFromPivot = false;
  58905. };
  58906. // _meshBuilder : inserts the shape model in the global SPS mesh
  58907. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58908. var i;
  58909. var u = 0;
  58910. var c = 0;
  58911. var n = 0;
  58912. this._resetCopy();
  58913. if (options && options.positionFunction) { // call to custom positionFunction
  58914. options.positionFunction(this._copy, idx, idxInShape);
  58915. this._mustUnrotateFixedNormals = true;
  58916. }
  58917. if (this._copy.rotationQuaternion) {
  58918. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58919. }
  58920. else {
  58921. this._yaw = this._copy.rotation.y;
  58922. this._pitch = this._copy.rotation.x;
  58923. this._roll = this._copy.rotation.z;
  58924. this._quaternionRotationYPR();
  58925. }
  58926. this._quaternionToRotationMatrix();
  58927. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58928. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58929. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58930. if (this._copy.translateFromPivot) {
  58931. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58932. }
  58933. else {
  58934. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58935. }
  58936. for (i = 0; i < shape.length; i++) {
  58937. this._vertex.x = shape[i].x;
  58938. this._vertex.y = shape[i].y;
  58939. this._vertex.z = shape[i].z;
  58940. if (options && options.vertexFunction) {
  58941. options.vertexFunction(this._copy, this._vertex, i);
  58942. }
  58943. this._vertex.x *= this._copy.scaling.x;
  58944. this._vertex.y *= this._copy.scaling.y;
  58945. this._vertex.z *= this._copy.scaling.z;
  58946. this._vertex.x -= this._scaledPivot.x;
  58947. this._vertex.y -= this._scaledPivot.y;
  58948. this._vertex.z -= this._scaledPivot.z;
  58949. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58950. this._rotated.addInPlace(this._pivotBackTranslation);
  58951. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58952. if (meshUV) {
  58953. 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);
  58954. u += 2;
  58955. }
  58956. if (this._copy.color) {
  58957. this._color = this._copy.color;
  58958. }
  58959. else if (meshCol && meshCol[c] !== undefined) {
  58960. this._color.r = meshCol[c];
  58961. this._color.g = meshCol[c + 1];
  58962. this._color.b = meshCol[c + 2];
  58963. this._color.a = meshCol[c + 3];
  58964. }
  58965. else {
  58966. this._color.r = 1.0;
  58967. this._color.g = 1.0;
  58968. this._color.b = 1.0;
  58969. this._color.a = 1.0;
  58970. }
  58971. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58972. c += 4;
  58973. if (!this.recomputeNormals && meshNor) {
  58974. this._normal.x = meshNor[n];
  58975. this._normal.y = meshNor[n + 1];
  58976. this._normal.z = meshNor[n + 2];
  58977. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58978. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58979. n += 3;
  58980. }
  58981. }
  58982. for (i = 0; i < meshInd.length; i++) {
  58983. var current_ind = p + meshInd[i];
  58984. indices.push(current_ind);
  58985. if (current_ind > 65535) {
  58986. this._needs32Bits = true;
  58987. }
  58988. }
  58989. if (this._pickable) {
  58990. var nbfaces = meshInd.length / 3;
  58991. for (i = 0; i < nbfaces; i++) {
  58992. this.pickedParticles.push({ idx: idx, faceId: i });
  58993. }
  58994. }
  58995. if (this._depthSort) {
  58996. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58997. }
  58998. return this._copy;
  58999. };
  59000. // returns a shape array from positions array
  59001. SolidParticleSystem.prototype._posToShape = function (positions) {
  59002. var shape = [];
  59003. for (var i = 0; i < positions.length; i += 3) {
  59004. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  59005. }
  59006. return shape;
  59007. };
  59008. // returns a shapeUV array from a Vector4 uvs
  59009. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  59010. var shapeUV = [];
  59011. if (uvs) {
  59012. for (var i = 0; i < uvs.length; i++)
  59013. shapeUV.push(uvs[i]);
  59014. }
  59015. return shapeUV;
  59016. };
  59017. // adds a new particle object in the particles array
  59018. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  59019. if (bInfo === void 0) { bInfo = null; }
  59020. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  59021. this.particles.push(sp);
  59022. return sp;
  59023. };
  59024. /**
  59025. * Adds some particles to the SPS from the model shape. Returns the shape id.
  59026. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  59027. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  59028. * @param nb (positive integer) the number of particles to be created from this model
  59029. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  59030. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  59031. * @returns the number of shapes in the system
  59032. */
  59033. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  59034. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59035. var meshInd = mesh.getIndices();
  59036. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59037. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59038. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59039. var bbInfo;
  59040. if (this._particlesIntersect) {
  59041. bbInfo = mesh.getBoundingInfo();
  59042. }
  59043. var shape = this._posToShape(meshPos);
  59044. var shapeUV = this._uvsToShapeUV(meshUV);
  59045. var posfunc = options ? options.positionFunction : null;
  59046. var vtxfunc = options ? options.vertexFunction : null;
  59047. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  59048. // particles
  59049. var sp;
  59050. var currentCopy;
  59051. var idx = this.nbParticles;
  59052. for (var i = 0; i < nb; i++) {
  59053. var currentPos = this._positions.length;
  59054. var currentInd = this._indices.length;
  59055. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  59056. if (this._updatable) {
  59057. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  59058. sp.position.copyFrom(currentCopy.position);
  59059. sp.rotation.copyFrom(currentCopy.rotation);
  59060. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  59061. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  59062. }
  59063. if (currentCopy.color && sp.color) {
  59064. sp.color.copyFrom(currentCopy.color);
  59065. }
  59066. sp.scaling.copyFrom(currentCopy.scaling);
  59067. sp.uvs.copyFrom(currentCopy.uvs);
  59068. }
  59069. this._index += shape.length;
  59070. idx++;
  59071. }
  59072. this.nbParticles += nb;
  59073. this._shapeCounter++;
  59074. return this._shapeCounter - 1;
  59075. };
  59076. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59077. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59078. this._resetCopy();
  59079. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59080. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59081. }
  59082. if (this._copy.rotationQuaternion) {
  59083. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59084. }
  59085. else {
  59086. this._yaw = this._copy.rotation.y;
  59087. this._pitch = this._copy.rotation.x;
  59088. this._roll = this._copy.rotation.z;
  59089. this._quaternionRotationYPR();
  59090. }
  59091. this._quaternionToRotationMatrix();
  59092. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59093. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59094. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59095. if (this._copy.translateFromPivot) {
  59096. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59097. }
  59098. else {
  59099. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59100. }
  59101. this._shape = particle._model._shape;
  59102. for (var pt = 0; pt < this._shape.length; pt++) {
  59103. this._vertex.x = this._shape[pt].x;
  59104. this._vertex.y = this._shape[pt].y;
  59105. this._vertex.z = this._shape[pt].z;
  59106. if (particle._model._vertexFunction) {
  59107. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59108. }
  59109. this._vertex.x *= this._copy.scaling.x;
  59110. this._vertex.y *= this._copy.scaling.y;
  59111. this._vertex.z *= this._copy.scaling.z;
  59112. this._vertex.x -= this._scaledPivot.x;
  59113. this._vertex.y -= this._scaledPivot.y;
  59114. this._vertex.z -= this._scaledPivot.z;
  59115. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59116. this._rotated.addInPlace(this._pivotBackTranslation);
  59117. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59118. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59119. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59120. }
  59121. particle.position.x = 0.0;
  59122. particle.position.y = 0.0;
  59123. particle.position.z = 0.0;
  59124. particle.rotation.x = 0.0;
  59125. particle.rotation.y = 0.0;
  59126. particle.rotation.z = 0.0;
  59127. particle.rotationQuaternion = null;
  59128. particle.scaling.x = 1.0;
  59129. particle.scaling.y = 1.0;
  59130. particle.scaling.z = 1.0;
  59131. particle.uvs.x = 0.0;
  59132. particle.uvs.y = 0.0;
  59133. particle.uvs.z = 1.0;
  59134. particle.uvs.w = 1.0;
  59135. particle.pivot.x = 0.0;
  59136. particle.pivot.y = 0.0;
  59137. particle.pivot.z = 0.0;
  59138. particle.translateFromPivot = false;
  59139. particle.parentId = null;
  59140. };
  59141. /**
  59142. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59143. * @returns the SPS.
  59144. */
  59145. SolidParticleSystem.prototype.rebuildMesh = function () {
  59146. for (var p = 0; p < this.particles.length; p++) {
  59147. this._rebuildParticle(this.particles[p]);
  59148. }
  59149. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59150. return this;
  59151. };
  59152. /**
  59153. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59154. * This method calls `updateParticle()` for each particle of the SPS.
  59155. * For an animated SPS, it is usually called within the render loop.
  59156. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59157. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59158. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59159. * @returns the SPS.
  59160. */
  59161. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59162. if (start === void 0) { start = 0; }
  59163. if (end === void 0) { end = this.nbParticles - 1; }
  59164. if (update === void 0) { update = true; }
  59165. if (!this._updatable) {
  59166. return this;
  59167. }
  59168. // custom beforeUpdate
  59169. this.beforeUpdateParticles(start, end, update);
  59170. this._cam_axisX.x = 1.0;
  59171. this._cam_axisX.y = 0.0;
  59172. this._cam_axisX.z = 0.0;
  59173. this._cam_axisY.x = 0.0;
  59174. this._cam_axisY.y = 1.0;
  59175. this._cam_axisY.z = 0.0;
  59176. this._cam_axisZ.x = 0.0;
  59177. this._cam_axisZ.y = 0.0;
  59178. this._cam_axisZ.z = 1.0;
  59179. // cases when the World Matrix is to be computed first
  59180. if (this.billboard || this._depthSort) {
  59181. this.mesh.computeWorldMatrix(true);
  59182. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59183. }
  59184. // if the particles will always face the camera
  59185. if (this.billboard) {
  59186. // compute the camera position and un-rotate it by the current mesh rotation
  59187. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59188. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59189. this._cam_axisZ.normalize();
  59190. // same for camera up vector extracted from the cam view matrix
  59191. var view = this._camera.getViewMatrix(true);
  59192. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59193. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59194. this._cam_axisY.normalize();
  59195. this._cam_axisX.normalize();
  59196. }
  59197. // if depthSort, compute the camera global position in the mesh local system
  59198. if (this._depthSort) {
  59199. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59200. }
  59201. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59202. var idx = 0; // current position index in the global array positions32
  59203. var index = 0; // position start index in the global array positions32 of the current particle
  59204. var colidx = 0; // current color index in the global array colors32
  59205. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59206. var uvidx = 0; // current uv index in the global array uvs32
  59207. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59208. var pt = 0; // current index in the particle model shape
  59209. if (this.mesh.isFacetDataEnabled) {
  59210. this._computeBoundingBox = true;
  59211. }
  59212. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59213. if (this._computeBoundingBox) {
  59214. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59215. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59216. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59217. }
  59218. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59219. if (this.mesh._boundingInfo) {
  59220. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59221. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59222. }
  59223. }
  59224. }
  59225. // particle loop
  59226. index = this.particles[start]._pos;
  59227. var vpos = (index / 3) | 0;
  59228. colorIndex = vpos * 4;
  59229. uvIndex = vpos * 2;
  59230. for (var p = start; p <= end; p++) {
  59231. this._particle = this.particles[p];
  59232. this._shape = this._particle._model._shape;
  59233. this._shapeUV = this._particle._model._shapeUV;
  59234. // call to custom user function to update the particle properties
  59235. this.updateParticle(this._particle);
  59236. // camera-particle distance for depth sorting
  59237. if (this._depthSort && this._depthSortParticles) {
  59238. var dsp = this.depthSortedParticles[p];
  59239. dsp.ind = this._particle._ind;
  59240. dsp.indicesLength = this._particle._model._indicesLength;
  59241. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59242. }
  59243. // skip the computations for inactive or already invisible particles
  59244. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59245. // increment indexes for the next particle
  59246. pt = this._shape.length;
  59247. index += pt * 3;
  59248. colorIndex += pt * 4;
  59249. uvIndex += pt * 2;
  59250. continue;
  59251. }
  59252. if (this._particle.isVisible) {
  59253. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59254. this._particleHasParent = (this._particle.parentId !== null);
  59255. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59256. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59257. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59258. // particle rotation matrix
  59259. if (this.billboard) {
  59260. this._particle.rotation.x = 0.0;
  59261. this._particle.rotation.y = 0.0;
  59262. }
  59263. if (this._computeParticleRotation || this.billboard) {
  59264. if (this._particle.rotationQuaternion) {
  59265. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59266. }
  59267. else {
  59268. this._yaw = this._particle.rotation.y;
  59269. this._pitch = this._particle.rotation.x;
  59270. this._roll = this._particle.rotation.z;
  59271. this._quaternionRotationYPR();
  59272. }
  59273. this._quaternionToRotationMatrix();
  59274. }
  59275. if (this._particleHasParent) {
  59276. this._parent = this.particles[this._particle.parentId];
  59277. 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];
  59278. 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];
  59279. 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];
  59280. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59281. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59282. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59283. if (this._computeParticleRotation || this.billboard) {
  59284. 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];
  59285. 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];
  59286. 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];
  59287. 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];
  59288. 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];
  59289. 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];
  59290. 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];
  59291. 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];
  59292. 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];
  59293. }
  59294. }
  59295. else {
  59296. this._particle._globalPosition.x = this._particle.position.x;
  59297. this._particle._globalPosition.y = this._particle.position.y;
  59298. this._particle._globalPosition.z = this._particle.position.z;
  59299. if (this._computeParticleRotation || this.billboard) {
  59300. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59301. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59302. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59303. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59304. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59305. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59306. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59307. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59308. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59309. }
  59310. }
  59311. if (this._particle.translateFromPivot) {
  59312. this._pivotBackTranslation.x = 0.0;
  59313. this._pivotBackTranslation.y = 0.0;
  59314. this._pivotBackTranslation.z = 0.0;
  59315. }
  59316. else {
  59317. this._pivotBackTranslation.x = this._scaledPivot.x;
  59318. this._pivotBackTranslation.y = this._scaledPivot.y;
  59319. this._pivotBackTranslation.z = this._scaledPivot.z;
  59320. }
  59321. // particle vertex loop
  59322. for (pt = 0; pt < this._shape.length; pt++) {
  59323. idx = index + pt * 3;
  59324. colidx = colorIndex + pt * 4;
  59325. uvidx = uvIndex + pt * 2;
  59326. this._vertex.x = this._shape[pt].x;
  59327. this._vertex.y = this._shape[pt].y;
  59328. this._vertex.z = this._shape[pt].z;
  59329. if (this._computeParticleVertex) {
  59330. this.updateParticleVertex(this._particle, this._vertex, pt);
  59331. }
  59332. // positions
  59333. this._vertex.x *= this._particle.scaling.x;
  59334. this._vertex.y *= this._particle.scaling.y;
  59335. this._vertex.z *= this._particle.scaling.z;
  59336. this._vertex.x -= this._scaledPivot.x;
  59337. this._vertex.y -= this._scaledPivot.y;
  59338. this._vertex.z -= this._scaledPivot.z;
  59339. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59340. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59341. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59342. this._rotated.x += this._pivotBackTranslation.x;
  59343. this._rotated.y += this._pivotBackTranslation.y;
  59344. this._rotated.z += this._pivotBackTranslation.z;
  59345. 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;
  59346. 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;
  59347. 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;
  59348. if (this._computeBoundingBox) {
  59349. if (this._positions32[idx] < this._minimum.x) {
  59350. this._minimum.x = this._positions32[idx];
  59351. }
  59352. if (this._positions32[idx] > this._maximum.x) {
  59353. this._maximum.x = this._positions32[idx];
  59354. }
  59355. if (this._positions32[idx + 1] < this._minimum.y) {
  59356. this._minimum.y = this._positions32[idx + 1];
  59357. }
  59358. if (this._positions32[idx + 1] > this._maximum.y) {
  59359. this._maximum.y = this._positions32[idx + 1];
  59360. }
  59361. if (this._positions32[idx + 2] < this._minimum.z) {
  59362. this._minimum.z = this._positions32[idx + 2];
  59363. }
  59364. if (this._positions32[idx + 2] > this._maximum.z) {
  59365. this._maximum.z = this._positions32[idx + 2];
  59366. }
  59367. }
  59368. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59369. if (!this._computeParticleVertex) {
  59370. this._normal.x = this._fixedNormal32[idx];
  59371. this._normal.y = this._fixedNormal32[idx + 1];
  59372. this._normal.z = this._fixedNormal32[idx + 2];
  59373. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59374. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59375. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59376. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59377. 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;
  59378. 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;
  59379. }
  59380. if (this._computeParticleColor && this._particle.color) {
  59381. this._colors32[colidx] = this._particle.color.r;
  59382. this._colors32[colidx + 1] = this._particle.color.g;
  59383. this._colors32[colidx + 2] = this._particle.color.b;
  59384. this._colors32[colidx + 3] = this._particle.color.a;
  59385. }
  59386. if (this._computeParticleTexture) {
  59387. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59388. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59389. }
  59390. }
  59391. }
  59392. // particle just set invisible : scaled to zero and positioned at the origin
  59393. else {
  59394. this._particle._stillInvisible = true; // mark the particle as invisible
  59395. for (pt = 0; pt < this._shape.length; pt++) {
  59396. idx = index + pt * 3;
  59397. colidx = colorIndex + pt * 4;
  59398. uvidx = uvIndex + pt * 2;
  59399. this._positions32[idx] = 0.0;
  59400. this._positions32[idx + 1] = 0.0;
  59401. this._positions32[idx + 2] = 0.0;
  59402. this._normals32[idx] = 0.0;
  59403. this._normals32[idx + 1] = 0.0;
  59404. this._normals32[idx + 2] = 0.0;
  59405. if (this._computeParticleColor && this._particle.color) {
  59406. this._colors32[colidx] = this._particle.color.r;
  59407. this._colors32[colidx + 1] = this._particle.color.g;
  59408. this._colors32[colidx + 2] = this._particle.color.b;
  59409. this._colors32[colidx + 3] = this._particle.color.a;
  59410. }
  59411. if (this._computeParticleTexture) {
  59412. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59413. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59414. }
  59415. }
  59416. }
  59417. // if the particle intersections must be computed : update the bbInfo
  59418. if (this._particlesIntersect) {
  59419. var bInfo = this._particle._boundingInfo;
  59420. var bBox = bInfo.boundingBox;
  59421. var bSphere = bInfo.boundingSphere;
  59422. if (!this._bSphereOnly) {
  59423. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59424. for (var b = 0; b < bBox.vectors.length; b++) {
  59425. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59426. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59427. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59428. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59429. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59430. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59431. 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;
  59432. 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;
  59433. 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;
  59434. }
  59435. bBox._update(this.mesh._worldMatrix);
  59436. }
  59437. // place and scale the particle bouding sphere in the SPS local system, then update it
  59438. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59439. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59440. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59441. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59442. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59443. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59444. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59445. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59446. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59447. 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));
  59448. bSphere._update(this.mesh._worldMatrix);
  59449. }
  59450. // increment indexes for the next particle
  59451. index = idx + 3;
  59452. colorIndex = colidx + 4;
  59453. uvIndex = uvidx + 2;
  59454. }
  59455. // if the VBO must be updated
  59456. if (update) {
  59457. if (this._computeParticleColor) {
  59458. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59459. }
  59460. if (this._computeParticleTexture) {
  59461. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59462. }
  59463. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59464. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59465. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59466. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59467. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59468. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59469. for (var i = 0; i < this._normals32.length; i++) {
  59470. this._fixedNormal32[i] = this._normals32[i];
  59471. }
  59472. }
  59473. if (!this.mesh.areNormalsFrozen) {
  59474. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59475. }
  59476. }
  59477. if (this._depthSort && this._depthSortParticles) {
  59478. this.depthSortedParticles.sort(this._depthSortFunction);
  59479. var dspl = this.depthSortedParticles.length;
  59480. var sorted = 0;
  59481. var lind = 0;
  59482. var sind = 0;
  59483. var sid = 0;
  59484. for (sorted = 0; sorted < dspl; sorted++) {
  59485. lind = this.depthSortedParticles[sorted].indicesLength;
  59486. sind = this.depthSortedParticles[sorted].ind;
  59487. for (var i = 0; i < lind; i++) {
  59488. this._indices32[sid] = this._indices[sind + i];
  59489. sid++;
  59490. }
  59491. }
  59492. this.mesh.updateIndices(this._indices32);
  59493. }
  59494. }
  59495. if (this._computeBoundingBox) {
  59496. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59497. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59498. }
  59499. this.afterUpdateParticles(start, end, update);
  59500. return this;
  59501. };
  59502. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59503. this._halfroll = this._roll * 0.5;
  59504. this._halfpitch = this._pitch * 0.5;
  59505. this._halfyaw = this._yaw * 0.5;
  59506. this._sinRoll = Math.sin(this._halfroll);
  59507. this._cosRoll = Math.cos(this._halfroll);
  59508. this._sinPitch = Math.sin(this._halfpitch);
  59509. this._cosPitch = Math.cos(this._halfpitch);
  59510. this._sinYaw = Math.sin(this._halfyaw);
  59511. this._cosYaw = Math.cos(this._halfyaw);
  59512. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59513. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59514. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59515. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59516. };
  59517. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59518. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59519. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59520. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59521. this._rotMatrix.m[3] = 0;
  59522. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59523. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59524. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59525. this._rotMatrix.m[7] = 0;
  59526. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59527. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59528. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59529. this._rotMatrix.m[11] = 0;
  59530. this._rotMatrix.m[12] = 0;
  59531. this._rotMatrix.m[13] = 0;
  59532. this._rotMatrix.m[14] = 0;
  59533. this._rotMatrix.m[15] = 1.0;
  59534. };
  59535. /**
  59536. * Disposes the SPS.
  59537. */
  59538. SolidParticleSystem.prototype.dispose = function () {
  59539. this.mesh.dispose();
  59540. this.vars = null;
  59541. // drop references to internal big arrays for the GC
  59542. this._positions = null;
  59543. this._indices = null;
  59544. this._normals = null;
  59545. this._uvs = null;
  59546. this._colors = null;
  59547. this._indices32 = null;
  59548. this._positions32 = null;
  59549. this._normals32 = null;
  59550. this._fixedNormal32 = null;
  59551. this._uvs32 = null;
  59552. this._colors32 = null;
  59553. this.pickedParticles = null;
  59554. };
  59555. /**
  59556. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59557. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59558. * @returns the SPS.
  59559. */
  59560. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59561. if (!this._isVisibilityBoxLocked) {
  59562. this.mesh.refreshBoundingInfo();
  59563. }
  59564. return this;
  59565. };
  59566. /**
  59567. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59568. * @param size the size (float) of the visibility box
  59569. * note : this doesn't lock the SPS mesh bounding box.
  59570. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59571. */
  59572. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59573. var vis = size / 2;
  59574. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59575. };
  59576. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59577. /**
  59578. * Gets whether the SPS as always visible or not
  59579. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59580. */
  59581. get: function () {
  59582. return this._alwaysVisible;
  59583. },
  59584. /**
  59585. * Sets the SPS as always visible or not
  59586. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59587. */
  59588. set: function (val) {
  59589. this._alwaysVisible = val;
  59590. this.mesh.alwaysSelectAsActiveMesh = val;
  59591. },
  59592. enumerable: true,
  59593. configurable: true
  59594. });
  59595. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59596. /**
  59597. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59598. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59599. */
  59600. get: function () {
  59601. return this._isVisibilityBoxLocked;
  59602. },
  59603. /**
  59604. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59605. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59606. */
  59607. set: function (val) {
  59608. this._isVisibilityBoxLocked = val;
  59609. var boundingInfo = this.mesh.getBoundingInfo();
  59610. boundingInfo.isLocked = val;
  59611. },
  59612. enumerable: true,
  59613. configurable: true
  59614. });
  59615. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59616. /**
  59617. * Gets if `setParticles()` computes the particle rotations or not.
  59618. * Default value : true. The SPS is faster when it's set to false.
  59619. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59620. */
  59621. get: function () {
  59622. return this._computeParticleRotation;
  59623. },
  59624. /**
  59625. * Tells to `setParticles()` to compute the particle rotations or not.
  59626. * Default value : true. The SPS is faster when it's set to false.
  59627. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59628. */
  59629. set: function (val) {
  59630. this._computeParticleRotation = val;
  59631. },
  59632. enumerable: true,
  59633. configurable: true
  59634. });
  59635. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59636. /**
  59637. * Gets if `setParticles()` computes the particle colors or not.
  59638. * Default value : true. The SPS is faster when it's set to false.
  59639. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59640. */
  59641. get: function () {
  59642. return this._computeParticleColor;
  59643. },
  59644. /**
  59645. * Tells to `setParticles()` to compute the particle colors or not.
  59646. * Default value : true. The SPS is faster when it's set to false.
  59647. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59648. */
  59649. set: function (val) {
  59650. this._computeParticleColor = val;
  59651. },
  59652. enumerable: true,
  59653. configurable: true
  59654. });
  59655. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59656. /**
  59657. * Gets if `setParticles()` computes the particle textures or not.
  59658. * Default value : true. The SPS is faster when it's set to false.
  59659. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59660. */
  59661. get: function () {
  59662. return this._computeParticleTexture;
  59663. },
  59664. set: function (val) {
  59665. this._computeParticleTexture = val;
  59666. },
  59667. enumerable: true,
  59668. configurable: true
  59669. });
  59670. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59671. /**
  59672. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59673. * Default value : false. The SPS is faster when it's set to false.
  59674. * Note : the particle custom vertex positions aren't stored values.
  59675. */
  59676. get: function () {
  59677. return this._computeParticleVertex;
  59678. },
  59679. /**
  59680. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59681. * Default value : false. The SPS is faster when it's set to false.
  59682. * Note : the particle custom vertex positions aren't stored values.
  59683. */
  59684. set: function (val) {
  59685. this._computeParticleVertex = val;
  59686. },
  59687. enumerable: true,
  59688. configurable: true
  59689. });
  59690. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59691. /**
  59692. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59693. */
  59694. get: function () {
  59695. return this._computeBoundingBox;
  59696. },
  59697. /**
  59698. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59699. */
  59700. set: function (val) {
  59701. this._computeBoundingBox = val;
  59702. },
  59703. enumerable: true,
  59704. configurable: true
  59705. });
  59706. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59707. /**
  59708. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59709. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59710. * Default : `true`
  59711. */
  59712. get: function () {
  59713. return this._depthSortParticles;
  59714. },
  59715. /**
  59716. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59717. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59718. * Default : `true`
  59719. */
  59720. set: function (val) {
  59721. this._depthSortParticles = val;
  59722. },
  59723. enumerable: true,
  59724. configurable: true
  59725. });
  59726. // =======================================================================
  59727. // Particle behavior logic
  59728. // these following methods may be overwritten by the user to fit his needs
  59729. /**
  59730. * This function does nothing. It may be overwritten to set all the particle first values.
  59731. * The SPS doesn't call this function, you may have to call it by your own.
  59732. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59733. */
  59734. SolidParticleSystem.prototype.initParticles = function () {
  59735. };
  59736. /**
  59737. * This function does nothing. It may be overwritten to recycle a particle.
  59738. * The SPS doesn't call this function, you may have to call it by your own.
  59739. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59740. * @param particle The particle to recycle
  59741. * @returns the recycled particle
  59742. */
  59743. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59744. return particle;
  59745. };
  59746. /**
  59747. * Updates a particle : this function should be overwritten by the user.
  59748. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59749. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59750. * @example : just set a particle position or velocity and recycle conditions
  59751. * @param particle The particle to update
  59752. * @returns the updated particle
  59753. */
  59754. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59755. return particle;
  59756. };
  59757. /**
  59758. * Updates a vertex of a particle : it can be overwritten by the user.
  59759. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59760. * @param particle the current particle
  59761. * @param vertex the current index of the current particle
  59762. * @param pt the index of the current vertex in the particle shape
  59763. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59764. * @example : just set a vertex particle position
  59765. * @returns the updated vertex
  59766. */
  59767. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59768. return vertex;
  59769. };
  59770. /**
  59771. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59772. * This does nothing and may be overwritten by the user.
  59773. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59774. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59775. * @param update the boolean update value actually passed to setParticles()
  59776. */
  59777. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59778. };
  59779. /**
  59780. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59781. * This will be passed three parameters.
  59782. * This does nothing and may be overwritten by the user.
  59783. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59784. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59785. * @param update the boolean update value actually passed to setParticles()
  59786. */
  59787. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59788. };
  59789. return SolidParticleSystem;
  59790. }());
  59791. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59792. })(BABYLON || (BABYLON = {}));
  59793. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59794. var BABYLON;
  59795. (function (BABYLON) {
  59796. var ShaderMaterial = /** @class */ (function (_super) {
  59797. __extends(ShaderMaterial, _super);
  59798. function ShaderMaterial(name, scene, shaderPath, options) {
  59799. var _this = _super.call(this, name, scene) || this;
  59800. _this._textures = {};
  59801. _this._textureArrays = {};
  59802. _this._floats = {};
  59803. _this._ints = {};
  59804. _this._floatsArrays = {};
  59805. _this._colors3 = {};
  59806. _this._colors3Arrays = {};
  59807. _this._colors4 = {};
  59808. _this._vectors2 = {};
  59809. _this._vectors3 = {};
  59810. _this._vectors4 = {};
  59811. _this._matrices = {};
  59812. _this._matrices3x3 = {};
  59813. _this._matrices2x2 = {};
  59814. _this._vectors2Arrays = {};
  59815. _this._vectors3Arrays = {};
  59816. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59817. _this._shaderPath = shaderPath;
  59818. options.needAlphaBlending = options.needAlphaBlending || false;
  59819. options.needAlphaTesting = options.needAlphaTesting || false;
  59820. options.attributes = options.attributes || ["position", "normal", "uv"];
  59821. options.uniforms = options.uniforms || ["worldViewProjection"];
  59822. options.uniformBuffers = options.uniformBuffers || [];
  59823. options.samplers = options.samplers || [];
  59824. options.defines = options.defines || [];
  59825. _this._options = options;
  59826. return _this;
  59827. }
  59828. ShaderMaterial.prototype.getClassName = function () {
  59829. return "ShaderMaterial";
  59830. };
  59831. ShaderMaterial.prototype.needAlphaBlending = function () {
  59832. return this._options.needAlphaBlending;
  59833. };
  59834. ShaderMaterial.prototype.needAlphaTesting = function () {
  59835. return this._options.needAlphaTesting;
  59836. };
  59837. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59838. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59839. this._options.uniforms.push(uniformName);
  59840. }
  59841. };
  59842. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59843. if (this._options.samplers.indexOf(name) === -1) {
  59844. this._options.samplers.push(name);
  59845. }
  59846. this._textures[name] = texture;
  59847. return this;
  59848. };
  59849. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59850. if (this._options.samplers.indexOf(name) === -1) {
  59851. this._options.samplers.push(name);
  59852. }
  59853. this._checkUniform(name);
  59854. this._textureArrays[name] = textures;
  59855. return this;
  59856. };
  59857. ShaderMaterial.prototype.setFloat = function (name, value) {
  59858. this._checkUniform(name);
  59859. this._floats[name] = value;
  59860. return this;
  59861. };
  59862. ShaderMaterial.prototype.setInt = function (name, value) {
  59863. this._checkUniform(name);
  59864. this._ints[name] = value;
  59865. return this;
  59866. };
  59867. ShaderMaterial.prototype.setFloats = function (name, value) {
  59868. this._checkUniform(name);
  59869. this._floatsArrays[name] = value;
  59870. return this;
  59871. };
  59872. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59873. this._checkUniform(name);
  59874. this._colors3[name] = value;
  59875. return this;
  59876. };
  59877. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59878. this._checkUniform(name);
  59879. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59880. color.toArray(arr, arr.length);
  59881. return arr;
  59882. }, []);
  59883. return this;
  59884. };
  59885. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59886. this._checkUniform(name);
  59887. this._colors4[name] = value;
  59888. return this;
  59889. };
  59890. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59891. this._checkUniform(name);
  59892. this._vectors2[name] = value;
  59893. return this;
  59894. };
  59895. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59896. this._checkUniform(name);
  59897. this._vectors3[name] = value;
  59898. return this;
  59899. };
  59900. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59901. this._checkUniform(name);
  59902. this._vectors4[name] = value;
  59903. return this;
  59904. };
  59905. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59906. this._checkUniform(name);
  59907. this._matrices[name] = value;
  59908. return this;
  59909. };
  59910. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59911. this._checkUniform(name);
  59912. this._matrices3x3[name] = value;
  59913. return this;
  59914. };
  59915. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59916. this._checkUniform(name);
  59917. this._matrices2x2[name] = value;
  59918. return this;
  59919. };
  59920. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59921. this._checkUniform(name);
  59922. this._vectors2Arrays[name] = value;
  59923. return this;
  59924. };
  59925. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59926. this._checkUniform(name);
  59927. this._vectors3Arrays[name] = value;
  59928. return this;
  59929. };
  59930. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59931. if (!mesh) {
  59932. return true;
  59933. }
  59934. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59935. return false;
  59936. }
  59937. return false;
  59938. };
  59939. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59940. var scene = this.getScene();
  59941. var engine = scene.getEngine();
  59942. if (!this.checkReadyOnEveryCall) {
  59943. if (this._renderId === scene.getRenderId()) {
  59944. if (this._checkCache(scene, mesh, useInstances)) {
  59945. return true;
  59946. }
  59947. }
  59948. }
  59949. // Instances
  59950. var defines = [];
  59951. var attribs = [];
  59952. var fallbacks = new BABYLON.EffectFallbacks();
  59953. if (useInstances) {
  59954. defines.push("#define INSTANCES");
  59955. }
  59956. for (var index = 0; index < this._options.defines.length; index++) {
  59957. defines.push(this._options.defines[index]);
  59958. }
  59959. for (var index = 0; index < this._options.attributes.length; index++) {
  59960. attribs.push(this._options.attributes[index]);
  59961. }
  59962. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59963. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59964. defines.push("#define VERTEXCOLOR");
  59965. }
  59966. // Bones
  59967. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59970. if (mesh.numBoneInfluencers > 4) {
  59971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59973. }
  59974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59975. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59976. fallbacks.addCPUSkinningFallback(0, mesh);
  59977. if (this._options.uniforms.indexOf("mBones") === -1) {
  59978. this._options.uniforms.push("mBones");
  59979. }
  59980. }
  59981. else {
  59982. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59983. }
  59984. // Textures
  59985. for (var name in this._textures) {
  59986. if (!this._textures[name].isReady()) {
  59987. return false;
  59988. }
  59989. }
  59990. // Alpha test
  59991. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59992. defines.push("#define ALPHATEST");
  59993. }
  59994. var previousEffect = this._effect;
  59995. var join = defines.join("\n");
  59996. this._effect = engine.createEffect(this._shaderPath, {
  59997. attributes: attribs,
  59998. uniformsNames: this._options.uniforms,
  59999. uniformBuffersNames: this._options.uniformBuffers,
  60000. samplers: this._options.samplers,
  60001. defines: join,
  60002. fallbacks: fallbacks,
  60003. onCompiled: this.onCompiled,
  60004. onError: this.onError
  60005. }, engine);
  60006. if (!this._effect.isReady()) {
  60007. return false;
  60008. }
  60009. if (previousEffect !== this._effect) {
  60010. scene.resetCachedMaterial();
  60011. }
  60012. this._renderId = scene.getRenderId();
  60013. return true;
  60014. };
  60015. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60016. var scene = this.getScene();
  60017. if (!this._effect) {
  60018. return;
  60019. }
  60020. if (this._options.uniforms.indexOf("world") !== -1) {
  60021. this._effect.setMatrix("world", world);
  60022. }
  60023. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60024. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60025. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60026. }
  60027. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60028. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60029. }
  60030. };
  60031. ShaderMaterial.prototype.bind = function (world, mesh) {
  60032. // Std values
  60033. this.bindOnlyWorldMatrix(world);
  60034. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60035. if (this._options.uniforms.indexOf("view") !== -1) {
  60036. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60037. }
  60038. if (this._options.uniforms.indexOf("projection") !== -1) {
  60039. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60040. }
  60041. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60042. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60043. }
  60044. // Bones
  60045. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60046. var name;
  60047. // Texture
  60048. for (name in this._textures) {
  60049. this._effect.setTexture(name, this._textures[name]);
  60050. }
  60051. // Texture arrays
  60052. for (name in this._textureArrays) {
  60053. this._effect.setTextureArray(name, this._textureArrays[name]);
  60054. }
  60055. // Int
  60056. for (name in this._ints) {
  60057. this._effect.setInt(name, this._ints[name]);
  60058. }
  60059. // Float
  60060. for (name in this._floats) {
  60061. this._effect.setFloat(name, this._floats[name]);
  60062. }
  60063. // Floats
  60064. for (name in this._floatsArrays) {
  60065. this._effect.setArray(name, this._floatsArrays[name]);
  60066. }
  60067. // Color3
  60068. for (name in this._colors3) {
  60069. this._effect.setColor3(name, this._colors3[name]);
  60070. }
  60071. for (name in this._colors3Arrays) {
  60072. this._effect.setArray3(name, this._colors3Arrays[name]);
  60073. }
  60074. // Color4
  60075. for (name in this._colors4) {
  60076. var color = this._colors4[name];
  60077. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60078. }
  60079. // Vector2
  60080. for (name in this._vectors2) {
  60081. this._effect.setVector2(name, this._vectors2[name]);
  60082. }
  60083. // Vector3
  60084. for (name in this._vectors3) {
  60085. this._effect.setVector3(name, this._vectors3[name]);
  60086. }
  60087. // Vector4
  60088. for (name in this._vectors4) {
  60089. this._effect.setVector4(name, this._vectors4[name]);
  60090. }
  60091. // Matrix
  60092. for (name in this._matrices) {
  60093. this._effect.setMatrix(name, this._matrices[name]);
  60094. }
  60095. // Matrix 3x3
  60096. for (name in this._matrices3x3) {
  60097. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60098. }
  60099. // Matrix 2x2
  60100. for (name in this._matrices2x2) {
  60101. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60102. }
  60103. // Vector2Array
  60104. for (name in this._vectors2Arrays) {
  60105. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60106. }
  60107. // Vector3Array
  60108. for (name in this._vectors3Arrays) {
  60109. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60110. }
  60111. }
  60112. this._afterBind(mesh);
  60113. };
  60114. ShaderMaterial.prototype.getActiveTextures = function () {
  60115. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60116. for (var name in this._textures) {
  60117. activeTextures.push(this._textures[name]);
  60118. }
  60119. for (var name in this._textureArrays) {
  60120. var array = this._textureArrays[name];
  60121. for (var index = 0; index < array.length; index++) {
  60122. activeTextures.push(array[index]);
  60123. }
  60124. }
  60125. return activeTextures;
  60126. };
  60127. ShaderMaterial.prototype.hasTexture = function (texture) {
  60128. if (_super.prototype.hasTexture.call(this, texture)) {
  60129. return true;
  60130. }
  60131. for (var name in this._textures) {
  60132. if (this._textures[name] === texture) {
  60133. return true;
  60134. }
  60135. }
  60136. for (var name in this._textureArrays) {
  60137. var array = this._textureArrays[name];
  60138. for (var index = 0; index < array.length; index++) {
  60139. if (array[index] === texture) {
  60140. return true;
  60141. }
  60142. }
  60143. }
  60144. return false;
  60145. };
  60146. ShaderMaterial.prototype.clone = function (name) {
  60147. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60148. return newShaderMaterial;
  60149. };
  60150. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60151. if (forceDisposeTextures) {
  60152. var name;
  60153. for (name in this._textures) {
  60154. this._textures[name].dispose();
  60155. }
  60156. for (name in this._textureArrays) {
  60157. var array = this._textureArrays[name];
  60158. for (var index = 0; index < array.length; index++) {
  60159. array[index].dispose();
  60160. }
  60161. }
  60162. }
  60163. this._textures = {};
  60164. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60165. };
  60166. ShaderMaterial.prototype.serialize = function () {
  60167. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60168. serializationObject.customType = "BABYLON.ShaderMaterial";
  60169. serializationObject.options = this._options;
  60170. serializationObject.shaderPath = this._shaderPath;
  60171. var name;
  60172. // Texture
  60173. serializationObject.textures = {};
  60174. for (name in this._textures) {
  60175. serializationObject.textures[name] = this._textures[name].serialize();
  60176. }
  60177. // Texture arrays
  60178. serializationObject.textureArrays = {};
  60179. for (name in this._textureArrays) {
  60180. serializationObject.textureArrays[name] = [];
  60181. var array = this._textureArrays[name];
  60182. for (var index = 0; index < array.length; index++) {
  60183. serializationObject.textureArrays[name].push(array[index].serialize());
  60184. }
  60185. }
  60186. // Float
  60187. serializationObject.floats = {};
  60188. for (name in this._floats) {
  60189. serializationObject.floats[name] = this._floats[name];
  60190. }
  60191. // Float s
  60192. serializationObject.FloatArrays = {};
  60193. for (name in this._floatsArrays) {
  60194. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60195. }
  60196. // Color3
  60197. serializationObject.colors3 = {};
  60198. for (name in this._colors3) {
  60199. serializationObject.colors3[name] = this._colors3[name].asArray();
  60200. }
  60201. // Color3 array
  60202. serializationObject.colors3Arrays = {};
  60203. for (name in this._colors3Arrays) {
  60204. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60205. }
  60206. // Color4
  60207. serializationObject.colors4 = {};
  60208. for (name in this._colors4) {
  60209. serializationObject.colors4[name] = this._colors4[name].asArray();
  60210. }
  60211. // Vector2
  60212. serializationObject.vectors2 = {};
  60213. for (name in this._vectors2) {
  60214. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60215. }
  60216. // Vector3
  60217. serializationObject.vectors3 = {};
  60218. for (name in this._vectors3) {
  60219. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60220. }
  60221. // Vector4
  60222. serializationObject.vectors4 = {};
  60223. for (name in this._vectors4) {
  60224. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60225. }
  60226. // Matrix
  60227. serializationObject.matrices = {};
  60228. for (name in this._matrices) {
  60229. serializationObject.matrices[name] = this._matrices[name].asArray();
  60230. }
  60231. // Matrix 3x3
  60232. serializationObject.matrices3x3 = {};
  60233. for (name in this._matrices3x3) {
  60234. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60235. }
  60236. // Matrix 2x2
  60237. serializationObject.matrices2x2 = {};
  60238. for (name in this._matrices2x2) {
  60239. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60240. }
  60241. // Vector2Array
  60242. serializationObject.vectors2Arrays = {};
  60243. for (name in this._vectors2Arrays) {
  60244. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60245. }
  60246. // Vector3Array
  60247. serializationObject.vectors3Arrays = {};
  60248. for (name in this._vectors3Arrays) {
  60249. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60250. }
  60251. return serializationObject;
  60252. };
  60253. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60254. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60255. var name;
  60256. // Texture
  60257. for (name in source.textures) {
  60258. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60259. }
  60260. // Texture arrays
  60261. for (name in source.textureArrays) {
  60262. var array = source.textureArrays[name];
  60263. var textureArray = new Array();
  60264. for (var index = 0; index < array.length; index++) {
  60265. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60266. }
  60267. material.setTextureArray(name, textureArray);
  60268. }
  60269. // Float
  60270. for (name in source.floats) {
  60271. material.setFloat(name, source.floats[name]);
  60272. }
  60273. // Float s
  60274. for (name in source.floatsArrays) {
  60275. material.setFloats(name, source.floatsArrays[name]);
  60276. }
  60277. // Color3
  60278. for (name in source.colors3) {
  60279. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60280. }
  60281. // Color3 arrays
  60282. for (name in source.colors3Arrays) {
  60283. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60284. if (i % 3 === 0) {
  60285. arr.push([num]);
  60286. }
  60287. else {
  60288. arr[arr.length - 1].push(num);
  60289. }
  60290. return arr;
  60291. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60292. material.setColor3Array(name, colors);
  60293. }
  60294. // Color4
  60295. for (name in source.colors4) {
  60296. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60297. }
  60298. // Vector2
  60299. for (name in source.vectors2) {
  60300. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60301. }
  60302. // Vector3
  60303. for (name in source.vectors3) {
  60304. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60305. }
  60306. // Vector4
  60307. for (name in source.vectors4) {
  60308. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60309. }
  60310. // Matrix
  60311. for (name in source.matrices) {
  60312. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60313. }
  60314. // Matrix 3x3
  60315. for (name in source.matrices3x3) {
  60316. material.setMatrix3x3(name, source.matrices3x3[name]);
  60317. }
  60318. // Matrix 2x2
  60319. for (name in source.matrices2x2) {
  60320. material.setMatrix2x2(name, source.matrices2x2[name]);
  60321. }
  60322. // Vector2Array
  60323. for (name in source.vectors2Arrays) {
  60324. material.setArray2(name, source.vectors2Arrays[name]);
  60325. }
  60326. // Vector3Array
  60327. for (name in source.vectors3Arrays) {
  60328. material.setArray3(name, source.vectors3Arrays[name]);
  60329. }
  60330. return material;
  60331. };
  60332. return ShaderMaterial;
  60333. }(BABYLON.Material));
  60334. BABYLON.ShaderMaterial = ShaderMaterial;
  60335. })(BABYLON || (BABYLON = {}));
  60336. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60337. var BABYLON;
  60338. (function (BABYLON) {
  60339. var GroundMesh = /** @class */ (function (_super) {
  60340. __extends(GroundMesh, _super);
  60341. function GroundMesh(name, scene) {
  60342. var _this = _super.call(this, name, scene) || this;
  60343. _this.generateOctree = false;
  60344. return _this;
  60345. }
  60346. GroundMesh.prototype.getClassName = function () {
  60347. return "GroundMesh";
  60348. };
  60349. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60350. get: function () {
  60351. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60352. },
  60353. enumerable: true,
  60354. configurable: true
  60355. });
  60356. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60357. get: function () {
  60358. return this._subdivisionsX;
  60359. },
  60360. enumerable: true,
  60361. configurable: true
  60362. });
  60363. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60364. get: function () {
  60365. return this._subdivisionsY;
  60366. },
  60367. enumerable: true,
  60368. configurable: true
  60369. });
  60370. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60371. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60372. this._subdivisionsX = chunksCount;
  60373. this._subdivisionsY = chunksCount;
  60374. this.subdivide(chunksCount);
  60375. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60376. };
  60377. /**
  60378. * Returns a height (y) value in the Worl system :
  60379. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60380. * Returns the ground y position if (x, z) are outside the ground surface.
  60381. */
  60382. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60383. var world = this.getWorldMatrix();
  60384. var invMat = BABYLON.Tmp.Matrix[5];
  60385. world.invertToRef(invMat);
  60386. var tmpVect = BABYLON.Tmp.Vector3[8];
  60387. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60388. x = tmpVect.x;
  60389. z = tmpVect.z;
  60390. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60391. return this.position.y;
  60392. }
  60393. if (!this._heightQuads || this._heightQuads.length == 0) {
  60394. this._initHeightQuads();
  60395. this._computeHeightQuads();
  60396. }
  60397. var facet = this._getFacetAt(x, z);
  60398. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60399. // return y in the World system
  60400. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60401. return tmpVect.y;
  60402. };
  60403. /**
  60404. * Returns a normalized vector (Vector3) orthogonal to the ground
  60405. * at the ground coordinates (x, z) expressed in the World system.
  60406. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60407. */
  60408. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60409. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60410. this.getNormalAtCoordinatesToRef(x, z, normal);
  60411. return normal;
  60412. };
  60413. /**
  60414. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60415. * at the ground coordinates (x, z) expressed in the World system.
  60416. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60417. * Returns the GroundMesh.
  60418. */
  60419. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60420. var world = this.getWorldMatrix();
  60421. var tmpMat = BABYLON.Tmp.Matrix[5];
  60422. world.invertToRef(tmpMat);
  60423. var tmpVect = BABYLON.Tmp.Vector3[8];
  60424. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60425. x = tmpVect.x;
  60426. z = tmpVect.z;
  60427. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60428. return this;
  60429. }
  60430. if (!this._heightQuads || this._heightQuads.length == 0) {
  60431. this._initHeightQuads();
  60432. this._computeHeightQuads();
  60433. }
  60434. var facet = this._getFacetAt(x, z);
  60435. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60436. return this;
  60437. };
  60438. /**
  60439. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60440. * if the ground has been updated.
  60441. * This can be used in the render loop.
  60442. * Returns the GroundMesh.
  60443. */
  60444. GroundMesh.prototype.updateCoordinateHeights = function () {
  60445. if (!this._heightQuads || this._heightQuads.length == 0) {
  60446. this._initHeightQuads();
  60447. }
  60448. this._computeHeightQuads();
  60449. return this;
  60450. };
  60451. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60452. GroundMesh.prototype._getFacetAt = function (x, z) {
  60453. // retrieve col and row from x, z coordinates in the ground local system
  60454. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60455. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60456. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60457. var facet;
  60458. if (z < quad.slope.x * x + quad.slope.y) {
  60459. facet = quad.facet1;
  60460. }
  60461. else {
  60462. facet = quad.facet2;
  60463. }
  60464. return facet;
  60465. };
  60466. // Creates and populates the heightMap array with "facet" elements :
  60467. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60468. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60469. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60470. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60471. // Returns the GroundMesh.
  60472. GroundMesh.prototype._initHeightQuads = function () {
  60473. var subdivisionsX = this._subdivisionsX;
  60474. var subdivisionsY = this._subdivisionsY;
  60475. this._heightQuads = new Array();
  60476. for (var row = 0; row < subdivisionsY; row++) {
  60477. for (var col = 0; col < subdivisionsX; col++) {
  60478. 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) };
  60479. this._heightQuads[row * subdivisionsX + col] = quad;
  60480. }
  60481. }
  60482. return this;
  60483. };
  60484. // Compute each quad element values and update the the heightMap array :
  60485. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60486. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60487. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60488. // Returns the GroundMesh.
  60489. GroundMesh.prototype._computeHeightQuads = function () {
  60490. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60491. if (!positions) {
  60492. return this;
  60493. }
  60494. var v1 = BABYLON.Tmp.Vector3[3];
  60495. var v2 = BABYLON.Tmp.Vector3[2];
  60496. var v3 = BABYLON.Tmp.Vector3[1];
  60497. var v4 = BABYLON.Tmp.Vector3[0];
  60498. var v1v2 = BABYLON.Tmp.Vector3[4];
  60499. var v1v3 = BABYLON.Tmp.Vector3[5];
  60500. var v1v4 = BABYLON.Tmp.Vector3[6];
  60501. var norm1 = BABYLON.Tmp.Vector3[7];
  60502. var norm2 = BABYLON.Tmp.Vector3[8];
  60503. var i = 0;
  60504. var j = 0;
  60505. var k = 0;
  60506. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60507. var h = 0;
  60508. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60509. var d2 = 0;
  60510. var subdivisionsX = this._subdivisionsX;
  60511. var subdivisionsY = this._subdivisionsY;
  60512. for (var row = 0; row < subdivisionsY; row++) {
  60513. for (var col = 0; col < subdivisionsX; col++) {
  60514. i = col * 3;
  60515. j = row * (subdivisionsX + 1) * 3;
  60516. k = (row + 1) * (subdivisionsX + 1) * 3;
  60517. v1.x = positions[j + i];
  60518. v1.y = positions[j + i + 1];
  60519. v1.z = positions[j + i + 2];
  60520. v2.x = positions[j + i + 3];
  60521. v2.y = positions[j + i + 4];
  60522. v2.z = positions[j + i + 5];
  60523. v3.x = positions[k + i];
  60524. v3.y = positions[k + i + 1];
  60525. v3.z = positions[k + i + 2];
  60526. v4.x = positions[k + i + 3];
  60527. v4.y = positions[k + i + 4];
  60528. v4.z = positions[k + i + 5];
  60529. // 2D slope V1V4
  60530. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60531. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60532. // facet equations :
  60533. // we compute each facet normal vector
  60534. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60535. // we compute the value d by applying the equation to v1 which belongs to the plane
  60536. // then we store the facet equation in a Vector4
  60537. v2.subtractToRef(v1, v1v2);
  60538. v3.subtractToRef(v1, v1v3);
  60539. v4.subtractToRef(v1, v1v4);
  60540. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60541. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60542. norm1.normalize();
  60543. norm2.normalize();
  60544. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60545. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60546. var quad = this._heightQuads[row * subdivisionsX + col];
  60547. quad.slope.copyFromFloats(cd, h);
  60548. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60549. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60550. }
  60551. }
  60552. return this;
  60553. };
  60554. GroundMesh.prototype.serialize = function (serializationObject) {
  60555. _super.prototype.serialize.call(this, serializationObject);
  60556. serializationObject.subdivisionsX = this._subdivisionsX;
  60557. serializationObject.subdivisionsY = this._subdivisionsY;
  60558. serializationObject.minX = this._minX;
  60559. serializationObject.maxX = this._maxX;
  60560. serializationObject.minZ = this._minZ;
  60561. serializationObject.maxZ = this._maxZ;
  60562. serializationObject.width = this._width;
  60563. serializationObject.height = this._height;
  60564. };
  60565. GroundMesh.Parse = function (parsedMesh, scene) {
  60566. var result = new GroundMesh(parsedMesh.name, scene);
  60567. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60568. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60569. result._minX = parsedMesh.minX;
  60570. result._maxX = parsedMesh.maxX;
  60571. result._minZ = parsedMesh.minZ;
  60572. result._maxZ = parsedMesh.maxZ;
  60573. result._width = parsedMesh.width;
  60574. result._height = parsedMesh.height;
  60575. return result;
  60576. };
  60577. return GroundMesh;
  60578. }(BABYLON.Mesh));
  60579. BABYLON.GroundMesh = GroundMesh;
  60580. })(BABYLON || (BABYLON = {}));
  60581. //# sourceMappingURL=babylon.groundMesh.js.map
  60582. var BABYLON;
  60583. (function (BABYLON) {
  60584. /**
  60585. * Creates an instance based on a source mesh.
  60586. */
  60587. var InstancedMesh = /** @class */ (function (_super) {
  60588. __extends(InstancedMesh, _super);
  60589. function InstancedMesh(name, source) {
  60590. var _this = _super.call(this, name, source.getScene()) || this;
  60591. source.instances.push(_this);
  60592. _this._sourceMesh = source;
  60593. _this.position.copyFrom(source.position);
  60594. _this.rotation.copyFrom(source.rotation);
  60595. _this.scaling.copyFrom(source.scaling);
  60596. if (source.rotationQuaternion) {
  60597. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60598. }
  60599. _this.infiniteDistance = source.infiniteDistance;
  60600. _this.setPivotMatrix(source.getPivotMatrix());
  60601. _this.refreshBoundingInfo();
  60602. _this._syncSubMeshes();
  60603. return _this;
  60604. }
  60605. /**
  60606. * Returns the string "InstancedMesh".
  60607. */
  60608. InstancedMesh.prototype.getClassName = function () {
  60609. return "InstancedMesh";
  60610. };
  60611. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60612. // Methods
  60613. get: function () {
  60614. return this._sourceMesh.receiveShadows;
  60615. },
  60616. enumerable: true,
  60617. configurable: true
  60618. });
  60619. Object.defineProperty(InstancedMesh.prototype, "material", {
  60620. get: function () {
  60621. return this._sourceMesh.material;
  60622. },
  60623. enumerable: true,
  60624. configurable: true
  60625. });
  60626. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60627. get: function () {
  60628. return this._sourceMesh.visibility;
  60629. },
  60630. enumerable: true,
  60631. configurable: true
  60632. });
  60633. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60634. get: function () {
  60635. return this._sourceMesh.skeleton;
  60636. },
  60637. enumerable: true,
  60638. configurable: true
  60639. });
  60640. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60641. get: function () {
  60642. return this._sourceMesh.renderingGroupId;
  60643. },
  60644. set: function (value) {
  60645. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60646. return;
  60647. }
  60648. //no-op with warning
  60649. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60650. },
  60651. enumerable: true,
  60652. configurable: true
  60653. });
  60654. /**
  60655. * Returns the total number of vertices (integer).
  60656. */
  60657. InstancedMesh.prototype.getTotalVertices = function () {
  60658. return this._sourceMesh.getTotalVertices();
  60659. };
  60660. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60661. get: function () {
  60662. return this._sourceMesh;
  60663. },
  60664. enumerable: true,
  60665. configurable: true
  60666. });
  60667. /**
  60668. * Is this node ready to be used/rendered
  60669. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60670. * @return {boolean} is it ready
  60671. */
  60672. InstancedMesh.prototype.isReady = function (completeCheck) {
  60673. if (completeCheck === void 0) { completeCheck = false; }
  60674. return this._sourceMesh.isReady(completeCheck, true);
  60675. };
  60676. /**
  60677. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60678. */
  60679. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60680. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60681. };
  60682. /**
  60683. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60684. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60685. * The `data` are either a numeric array either a Float32Array.
  60686. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60687. * 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).
  60688. * Note that a new underlying VertexBuffer object is created each call.
  60689. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60690. *
  60691. * Possible `kind` values :
  60692. * - BABYLON.VertexBuffer.PositionKind
  60693. * - BABYLON.VertexBuffer.UVKind
  60694. * - BABYLON.VertexBuffer.UV2Kind
  60695. * - BABYLON.VertexBuffer.UV3Kind
  60696. * - BABYLON.VertexBuffer.UV4Kind
  60697. * - BABYLON.VertexBuffer.UV5Kind
  60698. * - BABYLON.VertexBuffer.UV6Kind
  60699. * - BABYLON.VertexBuffer.ColorKind
  60700. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60701. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60702. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60703. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60704. *
  60705. * Returns the Mesh.
  60706. */
  60707. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60708. if (this.sourceMesh) {
  60709. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60710. }
  60711. return this.sourceMesh;
  60712. };
  60713. /**
  60714. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60715. * If the mesh has no geometry, it is simply returned as it is.
  60716. * The `data` are either a numeric array either a Float32Array.
  60717. * No new underlying VertexBuffer object is created.
  60718. * 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.
  60719. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60720. *
  60721. * Possible `kind` values :
  60722. * - BABYLON.VertexBuffer.PositionKind
  60723. * - BABYLON.VertexBuffer.UVKind
  60724. * - BABYLON.VertexBuffer.UV2Kind
  60725. * - BABYLON.VertexBuffer.UV3Kind
  60726. * - BABYLON.VertexBuffer.UV4Kind
  60727. * - BABYLON.VertexBuffer.UV5Kind
  60728. * - BABYLON.VertexBuffer.UV6Kind
  60729. * - BABYLON.VertexBuffer.ColorKind
  60730. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60731. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60732. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60733. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60734. *
  60735. * Returns the Mesh.
  60736. */
  60737. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60738. if (this.sourceMesh) {
  60739. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60740. }
  60741. return this.sourceMesh;
  60742. };
  60743. /**
  60744. * Sets the mesh indices.
  60745. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60746. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60747. * This method creates a new index buffer each call.
  60748. * Returns the Mesh.
  60749. */
  60750. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60751. if (totalVertices === void 0) { totalVertices = null; }
  60752. if (this.sourceMesh) {
  60753. this.sourceMesh.setIndices(indices, totalVertices);
  60754. }
  60755. return this.sourceMesh;
  60756. };
  60757. /**
  60758. * Boolean : True if the mesh owns the requested kind of data.
  60759. */
  60760. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60761. return this._sourceMesh.isVerticesDataPresent(kind);
  60762. };
  60763. /**
  60764. * Returns an array of indices (IndicesArray).
  60765. */
  60766. InstancedMesh.prototype.getIndices = function () {
  60767. return this._sourceMesh.getIndices();
  60768. };
  60769. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60770. get: function () {
  60771. return this._sourceMesh._positions;
  60772. },
  60773. enumerable: true,
  60774. configurable: true
  60775. });
  60776. /**
  60777. * Sets a new updated BoundingInfo to the mesh.
  60778. * Returns the mesh.
  60779. */
  60780. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60781. var meshBB = this._sourceMesh.getBoundingInfo();
  60782. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60783. this._updateBoundingInfo();
  60784. return this;
  60785. };
  60786. InstancedMesh.prototype._preActivate = function () {
  60787. if (this._currentLOD) {
  60788. this._currentLOD._preActivate();
  60789. }
  60790. return this;
  60791. };
  60792. InstancedMesh.prototype._activate = function (renderId) {
  60793. if (this._currentLOD) {
  60794. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60795. }
  60796. return this;
  60797. };
  60798. /**
  60799. * Returns the current associated LOD AbstractMesh.
  60800. */
  60801. InstancedMesh.prototype.getLOD = function (camera) {
  60802. if (!camera) {
  60803. return this;
  60804. }
  60805. var boundingInfo = this.getBoundingInfo();
  60806. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60807. if (this._currentLOD === this.sourceMesh) {
  60808. return this;
  60809. }
  60810. return this._currentLOD;
  60811. };
  60812. InstancedMesh.prototype._syncSubMeshes = function () {
  60813. this.releaseSubMeshes();
  60814. if (this._sourceMesh.subMeshes) {
  60815. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60816. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60817. }
  60818. }
  60819. return this;
  60820. };
  60821. InstancedMesh.prototype._generatePointsArray = function () {
  60822. return this._sourceMesh._generatePointsArray();
  60823. };
  60824. /**
  60825. * Creates a new InstancedMesh from the current mesh.
  60826. * - name (string) : the cloned mesh name
  60827. * - newParent (optional Node) : the optional Node to parent the clone to.
  60828. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60829. *
  60830. * Returns the clone.
  60831. */
  60832. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60833. var result = this._sourceMesh.createInstance(name);
  60834. // Deep copy
  60835. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60836. // Bounding info
  60837. this.refreshBoundingInfo();
  60838. // Parent
  60839. if (newParent) {
  60840. result.parent = newParent;
  60841. }
  60842. if (!doNotCloneChildren) {
  60843. // Children
  60844. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60845. var mesh = this.getScene().meshes[index];
  60846. if (mesh.parent === this) {
  60847. mesh.clone(mesh.name, result);
  60848. }
  60849. }
  60850. }
  60851. result.computeWorldMatrix(true);
  60852. return result;
  60853. };
  60854. /**
  60855. * Disposes the InstancedMesh.
  60856. * Returns nothing.
  60857. */
  60858. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60859. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60860. // Remove from mesh
  60861. var index = this._sourceMesh.instances.indexOf(this);
  60862. this._sourceMesh.instances.splice(index, 1);
  60863. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60864. };
  60865. return InstancedMesh;
  60866. }(BABYLON.AbstractMesh));
  60867. BABYLON.InstancedMesh = InstancedMesh;
  60868. })(BABYLON || (BABYLON = {}));
  60869. //# sourceMappingURL=babylon.instancedMesh.js.map
  60870. var BABYLON;
  60871. (function (BABYLON) {
  60872. var LinesMesh = /** @class */ (function (_super) {
  60873. __extends(LinesMesh, _super);
  60874. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60875. if (scene === void 0) { scene = null; }
  60876. if (parent === void 0) { parent = null; }
  60877. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60878. _this.useVertexColor = useVertexColor;
  60879. _this.useVertexAlpha = useVertexAlpha;
  60880. _this.color = new BABYLON.Color3(1, 1, 1);
  60881. _this.alpha = 1;
  60882. if (source) {
  60883. _this.color = source.color.clone();
  60884. _this.alpha = source.alpha;
  60885. _this.useVertexColor = source.useVertexColor;
  60886. _this.useVertexAlpha = source.useVertexAlpha;
  60887. }
  60888. _this._intersectionThreshold = 0.1;
  60889. var defines = [];
  60890. var options = {
  60891. attributes: [BABYLON.VertexBuffer.PositionKind],
  60892. uniforms: ["world", "viewProjection"],
  60893. needAlphaBlending: true,
  60894. defines: defines
  60895. };
  60896. if (useVertexAlpha === false) {
  60897. options.needAlphaBlending = false;
  60898. }
  60899. if (!useVertexColor) {
  60900. options.uniforms.push("color");
  60901. }
  60902. else {
  60903. options.defines.push("#define VERTEXCOLOR");
  60904. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60905. }
  60906. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60907. return _this;
  60908. }
  60909. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60910. /**
  60911. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60912. * This margin is expressed in world space coordinates, so its value may vary.
  60913. * Default value is 0.1
  60914. * @returns the intersection Threshold value.
  60915. */
  60916. get: function () {
  60917. return this._intersectionThreshold;
  60918. },
  60919. /**
  60920. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60921. * This margin is expressed in world space coordinates, so its value may vary.
  60922. * @param value the new threshold to apply
  60923. */
  60924. set: function (value) {
  60925. if (this._intersectionThreshold === value) {
  60926. return;
  60927. }
  60928. this._intersectionThreshold = value;
  60929. if (this.geometry) {
  60930. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60931. }
  60932. },
  60933. enumerable: true,
  60934. configurable: true
  60935. });
  60936. /**
  60937. * Returns the string "LineMesh"
  60938. */
  60939. LinesMesh.prototype.getClassName = function () {
  60940. return "LinesMesh";
  60941. };
  60942. Object.defineProperty(LinesMesh.prototype, "material", {
  60943. get: function () {
  60944. return this._colorShader;
  60945. },
  60946. set: function (value) {
  60947. // Do nothing
  60948. },
  60949. enumerable: true,
  60950. configurable: true
  60951. });
  60952. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60953. get: function () {
  60954. return false;
  60955. },
  60956. enumerable: true,
  60957. configurable: true
  60958. });
  60959. LinesMesh.prototype.createInstance = function (name) {
  60960. throw new Error("LinesMeshes do not support createInstance.");
  60961. };
  60962. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60963. if (!this._geometry) {
  60964. return this;
  60965. }
  60966. // VBOs
  60967. this._geometry._bind(this._colorShader.getEffect());
  60968. // Color
  60969. if (!this.useVertexColor) {
  60970. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60971. }
  60972. return this;
  60973. };
  60974. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60975. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60976. return this;
  60977. }
  60978. var engine = this.getScene().getEngine();
  60979. // Draw order
  60980. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60981. return this;
  60982. };
  60983. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60984. this._colorShader.dispose();
  60985. _super.prototype.dispose.call(this, doNotRecurse);
  60986. };
  60987. /**
  60988. * Returns a new LineMesh object cloned from the current one.
  60989. */
  60990. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60991. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60992. };
  60993. return LinesMesh;
  60994. }(BABYLON.Mesh));
  60995. BABYLON.LinesMesh = LinesMesh;
  60996. })(BABYLON || (BABYLON = {}));
  60997. //# sourceMappingURL=babylon.linesMesh.js.map
  60998. var BABYLON;
  60999. (function (BABYLON) {
  61000. /**
  61001. * Class containing static functions to help procedurally build meshes
  61002. */
  61003. var MeshBuilder = /** @class */ (function () {
  61004. function MeshBuilder() {
  61005. }
  61006. MeshBuilder.updateSideOrientation = function (orientation) {
  61007. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  61008. return BABYLON.Mesh.DOUBLESIDE;
  61009. }
  61010. if (orientation === undefined || orientation === null) {
  61011. return BABYLON.Mesh.FRONTSIDE;
  61012. }
  61013. return orientation;
  61014. };
  61015. /**
  61016. * Creates a box mesh
  61017. * * The parameter `size` sets the size (float) of each box side (default 1)
  61018. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  61019. * * 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)
  61020. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61021. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61022. * * 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
  61023. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61024. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  61025. * @param name defines the name of the mesh
  61026. * @param options defines the options used to create the mesh
  61027. * @param scene defines the hosting scene
  61028. * @returns the box mesh
  61029. */
  61030. MeshBuilder.CreateBox = function (name, options, scene) {
  61031. if (scene === void 0) { scene = null; }
  61032. var box = new BABYLON.Mesh(name, scene);
  61033. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61034. box._originalBuilderSideOrientation = options.sideOrientation;
  61035. var vertexData = BABYLON.VertexData.CreateBox(options);
  61036. vertexData.applyToMesh(box, options.updatable);
  61037. return box;
  61038. };
  61039. /**
  61040. * Creates a sphere mesh
  61041. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  61042. * * 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`)
  61043. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  61044. * * 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
  61045. * * 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)
  61046. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61047. * * 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
  61048. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61049. * @param name defines the name of the mesh
  61050. * @param options defines the options used to create the mesh
  61051. * @param scene defines the hosting scene
  61052. * @returns the sphere mesh
  61053. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  61054. */
  61055. MeshBuilder.CreateSphere = function (name, options, scene) {
  61056. var sphere = new BABYLON.Mesh(name, scene);
  61057. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61058. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61059. var vertexData = BABYLON.VertexData.CreateSphere(options);
  61060. vertexData.applyToMesh(sphere, options.updatable);
  61061. return sphere;
  61062. };
  61063. /**
  61064. * Creates a plane polygonal mesh. By default, this is a disc
  61065. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61066. * * 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
  61067. * * 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
  61068. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61069. * * 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
  61070. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61071. * @param name defines the name of the mesh
  61072. * @param options defines the options used to create the mesh
  61073. * @param scene defines the hosting scene
  61074. * @returns the plane polygonal mesh
  61075. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61076. */
  61077. MeshBuilder.CreateDisc = function (name, options, scene) {
  61078. if (scene === void 0) { scene = null; }
  61079. var disc = new BABYLON.Mesh(name, scene);
  61080. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61081. disc._originalBuilderSideOrientation = options.sideOrientation;
  61082. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61083. vertexData.applyToMesh(disc, options.updatable);
  61084. return disc;
  61085. };
  61086. /**
  61087. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61088. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61089. * * 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`)
  61090. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61091. * * 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
  61092. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61093. * * 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
  61094. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61095. * @param name defines the name of the mesh
  61096. * @param options defines the options used to create the mesh
  61097. * @param scene defines the hosting scene
  61098. * @returns the icosahedron mesh
  61099. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61100. */
  61101. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61102. var sphere = new BABYLON.Mesh(name, scene);
  61103. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61104. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61105. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61106. vertexData.applyToMesh(sphere, options.updatable);
  61107. return sphere;
  61108. };
  61109. ;
  61110. /**
  61111. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61112. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61113. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61114. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61115. * * 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
  61116. * * 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
  61117. * * 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
  61118. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61119. * * 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
  61120. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61121. * * 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
  61122. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61123. * * 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
  61124. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61125. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61126. * @param name defines the name of the mesh
  61127. * @param options defines the options used to create the mesh
  61128. * @param scene defines the hosting scene
  61129. * @returns the ribbon mesh
  61130. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61131. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61132. */
  61133. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61134. if (scene === void 0) { scene = null; }
  61135. var pathArray = options.pathArray;
  61136. var closeArray = options.closeArray;
  61137. var closePath = options.closePath;
  61138. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61139. var instance = options.instance;
  61140. var updatable = options.updatable;
  61141. if (instance) { // existing ribbon instance update
  61142. // positionFunction : ribbon case
  61143. // only pathArray and sideOrientation parameters are taken into account for positions update
  61144. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61145. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61146. var positionFunction = function (positions) {
  61147. var minlg = pathArray[0].length;
  61148. var i = 0;
  61149. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61150. for (var si = 1; si <= ns; si++) {
  61151. for (var p = 0; p < pathArray.length; p++) {
  61152. var path = pathArray[p];
  61153. var l = path.length;
  61154. minlg = (minlg < l) ? minlg : l;
  61155. var j = 0;
  61156. while (j < minlg) {
  61157. positions[i] = path[j].x;
  61158. positions[i + 1] = path[j].y;
  61159. positions[i + 2] = path[j].z;
  61160. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61161. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61162. }
  61163. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61164. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61165. }
  61166. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61167. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61168. }
  61169. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61170. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61171. }
  61172. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61173. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61174. }
  61175. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61176. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61177. }
  61178. j++;
  61179. i += 3;
  61180. }
  61181. if (instance._closePath) {
  61182. positions[i] = path[0].x;
  61183. positions[i + 1] = path[0].y;
  61184. positions[i + 2] = path[0].z;
  61185. i += 3;
  61186. }
  61187. }
  61188. }
  61189. };
  61190. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61191. positionFunction(positions);
  61192. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61193. instance._boundingInfo.update(instance._worldMatrix);
  61194. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61195. if (options.colors) {
  61196. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61197. for (var c = 0; c < options.colors.length; c++) {
  61198. colors[c * 4] = options.colors[c].r;
  61199. colors[c * 4 + 1] = options.colors[c].g;
  61200. colors[c * 4 + 2] = options.colors[c].b;
  61201. colors[c * 4 + 3] = options.colors[c].a;
  61202. }
  61203. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61204. }
  61205. if (options.uvs) {
  61206. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61207. for (var i = 0; i < options.uvs.length; i++) {
  61208. uvs[i * 2] = options.uvs[i].x;
  61209. uvs[i * 2 + 1] = options.uvs[i].y;
  61210. }
  61211. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61212. }
  61213. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61214. var indices = instance.getIndices();
  61215. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61216. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61217. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61218. if (instance._closePath) {
  61219. var indexFirst = 0;
  61220. var indexLast = 0;
  61221. for (var p = 0; p < pathArray.length; p++) {
  61222. indexFirst = instance._idx[p] * 3;
  61223. if (p + 1 < pathArray.length) {
  61224. indexLast = (instance._idx[p + 1] - 1) * 3;
  61225. }
  61226. else {
  61227. indexLast = normals.length - 3;
  61228. }
  61229. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61230. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61231. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61232. normals[indexLast] = normals[indexFirst];
  61233. normals[indexLast + 1] = normals[indexFirst + 1];
  61234. normals[indexLast + 2] = normals[indexFirst + 2];
  61235. }
  61236. }
  61237. if (!(instance.areNormalsFrozen)) {
  61238. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61239. }
  61240. }
  61241. return instance;
  61242. }
  61243. else { // new ribbon creation
  61244. var ribbon = new BABYLON.Mesh(name, scene);
  61245. ribbon._originalBuilderSideOrientation = sideOrientation;
  61246. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61247. if (closePath) {
  61248. ribbon._idx = vertexData._idx;
  61249. }
  61250. ribbon._closePath = closePath;
  61251. ribbon._closeArray = closeArray;
  61252. vertexData.applyToMesh(ribbon, updatable);
  61253. return ribbon;
  61254. }
  61255. };
  61256. /**
  61257. * Creates a cylinder or a cone mesh
  61258. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61259. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61260. * * 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.
  61261. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61262. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61263. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61264. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61265. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61266. * * 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).
  61267. * * 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
  61268. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61269. * * 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
  61270. * * 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.
  61271. * * If `enclose` is false, a ring surface is one element.
  61272. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61273. * * 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
  61274. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61275. * * 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
  61276. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61277. * @param name defines the name of the mesh
  61278. * @param options defines the options used to create the mesh
  61279. * @param scene defines the hosting scene
  61280. * @returns the cylinder mesh
  61281. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61282. */
  61283. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61284. var cylinder = new BABYLON.Mesh(name, scene);
  61285. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61286. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61287. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61288. vertexData.applyToMesh(cylinder, options.updatable);
  61289. return cylinder;
  61290. };
  61291. /**
  61292. * Creates a torus mesh
  61293. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61294. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61295. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61296. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61297. * * 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
  61298. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61299. * @param name defines the name of the mesh
  61300. * @param options defines the options used to create the mesh
  61301. * @param scene defines the hosting scene
  61302. * @returns the torus mesh
  61303. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61304. */
  61305. MeshBuilder.CreateTorus = function (name, options, scene) {
  61306. var torus = new BABYLON.Mesh(name, scene);
  61307. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61308. torus._originalBuilderSideOrientation = options.sideOrientation;
  61309. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61310. vertexData.applyToMesh(torus, options.updatable);
  61311. return torus;
  61312. };
  61313. /**
  61314. * Creates a torus knot mesh
  61315. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61316. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61317. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61318. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61319. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61320. * * 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
  61321. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61322. * @param name defines the name of the mesh
  61323. * @param options defines the options used to create the mesh
  61324. * @param scene defines the hosting scene
  61325. * @returns the torus knot mesh
  61326. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61327. */
  61328. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61329. var torusKnot = new BABYLON.Mesh(name, scene);
  61330. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61331. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61332. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61333. vertexData.applyToMesh(torusKnot, options.updatable);
  61334. return torusKnot;
  61335. };
  61336. /**
  61337. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61338. * * 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
  61339. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61340. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61341. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61342. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61343. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61344. * * 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
  61345. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61346. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61347. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61348. * @param name defines the name of the new line system
  61349. * @param options defines the options used to create the line system
  61350. * @param scene defines the hosting scene
  61351. * @returns a new line system mesh
  61352. */
  61353. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61354. var instance = options.instance;
  61355. var lines = options.lines;
  61356. var colors = options.colors;
  61357. if (instance) { // lines update
  61358. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61359. var vertexColor;
  61360. var lineColors;
  61361. if (colors) {
  61362. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61363. }
  61364. var i = 0;
  61365. var c = 0;
  61366. for (var l = 0; l < lines.length; l++) {
  61367. var points = lines[l];
  61368. for (var p = 0; p < points.length; p++) {
  61369. positions[i] = points[p].x;
  61370. positions[i + 1] = points[p].y;
  61371. positions[i + 2] = points[p].z;
  61372. if (colors && vertexColor) {
  61373. lineColors = colors[l];
  61374. vertexColor[c] = lineColors[p].r;
  61375. vertexColor[c + 1] = lineColors[p].g;
  61376. vertexColor[c + 2] = lineColors[p].b;
  61377. vertexColor[c + 3] = lineColors[p].a;
  61378. c += 4;
  61379. }
  61380. i += 3;
  61381. }
  61382. }
  61383. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61384. if (colors && vertexColor) {
  61385. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61386. }
  61387. return instance;
  61388. }
  61389. // line system creation
  61390. var useVertexColor = (colors) ? true : false;
  61391. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61392. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61393. vertexData.applyToMesh(lineSystem, options.updatable);
  61394. return lineSystem;
  61395. };
  61396. /**
  61397. * Creates a line mesh
  61398. * 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
  61399. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61400. * * The parameter `points` is an array successive Vector3
  61401. * * 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
  61402. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61403. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61404. * * When updating an instance, remember that only point positions can change, not the number of points
  61405. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61406. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61407. * @param name defines the name of the new line system
  61408. * @param options defines the options used to create the line system
  61409. * @param scene defines the hosting scene
  61410. * @returns a new line mesh
  61411. */
  61412. MeshBuilder.CreateLines = function (name, options, scene) {
  61413. if (scene === void 0) { scene = null; }
  61414. var colors = (options.colors) ? [options.colors] : null;
  61415. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61416. return lines;
  61417. };
  61418. /**
  61419. * Creates a dashed line mesh
  61420. * * 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
  61421. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61422. * * The parameter `points` is an array successive Vector3
  61423. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61424. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61425. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61426. * * 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
  61427. * * When updating an instance, remember that only point positions can change, not the number of points
  61428. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61429. * @param name defines the name of the mesh
  61430. * @param options defines the options used to create the mesh
  61431. * @param scene defines the hosting scene
  61432. * @returns the dashed line mesh
  61433. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61434. */
  61435. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61436. if (scene === void 0) { scene = null; }
  61437. var points = options.points;
  61438. var instance = options.instance;
  61439. var gapSize = options.gapSize || 1;
  61440. var dashSize = options.dashSize || 3;
  61441. if (instance) { // dashed lines update
  61442. var positionFunction = function (positions) {
  61443. var curvect = BABYLON.Vector3.Zero();
  61444. var nbSeg = positions.length / 6;
  61445. var lg = 0;
  61446. var nb = 0;
  61447. var shft = 0;
  61448. var dashshft = 0;
  61449. var curshft = 0;
  61450. var p = 0;
  61451. var i = 0;
  61452. var j = 0;
  61453. for (i = 0; i < points.length - 1; i++) {
  61454. points[i + 1].subtractToRef(points[i], curvect);
  61455. lg += curvect.length();
  61456. }
  61457. shft = lg / nbSeg;
  61458. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61459. for (i = 0; i < points.length - 1; i++) {
  61460. points[i + 1].subtractToRef(points[i], curvect);
  61461. nb = Math.floor(curvect.length() / shft);
  61462. curvect.normalize();
  61463. j = 0;
  61464. while (j < nb && p < positions.length) {
  61465. curshft = shft * j;
  61466. positions[p] = points[i].x + curshft * curvect.x;
  61467. positions[p + 1] = points[i].y + curshft * curvect.y;
  61468. positions[p + 2] = points[i].z + curshft * curvect.z;
  61469. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61470. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61471. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61472. p += 6;
  61473. j++;
  61474. }
  61475. }
  61476. while (p < positions.length) {
  61477. positions[p] = points[i].x;
  61478. positions[p + 1] = points[i].y;
  61479. positions[p + 2] = points[i].z;
  61480. p += 3;
  61481. }
  61482. };
  61483. instance.updateMeshPositions(positionFunction, false);
  61484. return instance;
  61485. }
  61486. // dashed lines creation
  61487. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61488. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61489. vertexData.applyToMesh(dashedLines, options.updatable);
  61490. dashedLines.dashSize = dashSize;
  61491. dashedLines.gapSize = gapSize;
  61492. return dashedLines;
  61493. };
  61494. /**
  61495. * 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.
  61496. * * 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.
  61497. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61498. * * 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.
  61499. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61500. * * 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
  61501. * * 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
  61502. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61503. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61504. * * 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
  61505. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61506. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61507. * @param name defines the name of the mesh
  61508. * @param options defines the options used to create the mesh
  61509. * @param scene defines the hosting scene
  61510. * @returns the extruded shape mesh
  61511. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61512. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61513. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61514. */
  61515. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61516. if (scene === void 0) { scene = null; }
  61517. var path = options.path;
  61518. var shape = options.shape;
  61519. var scale = options.scale || 1;
  61520. var rotation = options.rotation || 0;
  61521. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61522. var updatable = options.updatable;
  61523. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61524. var instance = options.instance || null;
  61525. var invertUV = options.invertUV || false;
  61526. 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);
  61527. };
  61528. /**
  61529. * Creates an custom extruded shape mesh.
  61530. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61531. * * 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.
  61532. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61533. * * 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
  61534. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61535. * * 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
  61536. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61537. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61538. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61539. * * 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
  61540. * * 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
  61541. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61542. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61543. * * 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
  61544. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61545. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61546. * @param name defines the name of the mesh
  61547. * @param options defines the options used to create the mesh
  61548. * @param scene defines the hosting scene
  61549. * @returns the custom extruded shape mesh
  61550. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61551. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61552. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61553. */
  61554. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61555. var path = options.path;
  61556. var shape = options.shape;
  61557. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61558. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61559. var ribbonCloseArray = options.ribbonCloseArray || false;
  61560. var ribbonClosePath = options.ribbonClosePath || false;
  61561. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61562. var updatable = options.updatable;
  61563. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61564. var instance = options.instance;
  61565. var invertUV = options.invertUV || false;
  61566. 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);
  61567. };
  61568. /**
  61569. * Creates lathe mesh.
  61570. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61571. * * 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
  61572. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61573. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61574. * * 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
  61575. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61576. * * 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
  61577. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61578. * * 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
  61579. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61580. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61581. * @param name defines the name of the mesh
  61582. * @param options defines the options used to create the mesh
  61583. * @param scene defines the hosting scene
  61584. * @returns the lathe mesh
  61585. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61586. */
  61587. MeshBuilder.CreateLathe = function (name, options, scene) {
  61588. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61589. var closed = (options.closed === undefined) ? true : options.closed;
  61590. var shape = options.shape;
  61591. var radius = options.radius || 1;
  61592. var tessellation = options.tessellation || 64;
  61593. var updatable = options.updatable;
  61594. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61595. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61596. var pi2 = Math.PI * 2;
  61597. var paths = new Array();
  61598. var invertUV = options.invertUV || false;
  61599. var i = 0;
  61600. var p = 0;
  61601. var step = pi2 / tessellation * arc;
  61602. var rotated;
  61603. var path = new Array();
  61604. for (i = 0; i <= tessellation; i++) {
  61605. var path = [];
  61606. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61607. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61608. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61609. }
  61610. for (p = 0; p < shape.length; p++) {
  61611. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61612. path.push(rotated);
  61613. }
  61614. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61615. 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));
  61616. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61617. }
  61618. paths.push(path);
  61619. }
  61620. // lathe ribbon
  61621. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61622. return lathe;
  61623. };
  61624. /**
  61625. * Creates a plane mesh
  61626. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61627. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61628. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61629. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61630. * * 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
  61631. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61632. * @param name defines the name of the mesh
  61633. * @param options defines the options used to create the mesh
  61634. * @param scene defines the hosting scene
  61635. * @returns the plane mesh
  61636. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61637. */
  61638. MeshBuilder.CreatePlane = function (name, options, scene) {
  61639. var plane = new BABYLON.Mesh(name, scene);
  61640. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61641. plane._originalBuilderSideOrientation = options.sideOrientation;
  61642. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61643. vertexData.applyToMesh(plane, options.updatable);
  61644. if (options.sourcePlane) {
  61645. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61646. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61647. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61648. plane.rotate(vectorProduct, product);
  61649. }
  61650. return plane;
  61651. };
  61652. /**
  61653. * Creates a ground mesh
  61654. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61655. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61656. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61657. * @param name defines the name of the mesh
  61658. * @param options defines the options used to create the mesh
  61659. * @param scene defines the hosting scene
  61660. * @returns the ground mesh
  61661. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61662. */
  61663. MeshBuilder.CreateGround = function (name, options, scene) {
  61664. var ground = new BABYLON.GroundMesh(name, scene);
  61665. ground._setReady(false);
  61666. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61667. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61668. ground._width = options.width || 1;
  61669. ground._height = options.height || 1;
  61670. ground._maxX = ground._width / 2;
  61671. ground._maxZ = ground._height / 2;
  61672. ground._minX = -ground._maxX;
  61673. ground._minZ = -ground._maxZ;
  61674. var vertexData = BABYLON.VertexData.CreateGround(options);
  61675. vertexData.applyToMesh(ground, options.updatable);
  61676. ground._setReady(true);
  61677. return ground;
  61678. };
  61679. /**
  61680. * Creates a tiled ground mesh
  61681. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61682. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61683. * * 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
  61684. * * 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
  61685. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61686. * @param name defines the name of the mesh
  61687. * @param options defines the options used to create the mesh
  61688. * @param scene defines the hosting scene
  61689. * @returns the tiled ground mesh
  61690. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61691. */
  61692. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61693. var tiledGround = new BABYLON.Mesh(name, scene);
  61694. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61695. vertexData.applyToMesh(tiledGround, options.updatable);
  61696. return tiledGround;
  61697. };
  61698. /**
  61699. * Creates a ground mesh from a height map
  61700. * * The parameter `url` sets the URL of the height map image resource.
  61701. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61702. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61703. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61704. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61705. * * 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.
  61706. * * 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).
  61707. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61708. * @param name defines the name of the mesh
  61709. * @param url defines the url to the height map
  61710. * @param options defines the options used to create the mesh
  61711. * @param scene defines the hosting scene
  61712. * @returns the ground mesh
  61713. * @see http://doc.babylonjs.com/babylon101/height_map
  61714. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61715. */
  61716. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61717. var width = options.width || 10.0;
  61718. var height = options.height || 10.0;
  61719. var subdivisions = options.subdivisions || 1 | 0;
  61720. var minHeight = options.minHeight || 0.0;
  61721. var maxHeight = options.maxHeight || 1.0;
  61722. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61723. var updatable = options.updatable;
  61724. var onReady = options.onReady;
  61725. var ground = new BABYLON.GroundMesh(name, scene);
  61726. ground._subdivisionsX = subdivisions;
  61727. ground._subdivisionsY = subdivisions;
  61728. ground._width = width;
  61729. ground._height = height;
  61730. ground._maxX = ground._width / 2.0;
  61731. ground._maxZ = ground._height / 2.0;
  61732. ground._minX = -ground._maxX;
  61733. ground._minZ = -ground._maxZ;
  61734. ground._setReady(false);
  61735. var onload = function (img) {
  61736. // Getting height map data
  61737. var canvas = document.createElement("canvas");
  61738. var context = canvas.getContext("2d");
  61739. if (!context) {
  61740. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61741. }
  61742. if (scene.isDisposed) {
  61743. return;
  61744. }
  61745. var bufferWidth = img.width;
  61746. var bufferHeight = img.height;
  61747. canvas.width = bufferWidth;
  61748. canvas.height = bufferHeight;
  61749. context.drawImage(img, 0, 0);
  61750. // Create VertexData from map data
  61751. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61752. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61753. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61754. width: width, height: height,
  61755. subdivisions: subdivisions,
  61756. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61757. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61758. });
  61759. vertexData.applyToMesh(ground, updatable);
  61760. //execute ready callback, if set
  61761. if (onReady) {
  61762. onReady(ground);
  61763. }
  61764. ground._setReady(true);
  61765. };
  61766. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61767. return ground;
  61768. };
  61769. /**
  61770. * Creates a polygon mesh
  61771. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61772. * * 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
  61773. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61774. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61775. * * 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)
  61776. * * Remember you can only change the shape positions, not their number when updating a polygon
  61777. * @param name defines the name of the mesh
  61778. * @param options defines the options used to create the mesh
  61779. * @param scene defines the hosting scene
  61780. * @returns the polygon mesh
  61781. */
  61782. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61783. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61784. var shape = options.shape;
  61785. var holes = options.holes || [];
  61786. var depth = options.depth || 0;
  61787. var contours = [];
  61788. var hole = [];
  61789. for (var i = 0; i < shape.length; i++) {
  61790. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61791. }
  61792. var epsilon = 0.00000001;
  61793. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61794. contours.pop();
  61795. }
  61796. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61797. for (var hNb = 0; hNb < holes.length; hNb++) {
  61798. hole = [];
  61799. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61800. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61801. }
  61802. polygonTriangulation.addHole(hole);
  61803. }
  61804. var polygon = polygonTriangulation.build(options.updatable, depth);
  61805. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61806. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61807. vertexData.applyToMesh(polygon, options.updatable);
  61808. return polygon;
  61809. };
  61810. ;
  61811. /**
  61812. * Creates an extruded polygon mesh, with depth in the Y direction.
  61813. * * 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)
  61814. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61815. * @param name defines the name of the mesh
  61816. * @param options defines the options used to create the mesh
  61817. * @param scene defines the hosting scene
  61818. * @returns the polygon mesh
  61819. */
  61820. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61821. return MeshBuilder.CreatePolygon(name, options, scene);
  61822. };
  61823. ;
  61824. /**
  61825. * Creates a tube mesh.
  61826. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61827. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61828. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61829. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61830. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61831. * * 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)
  61832. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61833. * * 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
  61834. * * 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
  61835. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61836. * * 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
  61837. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61838. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61839. * @param name defines the name of the mesh
  61840. * @param options defines the options used to create the mesh
  61841. * @param scene defines the hosting scene
  61842. * @returns the tube mesh
  61843. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61844. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61845. */
  61846. MeshBuilder.CreateTube = function (name, options, scene) {
  61847. var path = options.path;
  61848. var instance = options.instance;
  61849. var radius = 1.0;
  61850. if (instance) {
  61851. radius = instance.radius;
  61852. }
  61853. if (options.radius !== undefined) {
  61854. radius = options.radius;
  61855. }
  61856. ;
  61857. var tessellation = options.tessellation || 64 | 0;
  61858. var radiusFunction = options.radiusFunction || null;
  61859. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61860. var invertUV = options.invertUV || false;
  61861. var updatable = options.updatable;
  61862. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61863. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61864. // tube geometry
  61865. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61866. var tangents = path3D.getTangents();
  61867. var normals = path3D.getNormals();
  61868. var distances = path3D.getDistances();
  61869. var pi2 = Math.PI * 2;
  61870. var step = pi2 / tessellation * arc;
  61871. var returnRadius = function () { return radius; };
  61872. var radiusFunctionFinal = radiusFunction || returnRadius;
  61873. var circlePath;
  61874. var rad;
  61875. var normal;
  61876. var rotated;
  61877. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61878. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61879. for (var i = 0; i < path.length; i++) {
  61880. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61881. circlePath = Array(); // current circle array
  61882. normal = normals[i]; // current normal
  61883. for (var t = 0; t < tessellation; t++) {
  61884. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61885. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61886. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61887. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61888. circlePath[t] = rotated;
  61889. }
  61890. circlePaths[index] = circlePath;
  61891. index++;
  61892. }
  61893. // cap
  61894. var capPath = function (nbPoints, pathIndex) {
  61895. var pointCap = Array();
  61896. for (var i = 0; i < nbPoints; i++) {
  61897. pointCap.push(path[pathIndex]);
  61898. }
  61899. return pointCap;
  61900. };
  61901. switch (cap) {
  61902. case BABYLON.Mesh.NO_CAP:
  61903. break;
  61904. case BABYLON.Mesh.CAP_START:
  61905. circlePaths[0] = capPath(tessellation, 0);
  61906. circlePaths[1] = circlePaths[2].slice(0);
  61907. break;
  61908. case BABYLON.Mesh.CAP_END:
  61909. circlePaths[index] = circlePaths[index - 1].slice(0);
  61910. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61911. break;
  61912. case BABYLON.Mesh.CAP_ALL:
  61913. circlePaths[0] = capPath(tessellation, 0);
  61914. circlePaths[1] = circlePaths[2].slice(0);
  61915. circlePaths[index] = circlePaths[index - 1].slice(0);
  61916. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61917. break;
  61918. default:
  61919. break;
  61920. }
  61921. return circlePaths;
  61922. };
  61923. var path3D;
  61924. var pathArray;
  61925. if (instance) { // tube update
  61926. var arc = options.arc || instance.arc;
  61927. path3D = (instance.path3D).update(path);
  61928. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61929. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61930. instance.path3D = path3D;
  61931. instance.pathArray = pathArray;
  61932. instance.arc = arc;
  61933. instance.radius = radius;
  61934. return instance;
  61935. }
  61936. // tube creation
  61937. path3D = new BABYLON.Path3D(path);
  61938. var newPathArray = new Array();
  61939. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61940. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61941. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61942. tube.pathArray = pathArray;
  61943. tube.path3D = path3D;
  61944. tube.tessellation = tessellation;
  61945. tube.cap = cap;
  61946. tube.arc = options.arc;
  61947. tube.radius = radius;
  61948. return tube;
  61949. };
  61950. /**
  61951. * Creates a polyhedron mesh
  61952. * * 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
  61953. * * The parameter `size` (positive float, default 1) sets the polygon size
  61954. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61955. * * 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`
  61956. * * 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
  61957. * * 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)`)
  61958. * * 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
  61959. * * 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
  61960. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61961. * * 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
  61962. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61963. * @param name defines the name of the mesh
  61964. * @param options defines the options used to create the mesh
  61965. * @param scene defines the hosting scene
  61966. * @returns the polyhedron mesh
  61967. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61968. */
  61969. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61970. var polyhedron = new BABYLON.Mesh(name, scene);
  61971. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61972. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61973. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61974. vertexData.applyToMesh(polyhedron, options.updatable);
  61975. return polyhedron;
  61976. };
  61977. /**
  61978. * Creates a decal mesh.
  61979. * 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
  61980. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61981. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61982. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61983. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61984. * @param name defines the name of the mesh
  61985. * @param sourceMesh defines the mesh where the decal must be applied
  61986. * @param options defines the options used to create the mesh
  61987. * @param scene defines the hosting scene
  61988. * @returns the decal mesh
  61989. * @see http://doc.babylonjs.com/how_to/decals
  61990. */
  61991. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61992. var indices = sourceMesh.getIndices();
  61993. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61994. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61995. var position = options.position || BABYLON.Vector3.Zero();
  61996. var normal = options.normal || BABYLON.Vector3.Up();
  61997. var size = options.size || BABYLON.Vector3.One();
  61998. var angle = options.angle || 0;
  61999. // Getting correct rotation
  62000. if (!normal) {
  62001. var target = new BABYLON.Vector3(0, 0, 1);
  62002. var camera = sourceMesh.getScene().activeCamera;
  62003. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  62004. normal = camera.globalPosition.subtract(cameraWorldTarget);
  62005. }
  62006. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  62007. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  62008. var pitch = Math.atan2(normal.y, len);
  62009. // Matrix
  62010. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  62011. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  62012. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  62013. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  62014. var vertexData = new BABYLON.VertexData();
  62015. vertexData.indices = [];
  62016. vertexData.positions = [];
  62017. vertexData.normals = [];
  62018. vertexData.uvs = [];
  62019. var currentVertexDataIndex = 0;
  62020. var extractDecalVector3 = function (indexId) {
  62021. var result = new BABYLON.PositionNormalVertex();
  62022. if (!indices || !positions || !normals) {
  62023. return result;
  62024. }
  62025. var vertexId = indices[indexId];
  62026. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  62027. // Send vector to decal local world
  62028. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  62029. // Get normal
  62030. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  62031. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  62032. return result;
  62033. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  62034. var clip = function (vertices, axis) {
  62035. if (vertices.length === 0) {
  62036. return vertices;
  62037. }
  62038. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  62039. var clipVertices = function (v0, v1) {
  62040. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  62041. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  62042. };
  62043. var result = new Array();
  62044. for (var index = 0; index < vertices.length; index += 3) {
  62045. var v1Out;
  62046. var v2Out;
  62047. var v3Out;
  62048. var total = 0;
  62049. var nV1 = null;
  62050. var nV2 = null;
  62051. var nV3 = null;
  62052. var nV4 = null;
  62053. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  62054. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  62055. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  62056. v1Out = d1 > 0;
  62057. v2Out = d2 > 0;
  62058. v3Out = d3 > 0;
  62059. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  62060. switch (total) {
  62061. case 0:
  62062. result.push(vertices[index]);
  62063. result.push(vertices[index + 1]);
  62064. result.push(vertices[index + 2]);
  62065. break;
  62066. case 1:
  62067. if (v1Out) {
  62068. nV1 = vertices[index + 1];
  62069. nV2 = vertices[index + 2];
  62070. nV3 = clipVertices(vertices[index], nV1);
  62071. nV4 = clipVertices(vertices[index], nV2);
  62072. }
  62073. if (v2Out) {
  62074. nV1 = vertices[index];
  62075. nV2 = vertices[index + 2];
  62076. nV3 = clipVertices(vertices[index + 1], nV1);
  62077. nV4 = clipVertices(vertices[index + 1], nV2);
  62078. result.push(nV3);
  62079. result.push(nV2.clone());
  62080. result.push(nV1.clone());
  62081. result.push(nV2.clone());
  62082. result.push(nV3.clone());
  62083. result.push(nV4);
  62084. break;
  62085. }
  62086. if (v3Out) {
  62087. nV1 = vertices[index];
  62088. nV2 = vertices[index + 1];
  62089. nV3 = clipVertices(vertices[index + 2], nV1);
  62090. nV4 = clipVertices(vertices[index + 2], nV2);
  62091. }
  62092. if (nV1 && nV2 && nV3 && nV4) {
  62093. result.push(nV1.clone());
  62094. result.push(nV2.clone());
  62095. result.push(nV3);
  62096. result.push(nV4);
  62097. result.push(nV3.clone());
  62098. result.push(nV2.clone());
  62099. }
  62100. break;
  62101. case 2:
  62102. if (!v1Out) {
  62103. nV1 = vertices[index].clone();
  62104. nV2 = clipVertices(nV1, vertices[index + 1]);
  62105. nV3 = clipVertices(nV1, vertices[index + 2]);
  62106. result.push(nV1);
  62107. result.push(nV2);
  62108. result.push(nV3);
  62109. }
  62110. if (!v2Out) {
  62111. nV1 = vertices[index + 1].clone();
  62112. nV2 = clipVertices(nV1, vertices[index + 2]);
  62113. nV3 = clipVertices(nV1, vertices[index]);
  62114. result.push(nV1);
  62115. result.push(nV2);
  62116. result.push(nV3);
  62117. }
  62118. if (!v3Out) {
  62119. nV1 = vertices[index + 2].clone();
  62120. nV2 = clipVertices(nV1, vertices[index]);
  62121. nV3 = clipVertices(nV1, vertices[index + 1]);
  62122. result.push(nV1);
  62123. result.push(nV2);
  62124. result.push(nV3);
  62125. }
  62126. break;
  62127. case 3:
  62128. break;
  62129. }
  62130. }
  62131. return result;
  62132. };
  62133. for (var index = 0; index < indices.length; index += 3) {
  62134. var faceVertices = new Array();
  62135. faceVertices.push(extractDecalVector3(index));
  62136. faceVertices.push(extractDecalVector3(index + 1));
  62137. faceVertices.push(extractDecalVector3(index + 2));
  62138. // Clip
  62139. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62140. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62141. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62142. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62143. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62144. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62145. if (faceVertices.length === 0) {
  62146. continue;
  62147. }
  62148. // Add UVs and get back to world
  62149. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62150. var vertex = faceVertices[vIndex];
  62151. //TODO check for Int32Array | Uint32Array | Uint16Array
  62152. vertexData.indices.push(currentVertexDataIndex);
  62153. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62154. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62155. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62156. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62157. currentVertexDataIndex++;
  62158. }
  62159. }
  62160. // Return mesh
  62161. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62162. vertexData.applyToMesh(decal);
  62163. decal.position = position.clone();
  62164. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62165. return decal;
  62166. };
  62167. // Privates
  62168. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62169. // extrusion geometry
  62170. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62171. var tangents = path3D.getTangents();
  62172. var normals = path3D.getNormals();
  62173. var binormals = path3D.getBinormals();
  62174. var distances = path3D.getDistances();
  62175. var angle = 0;
  62176. var returnScale = function () { return scale !== null ? scale : 1; };
  62177. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62178. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62179. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62180. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62181. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62182. for (var i = 0; i < curve.length; i++) {
  62183. var shapePath = new Array();
  62184. var angleStep = rotate(i, distances[i]);
  62185. var scaleRatio = scl(i, distances[i]);
  62186. for (var p = 0; p < shape.length; p++) {
  62187. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62188. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62189. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62190. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62191. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62192. shapePath[p] = rotated;
  62193. }
  62194. shapePaths[index] = shapePath;
  62195. angle += angleStep;
  62196. index++;
  62197. }
  62198. // cap
  62199. var capPath = function (shapePath) {
  62200. var pointCap = Array();
  62201. var barycenter = BABYLON.Vector3.Zero();
  62202. var i;
  62203. for (i = 0; i < shapePath.length; i++) {
  62204. barycenter.addInPlace(shapePath[i]);
  62205. }
  62206. barycenter.scaleInPlace(1.0 / shapePath.length);
  62207. for (i = 0; i < shapePath.length; i++) {
  62208. pointCap.push(barycenter);
  62209. }
  62210. return pointCap;
  62211. };
  62212. switch (cap) {
  62213. case BABYLON.Mesh.NO_CAP:
  62214. break;
  62215. case BABYLON.Mesh.CAP_START:
  62216. shapePaths[0] = capPath(shapePaths[2]);
  62217. shapePaths[1] = shapePaths[2];
  62218. break;
  62219. case BABYLON.Mesh.CAP_END:
  62220. shapePaths[index] = shapePaths[index - 1];
  62221. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62222. break;
  62223. case BABYLON.Mesh.CAP_ALL:
  62224. shapePaths[0] = capPath(shapePaths[2]);
  62225. shapePaths[1] = shapePaths[2];
  62226. shapePaths[index] = shapePaths[index - 1];
  62227. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62228. break;
  62229. default:
  62230. break;
  62231. }
  62232. return shapePaths;
  62233. };
  62234. var path3D;
  62235. var pathArray;
  62236. if (instance) { // instance update
  62237. path3D = (instance.path3D).update(curve);
  62238. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62239. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62240. return instance;
  62241. }
  62242. // extruded shape creation
  62243. path3D = new BABYLON.Path3D(curve);
  62244. var newShapePaths = new Array();
  62245. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62246. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62247. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62248. extrudedGeneric.pathArray = pathArray;
  62249. extrudedGeneric.path3D = path3D;
  62250. extrudedGeneric.cap = cap;
  62251. return extrudedGeneric;
  62252. };
  62253. return MeshBuilder;
  62254. }());
  62255. BABYLON.MeshBuilder = MeshBuilder;
  62256. })(BABYLON || (BABYLON = {}));
  62257. //# sourceMappingURL=babylon.meshBuilder.js.map
  62258. var BABYLON;
  62259. (function (BABYLON) {
  62260. /**
  62261. * Draco compression (https://google.github.io/draco/)
  62262. *
  62263. * This class wraps the Draco module.
  62264. *
  62265. * **Encoder**
  62266. *
  62267. * The encoder is not currently implemented.
  62268. *
  62269. * **Decoder**
  62270. *
  62271. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62272. *
  62273. * To update the configuration, use the following code:
  62274. * ```javascript
  62275. * BABYLON.DracoCompression.Configuration = {
  62276. * decoder: {
  62277. * wasmUrl: "<url to the WebAssembly library>",
  62278. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62279. * fallbackUrl: "<url to the fallback JavaScript library>",
  62280. * }
  62281. * };
  62282. * ```
  62283. *
  62284. * 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.
  62285. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62286. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62287. *
  62288. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62289. * ```javascript
  62290. * var dracoCompression = new BABYLON.DracoCompression();
  62291. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62292. * [BABYLON.VertexBuffer.PositionKind]: 0
  62293. * });
  62294. * ```
  62295. *
  62296. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62297. */
  62298. var DracoCompression = /** @class */ (function () {
  62299. /**
  62300. * Constructor
  62301. */
  62302. function DracoCompression() {
  62303. }
  62304. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62305. /**
  62306. * Returns true if the decoder is available.
  62307. */
  62308. get: function () {
  62309. if (typeof DracoDecoderModule !== "undefined") {
  62310. return true;
  62311. }
  62312. var decoder = DracoCompression.Configuration.decoder;
  62313. if (decoder) {
  62314. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62315. return true;
  62316. }
  62317. if (decoder.fallbackUrl) {
  62318. return true;
  62319. }
  62320. }
  62321. return false;
  62322. },
  62323. enumerable: true,
  62324. configurable: true
  62325. });
  62326. /**
  62327. * Stop all async operations and release resources.
  62328. */
  62329. DracoCompression.prototype.dispose = function () {
  62330. };
  62331. /**
  62332. * Decode Draco compressed mesh data to vertex data.
  62333. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62334. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62335. * @returns A promise that resolves with the decoded vertex data
  62336. */
  62337. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62338. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62339. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62340. var module = wrappedModule.module;
  62341. var vertexData = new BABYLON.VertexData();
  62342. var buffer = new module.DecoderBuffer();
  62343. buffer.Init(dataView, dataView.byteLength);
  62344. var decoder = new module.Decoder();
  62345. var geometry;
  62346. var status;
  62347. try {
  62348. var type = decoder.GetEncodedGeometryType(buffer);
  62349. switch (type) {
  62350. case module.TRIANGULAR_MESH:
  62351. geometry = new module.Mesh();
  62352. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62353. break;
  62354. case module.POINT_CLOUD:
  62355. geometry = new module.PointCloud();
  62356. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62357. break;
  62358. default:
  62359. throw new Error("Invalid geometry type " + type);
  62360. }
  62361. if (!status.ok() || !geometry.ptr) {
  62362. throw new Error(status.error_msg());
  62363. }
  62364. var numPoints = geometry.num_points();
  62365. if (type === module.TRIANGULAR_MESH) {
  62366. var numFaces = geometry.num_faces();
  62367. var faceIndices = new module.DracoInt32Array();
  62368. try {
  62369. var indices = new Uint32Array(numFaces * 3);
  62370. for (var i = 0; i < numFaces; i++) {
  62371. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62372. var offset = i * 3;
  62373. indices[offset + 0] = faceIndices.GetValue(0);
  62374. indices[offset + 1] = faceIndices.GetValue(1);
  62375. indices[offset + 2] = faceIndices.GetValue(2);
  62376. }
  62377. vertexData.indices = indices;
  62378. }
  62379. finally {
  62380. module.destroy(faceIndices);
  62381. }
  62382. }
  62383. for (var kind in attributes) {
  62384. var uniqueId = attributes[kind];
  62385. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62386. var dracoData = new module.DracoFloat32Array();
  62387. try {
  62388. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62389. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62390. for (var i = 0; i < babylonData.length; i++) {
  62391. babylonData[i] = dracoData.GetValue(i);
  62392. }
  62393. vertexData.set(babylonData, kind);
  62394. }
  62395. finally {
  62396. module.destroy(dracoData);
  62397. }
  62398. }
  62399. }
  62400. finally {
  62401. if (geometry) {
  62402. module.destroy(geometry);
  62403. }
  62404. module.destroy(decoder);
  62405. module.destroy(buffer);
  62406. }
  62407. return vertexData;
  62408. });
  62409. };
  62410. DracoCompression._GetDecoderModule = function () {
  62411. if (!DracoCompression._DecoderModulePromise) {
  62412. var promise = null;
  62413. var config_1 = {};
  62414. if (typeof DracoDecoderModule !== "undefined") {
  62415. promise = Promise.resolve();
  62416. }
  62417. else {
  62418. var decoder = DracoCompression.Configuration.decoder;
  62419. if (decoder) {
  62420. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62421. promise = Promise.all([
  62422. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62423. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62424. config_1.wasmBinary = data;
  62425. })
  62426. ]);
  62427. }
  62428. else if (decoder.fallbackUrl) {
  62429. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62430. }
  62431. }
  62432. }
  62433. if (!promise) {
  62434. throw new Error("Draco decoder module is not available");
  62435. }
  62436. DracoCompression._DecoderModulePromise = promise.then(function () {
  62437. return new Promise(function (resolve) {
  62438. config_1.onModuleLoaded = function (decoderModule) {
  62439. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62440. resolve({ module: decoderModule });
  62441. };
  62442. DracoDecoderModule(config_1);
  62443. });
  62444. });
  62445. }
  62446. return DracoCompression._DecoderModulePromise;
  62447. };
  62448. DracoCompression._LoadScriptAsync = function (url) {
  62449. return new Promise(function (resolve, reject) {
  62450. BABYLON.Tools.LoadScript(url, function () {
  62451. resolve();
  62452. }, function (message) {
  62453. reject(new Error(message));
  62454. });
  62455. });
  62456. };
  62457. DracoCompression._LoadFileAsync = function (url) {
  62458. return new Promise(function (resolve, reject) {
  62459. BABYLON.Tools.LoadFile(url, function (data) {
  62460. resolve(data);
  62461. }, undefined, undefined, true, function (request, exception) {
  62462. reject(exception);
  62463. });
  62464. });
  62465. };
  62466. /**
  62467. * The configuration. Defaults to the following urls:
  62468. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62469. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62470. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62471. */
  62472. DracoCompression.Configuration = {
  62473. decoder: {
  62474. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62475. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62476. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62477. }
  62478. };
  62479. return DracoCompression;
  62480. }());
  62481. BABYLON.DracoCompression = DracoCompression;
  62482. })(BABYLON || (BABYLON = {}));
  62483. //# sourceMappingURL=babylon.dracoCompression.js.map
  62484. var BABYLON;
  62485. (function (BABYLON) {
  62486. var AudioEngine = /** @class */ (function () {
  62487. function AudioEngine() {
  62488. this._audioContext = null;
  62489. this._audioContextInitialized = false;
  62490. this.canUseWebAudio = false;
  62491. this.WarnedWebAudioUnsupported = false;
  62492. this.unlocked = false;
  62493. this.isMP3supported = false;
  62494. this.isOGGsupported = false;
  62495. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62496. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62497. this.canUseWebAudio = true;
  62498. }
  62499. var audioElem = document.createElement('audio');
  62500. try {
  62501. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62502. this.isMP3supported = true;
  62503. }
  62504. }
  62505. catch (e) {
  62506. // protect error during capability check.
  62507. }
  62508. try {
  62509. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62510. this.isOGGsupported = true;
  62511. }
  62512. }
  62513. catch (e) {
  62514. // protect error during capability check.
  62515. }
  62516. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62517. this._unlockiOSaudio();
  62518. }
  62519. else {
  62520. this.unlocked = true;
  62521. }
  62522. }
  62523. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62524. get: function () {
  62525. if (!this._audioContextInitialized) {
  62526. this._initializeAudioContext();
  62527. }
  62528. return this._audioContext;
  62529. },
  62530. enumerable: true,
  62531. configurable: true
  62532. });
  62533. AudioEngine.prototype._unlockiOSaudio = function () {
  62534. var _this = this;
  62535. var unlockaudio = function () {
  62536. if (!_this.audioContext) {
  62537. return;
  62538. }
  62539. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62540. var source = _this.audioContext.createBufferSource();
  62541. source.buffer = buffer;
  62542. source.connect(_this.audioContext.destination);
  62543. source.start(0);
  62544. setTimeout(function () {
  62545. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62546. _this.unlocked = true;
  62547. window.removeEventListener('touchend', unlockaudio, false);
  62548. if (_this.onAudioUnlocked) {
  62549. _this.onAudioUnlocked();
  62550. }
  62551. }
  62552. }, 0);
  62553. };
  62554. window.addEventListener('touchend', unlockaudio, false);
  62555. };
  62556. AudioEngine.prototype._initializeAudioContext = function () {
  62557. try {
  62558. if (this.canUseWebAudio) {
  62559. this._audioContext = new AudioContext();
  62560. // create a global volume gain node
  62561. this.masterGain = this._audioContext.createGain();
  62562. this.masterGain.gain.value = 1;
  62563. this.masterGain.connect(this._audioContext.destination);
  62564. this._audioContextInitialized = true;
  62565. }
  62566. }
  62567. catch (e) {
  62568. this.canUseWebAudio = false;
  62569. BABYLON.Tools.Error("Web Audio: " + e.message);
  62570. }
  62571. };
  62572. AudioEngine.prototype.dispose = function () {
  62573. if (this.canUseWebAudio && this._audioContextInitialized) {
  62574. if (this._connectedAnalyser && this._audioContext) {
  62575. this._connectedAnalyser.stopDebugCanvas();
  62576. this._connectedAnalyser.dispose();
  62577. this.masterGain.disconnect();
  62578. this.masterGain.connect(this._audioContext.destination);
  62579. this._connectedAnalyser = null;
  62580. }
  62581. this.masterGain.gain.value = 1;
  62582. }
  62583. this.WarnedWebAudioUnsupported = false;
  62584. };
  62585. AudioEngine.prototype.getGlobalVolume = function () {
  62586. if (this.canUseWebAudio && this._audioContextInitialized) {
  62587. return this.masterGain.gain.value;
  62588. }
  62589. else {
  62590. return -1;
  62591. }
  62592. };
  62593. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62594. if (this.canUseWebAudio && this._audioContextInitialized) {
  62595. this.masterGain.gain.value = newVolume;
  62596. }
  62597. };
  62598. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62599. if (this._connectedAnalyser) {
  62600. this._connectedAnalyser.stopDebugCanvas();
  62601. }
  62602. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62603. this._connectedAnalyser = analyser;
  62604. this.masterGain.disconnect();
  62605. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62606. }
  62607. };
  62608. return AudioEngine;
  62609. }());
  62610. BABYLON.AudioEngine = AudioEngine;
  62611. })(BABYLON || (BABYLON = {}));
  62612. //# sourceMappingURL=babylon.audioEngine.js.map
  62613. var BABYLON;
  62614. (function (BABYLON) {
  62615. var Sound = /** @class */ (function () {
  62616. /**
  62617. * Create a sound and attach it to a scene
  62618. * @param name Name of your sound
  62619. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62620. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62621. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62622. */
  62623. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62624. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62625. var _this = this;
  62626. this.autoplay = false;
  62627. this.loop = false;
  62628. this.useCustomAttenuation = false;
  62629. this.spatialSound = false;
  62630. this.refDistance = 1;
  62631. this.rolloffFactor = 1;
  62632. this.maxDistance = 100;
  62633. this.distanceModel = "linear";
  62634. this._panningModel = "equalpower";
  62635. this._playbackRate = 1;
  62636. this._streaming = false;
  62637. this._startTime = 0;
  62638. this._startOffset = 0;
  62639. this._position = BABYLON.Vector3.Zero();
  62640. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62641. this._volume = 1;
  62642. this._isReadyToPlay = false;
  62643. this.isPlaying = false;
  62644. this.isPaused = false;
  62645. this._isDirectional = false;
  62646. // Used if you'd like to create a directional sound.
  62647. // If not set, the sound will be omnidirectional
  62648. this._coneInnerAngle = 360;
  62649. this._coneOuterAngle = 360;
  62650. this._coneOuterGain = 0;
  62651. this._isOutputConnected = false;
  62652. this._urlType = "Unknown";
  62653. this.name = name;
  62654. this._scene = scene;
  62655. this._readyToPlayCallback = readyToPlayCallback;
  62656. // Default custom attenuation function is a linear attenuation
  62657. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62658. if (currentDistance < maxDistance) {
  62659. return currentVolume * (1 - currentDistance / maxDistance);
  62660. }
  62661. else {
  62662. return 0;
  62663. }
  62664. };
  62665. if (options) {
  62666. this.autoplay = options.autoplay || false;
  62667. this.loop = options.loop || false;
  62668. // if volume === 0, we need another way to check this option
  62669. if (options.volume !== undefined) {
  62670. this._volume = options.volume;
  62671. }
  62672. this.spatialSound = options.spatialSound || false;
  62673. this.maxDistance = options.maxDistance || 100;
  62674. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62675. this.rolloffFactor = options.rolloffFactor || 1;
  62676. this.refDistance = options.refDistance || 1;
  62677. this.distanceModel = options.distanceModel || "linear";
  62678. this._playbackRate = options.playbackRate || 1;
  62679. this._streaming = options.streaming || false;
  62680. }
  62681. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62682. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62683. this._soundGain.gain.value = this._volume;
  62684. this._inputAudioNode = this._soundGain;
  62685. this._ouputAudioNode = this._soundGain;
  62686. if (this.spatialSound) {
  62687. this._createSpatialParameters();
  62688. }
  62689. this._scene.mainSoundTrack.AddSound(this);
  62690. var validParameter = true;
  62691. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62692. if (urlOrArrayBuffer) {
  62693. try {
  62694. if (typeof (urlOrArrayBuffer) === "string")
  62695. this._urlType = "String";
  62696. if (Array.isArray(urlOrArrayBuffer))
  62697. this._urlType = "Array";
  62698. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62699. this._urlType = "ArrayBuffer";
  62700. var urls = [];
  62701. var codecSupportedFound = false;
  62702. switch (this._urlType) {
  62703. case "ArrayBuffer":
  62704. if (urlOrArrayBuffer.byteLength > 0) {
  62705. codecSupportedFound = true;
  62706. this._soundLoaded(urlOrArrayBuffer);
  62707. }
  62708. break;
  62709. case "String":
  62710. urls.push(urlOrArrayBuffer);
  62711. case "Array":
  62712. if (urls.length === 0)
  62713. urls = urlOrArrayBuffer;
  62714. // If we found a supported format, we load it immediately and stop the loop
  62715. for (var i = 0; i < urls.length; i++) {
  62716. var url = urls[i];
  62717. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62718. codecSupportedFound = true;
  62719. }
  62720. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62721. codecSupportedFound = true;
  62722. }
  62723. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62724. codecSupportedFound = true;
  62725. }
  62726. if (url.indexOf("blob:") !== -1) {
  62727. codecSupportedFound = true;
  62728. }
  62729. if (codecSupportedFound) {
  62730. // Loading sound using XHR2
  62731. if (!this._streaming) {
  62732. this._scene._loadFile(url, function (data) {
  62733. _this._soundLoaded(data);
  62734. }, undefined, true, true, function (exception) {
  62735. if (exception) {
  62736. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62737. }
  62738. BABYLON.Tools.Error("Sound creation aborted.");
  62739. _this._scene.mainSoundTrack.RemoveSound(_this);
  62740. });
  62741. }
  62742. // Streaming sound using HTML5 Audio tag
  62743. else {
  62744. this._htmlAudioElement = new Audio(url);
  62745. this._htmlAudioElement.controls = false;
  62746. this._htmlAudioElement.loop = this.loop;
  62747. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62748. this._htmlAudioElement.preload = "auto";
  62749. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62750. _this._isReadyToPlay = true;
  62751. if (_this.autoplay) {
  62752. _this.play();
  62753. }
  62754. if (_this._readyToPlayCallback) {
  62755. _this._readyToPlayCallback();
  62756. }
  62757. });
  62758. document.body.appendChild(this._htmlAudioElement);
  62759. }
  62760. break;
  62761. }
  62762. }
  62763. break;
  62764. default:
  62765. validParameter = false;
  62766. break;
  62767. }
  62768. if (!validParameter) {
  62769. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62770. }
  62771. else {
  62772. if (!codecSupportedFound) {
  62773. this._isReadyToPlay = true;
  62774. // Simulating a ready to play event to avoid breaking code path
  62775. if (this._readyToPlayCallback) {
  62776. window.setTimeout(function () {
  62777. if (_this._readyToPlayCallback) {
  62778. _this._readyToPlayCallback();
  62779. }
  62780. }, 1000);
  62781. }
  62782. }
  62783. }
  62784. }
  62785. catch (ex) {
  62786. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62787. this._scene.mainSoundTrack.RemoveSound(this);
  62788. }
  62789. }
  62790. }
  62791. else {
  62792. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62793. this._scene.mainSoundTrack.AddSound(this);
  62794. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62795. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62796. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62797. }
  62798. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62799. if (this._readyToPlayCallback) {
  62800. window.setTimeout(function () {
  62801. if (_this._readyToPlayCallback) {
  62802. _this._readyToPlayCallback();
  62803. }
  62804. }, 1000);
  62805. }
  62806. }
  62807. }
  62808. Sound.prototype.dispose = function () {
  62809. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62810. if (this.isPlaying) {
  62811. this.stop();
  62812. }
  62813. this._isReadyToPlay = false;
  62814. if (this.soundTrackId === -1) {
  62815. this._scene.mainSoundTrack.RemoveSound(this);
  62816. }
  62817. else {
  62818. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62819. }
  62820. if (this._soundGain) {
  62821. this._soundGain.disconnect();
  62822. this._soundGain = null;
  62823. }
  62824. if (this._soundPanner) {
  62825. this._soundPanner.disconnect();
  62826. this._soundPanner = null;
  62827. }
  62828. if (this._soundSource) {
  62829. this._soundSource.disconnect();
  62830. this._soundSource = null;
  62831. }
  62832. this._audioBuffer = null;
  62833. if (this._htmlAudioElement) {
  62834. this._htmlAudioElement.pause();
  62835. this._htmlAudioElement.src = "";
  62836. document.body.removeChild(this._htmlAudioElement);
  62837. }
  62838. if (this._connectedMesh && this._registerFunc) {
  62839. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62840. this._connectedMesh = null;
  62841. }
  62842. }
  62843. };
  62844. Sound.prototype.isReady = function () {
  62845. return this._isReadyToPlay;
  62846. };
  62847. Sound.prototype._soundLoaded = function (audioData) {
  62848. var _this = this;
  62849. if (!BABYLON.Engine.audioEngine.audioContext) {
  62850. return;
  62851. }
  62852. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62853. _this._audioBuffer = buffer;
  62854. _this._isReadyToPlay = true;
  62855. if (_this.autoplay) {
  62856. _this.play();
  62857. }
  62858. if (_this._readyToPlayCallback) {
  62859. _this._readyToPlayCallback();
  62860. }
  62861. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62862. };
  62863. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62865. this._audioBuffer = audioBuffer;
  62866. this._isReadyToPlay = true;
  62867. }
  62868. };
  62869. Sound.prototype.updateOptions = function (options) {
  62870. if (options) {
  62871. this.loop = options.loop || this.loop;
  62872. this.maxDistance = options.maxDistance || this.maxDistance;
  62873. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62874. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62875. this.refDistance = options.refDistance || this.refDistance;
  62876. this.distanceModel = options.distanceModel || this.distanceModel;
  62877. this._playbackRate = options.playbackRate || this._playbackRate;
  62878. this._updateSpatialParameters();
  62879. if (this.isPlaying) {
  62880. if (this._streaming) {
  62881. this._htmlAudioElement.playbackRate = this._playbackRate;
  62882. }
  62883. else {
  62884. if (this._soundSource) {
  62885. this._soundSource.playbackRate.value = this._playbackRate;
  62886. }
  62887. }
  62888. }
  62889. }
  62890. };
  62891. Sound.prototype._createSpatialParameters = function () {
  62892. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62893. if (this._scene.headphone) {
  62894. this._panningModel = "HRTF";
  62895. }
  62896. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62897. this._updateSpatialParameters();
  62898. this._soundPanner.connect(this._ouputAudioNode);
  62899. this._inputAudioNode = this._soundPanner;
  62900. }
  62901. };
  62902. Sound.prototype._updateSpatialParameters = function () {
  62903. if (this.spatialSound && this._soundPanner) {
  62904. if (this.useCustomAttenuation) {
  62905. // Tricks to disable in a way embedded Web Audio attenuation
  62906. this._soundPanner.distanceModel = "linear";
  62907. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62908. this._soundPanner.refDistance = 1;
  62909. this._soundPanner.rolloffFactor = 1;
  62910. this._soundPanner.panningModel = this._panningModel;
  62911. }
  62912. else {
  62913. this._soundPanner.distanceModel = this.distanceModel;
  62914. this._soundPanner.maxDistance = this.maxDistance;
  62915. this._soundPanner.refDistance = this.refDistance;
  62916. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62917. this._soundPanner.panningModel = this._panningModel;
  62918. }
  62919. }
  62920. };
  62921. Sound.prototype.switchPanningModelToHRTF = function () {
  62922. this._panningModel = "HRTF";
  62923. this._switchPanningModel();
  62924. };
  62925. Sound.prototype.switchPanningModelToEqualPower = function () {
  62926. this._panningModel = "equalpower";
  62927. this._switchPanningModel();
  62928. };
  62929. Sound.prototype._switchPanningModel = function () {
  62930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62931. this._soundPanner.panningModel = this._panningModel;
  62932. }
  62933. };
  62934. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62935. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62936. if (this._isOutputConnected) {
  62937. this._ouputAudioNode.disconnect();
  62938. }
  62939. this._ouputAudioNode.connect(soundTrackAudioNode);
  62940. this._isOutputConnected = true;
  62941. }
  62942. };
  62943. /**
  62944. * Transform this sound into a directional source
  62945. * @param coneInnerAngle Size of the inner cone in degree
  62946. * @param coneOuterAngle Size of the outer cone in degree
  62947. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62948. */
  62949. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62950. if (coneOuterAngle < coneInnerAngle) {
  62951. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62952. return;
  62953. }
  62954. this._coneInnerAngle = coneInnerAngle;
  62955. this._coneOuterAngle = coneOuterAngle;
  62956. this._coneOuterGain = coneOuterGain;
  62957. this._isDirectional = true;
  62958. if (this.isPlaying && this.loop) {
  62959. this.stop();
  62960. this.play();
  62961. }
  62962. };
  62963. Sound.prototype.setPosition = function (newPosition) {
  62964. this._position = newPosition;
  62965. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62966. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62967. }
  62968. };
  62969. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62970. this._localDirection = newLocalDirection;
  62971. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62972. this._updateDirection();
  62973. }
  62974. };
  62975. Sound.prototype._updateDirection = function () {
  62976. if (!this._connectedMesh || !this._soundPanner) {
  62977. return;
  62978. }
  62979. var mat = this._connectedMesh.getWorldMatrix();
  62980. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62981. direction.normalize();
  62982. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62983. };
  62984. Sound.prototype.updateDistanceFromListener = function () {
  62985. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62986. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62987. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62988. }
  62989. };
  62990. Sound.prototype.setAttenuationFunction = function (callback) {
  62991. this._customAttenuationFunction = callback;
  62992. };
  62993. /**
  62994. * Play the sound
  62995. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62996. * @param offset (optional) Start the sound setting it at a specific time
  62997. */
  62998. Sound.prototype.play = function (time, offset) {
  62999. var _this = this;
  63000. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  63001. try {
  63002. if (this._startOffset < 0) {
  63003. time = -this._startOffset;
  63004. this._startOffset = 0;
  63005. }
  63006. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63007. if (!this._soundSource || !this._streamingSource) {
  63008. if (this.spatialSound && this._soundPanner) {
  63009. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63010. if (this._isDirectional) {
  63011. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  63012. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  63013. this._soundPanner.coneOuterGain = this._coneOuterGain;
  63014. if (this._connectedMesh) {
  63015. this._updateDirection();
  63016. }
  63017. else {
  63018. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  63019. }
  63020. }
  63021. }
  63022. }
  63023. if (this._streaming) {
  63024. if (!this._streamingSource) {
  63025. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  63026. this._htmlAudioElement.onended = function () { _this._onended(); };
  63027. this._htmlAudioElement.playbackRate = this._playbackRate;
  63028. }
  63029. this._streamingSource.disconnect();
  63030. this._streamingSource.connect(this._inputAudioNode);
  63031. this._htmlAudioElement.play();
  63032. }
  63033. else {
  63034. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  63035. this._soundSource.buffer = this._audioBuffer;
  63036. this._soundSource.connect(this._inputAudioNode);
  63037. this._soundSource.loop = this.loop;
  63038. this._soundSource.playbackRate.value = this._playbackRate;
  63039. this._soundSource.onended = function () { _this._onended(); };
  63040. if (this._soundSource.buffer) {
  63041. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  63042. }
  63043. }
  63044. this._startTime = startTime;
  63045. this.isPlaying = true;
  63046. this.isPaused = false;
  63047. }
  63048. catch (ex) {
  63049. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63050. }
  63051. }
  63052. };
  63053. Sound.prototype._onended = function () {
  63054. this.isPlaying = false;
  63055. if (this.onended) {
  63056. this.onended();
  63057. }
  63058. };
  63059. /**
  63060. * Stop the sound
  63061. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63062. */
  63063. Sound.prototype.stop = function (time) {
  63064. if (this.isPlaying) {
  63065. if (this._streaming) {
  63066. this._htmlAudioElement.pause();
  63067. // Test needed for Firefox or it will generate an Invalid State Error
  63068. if (this._htmlAudioElement.currentTime > 0) {
  63069. this._htmlAudioElement.currentTime = 0;
  63070. }
  63071. }
  63072. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63073. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63074. this._soundSource.stop(stopTime);
  63075. this._soundSource.onended = function () { };
  63076. if (!this.isPaused) {
  63077. this._startOffset = 0;
  63078. }
  63079. }
  63080. this.isPlaying = false;
  63081. }
  63082. };
  63083. Sound.prototype.pause = function () {
  63084. if (this.isPlaying) {
  63085. this.isPaused = true;
  63086. if (this._streaming) {
  63087. this._htmlAudioElement.pause();
  63088. }
  63089. else if (BABYLON.Engine.audioEngine.audioContext) {
  63090. this.stop(0);
  63091. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63092. }
  63093. }
  63094. };
  63095. Sound.prototype.setVolume = function (newVolume, time) {
  63096. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63097. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63098. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63099. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63100. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63101. }
  63102. else {
  63103. this._soundGain.gain.value = newVolume;
  63104. }
  63105. }
  63106. this._volume = newVolume;
  63107. };
  63108. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63109. this._playbackRate = newPlaybackRate;
  63110. if (this.isPlaying) {
  63111. if (this._streaming) {
  63112. this._htmlAudioElement.playbackRate = this._playbackRate;
  63113. }
  63114. else if (this._soundSource) {
  63115. this._soundSource.playbackRate.value = this._playbackRate;
  63116. }
  63117. }
  63118. };
  63119. Sound.prototype.getVolume = function () {
  63120. return this._volume;
  63121. };
  63122. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63123. var _this = this;
  63124. if (this._connectedMesh && this._registerFunc) {
  63125. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63126. this._registerFunc = null;
  63127. }
  63128. this._connectedMesh = meshToConnectTo;
  63129. if (!this.spatialSound) {
  63130. this.spatialSound = true;
  63131. this._createSpatialParameters();
  63132. if (this.isPlaying && this.loop) {
  63133. this.stop();
  63134. this.play();
  63135. }
  63136. }
  63137. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63138. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63139. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63140. };
  63141. Sound.prototype.detachFromMesh = function () {
  63142. if (this._connectedMesh && this._registerFunc) {
  63143. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63144. this._registerFunc = null;
  63145. this._connectedMesh = null;
  63146. }
  63147. };
  63148. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63149. if (!node.getBoundingInfo) {
  63150. return;
  63151. }
  63152. var mesh = node;
  63153. var boundingInfo = mesh.getBoundingInfo();
  63154. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63155. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63156. this._updateDirection();
  63157. }
  63158. };
  63159. Sound.prototype.clone = function () {
  63160. var _this = this;
  63161. if (!this._streaming) {
  63162. var setBufferAndRun = function () {
  63163. if (_this._isReadyToPlay) {
  63164. clonedSound._audioBuffer = _this.getAudioBuffer();
  63165. clonedSound._isReadyToPlay = true;
  63166. if (clonedSound.autoplay) {
  63167. clonedSound.play();
  63168. }
  63169. }
  63170. else {
  63171. window.setTimeout(setBufferAndRun, 300);
  63172. }
  63173. };
  63174. var currentOptions = {
  63175. autoplay: this.autoplay, loop: this.loop,
  63176. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63177. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63178. refDistance: this.refDistance, distanceModel: this.distanceModel
  63179. };
  63180. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63181. if (this.useCustomAttenuation) {
  63182. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63183. }
  63184. clonedSound.setPosition(this._position);
  63185. clonedSound.setPlaybackRate(this._playbackRate);
  63186. setBufferAndRun();
  63187. return clonedSound;
  63188. }
  63189. // Can't clone a streaming sound
  63190. else {
  63191. return null;
  63192. }
  63193. };
  63194. Sound.prototype.getAudioBuffer = function () {
  63195. return this._audioBuffer;
  63196. };
  63197. Sound.prototype.serialize = function () {
  63198. var serializationObject = {
  63199. name: this.name,
  63200. url: this.name,
  63201. autoplay: this.autoplay,
  63202. loop: this.loop,
  63203. volume: this._volume,
  63204. spatialSound: this.spatialSound,
  63205. maxDistance: this.maxDistance,
  63206. rolloffFactor: this.rolloffFactor,
  63207. refDistance: this.refDistance,
  63208. distanceModel: this.distanceModel,
  63209. playbackRate: this._playbackRate,
  63210. panningModel: this._panningModel,
  63211. soundTrackId: this.soundTrackId
  63212. };
  63213. if (this.spatialSound) {
  63214. if (this._connectedMesh)
  63215. serializationObject.connectedMeshId = this._connectedMesh.id;
  63216. serializationObject.position = this._position.asArray();
  63217. serializationObject.refDistance = this.refDistance;
  63218. serializationObject.distanceModel = this.distanceModel;
  63219. serializationObject.isDirectional = this._isDirectional;
  63220. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63221. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63222. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63223. serializationObject.coneOuterGain = this._coneOuterGain;
  63224. }
  63225. return serializationObject;
  63226. };
  63227. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63228. var soundName = parsedSound.name;
  63229. var soundUrl;
  63230. if (parsedSound.url) {
  63231. soundUrl = rootUrl + parsedSound.url;
  63232. }
  63233. else {
  63234. soundUrl = rootUrl + soundName;
  63235. }
  63236. var options = {
  63237. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63238. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63239. rolloffFactor: parsedSound.rolloffFactor,
  63240. refDistance: parsedSound.refDistance,
  63241. distanceModel: parsedSound.distanceModel,
  63242. playbackRate: parsedSound.playbackRate
  63243. };
  63244. var newSound;
  63245. if (!sourceSound) {
  63246. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63247. scene._addPendingData(newSound);
  63248. }
  63249. else {
  63250. var setBufferAndRun = function () {
  63251. if (sourceSound._isReadyToPlay) {
  63252. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63253. newSound._isReadyToPlay = true;
  63254. if (newSound.autoplay) {
  63255. newSound.play();
  63256. }
  63257. }
  63258. else {
  63259. window.setTimeout(setBufferAndRun, 300);
  63260. }
  63261. };
  63262. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63263. setBufferAndRun();
  63264. }
  63265. if (parsedSound.position) {
  63266. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63267. newSound.setPosition(soundPosition);
  63268. }
  63269. if (parsedSound.isDirectional) {
  63270. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63271. if (parsedSound.localDirectionToMesh) {
  63272. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63273. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63274. }
  63275. }
  63276. if (parsedSound.connectedMeshId) {
  63277. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63278. if (connectedMesh) {
  63279. newSound.attachToMesh(connectedMesh);
  63280. }
  63281. }
  63282. return newSound;
  63283. };
  63284. return Sound;
  63285. }());
  63286. BABYLON.Sound = Sound;
  63287. })(BABYLON || (BABYLON = {}));
  63288. //# sourceMappingURL=babylon.sound.js.map
  63289. var BABYLON;
  63290. (function (BABYLON) {
  63291. var SoundTrack = /** @class */ (function () {
  63292. function SoundTrack(scene, options) {
  63293. this.id = -1;
  63294. this._isMainTrack = false;
  63295. this._isInitialized = false;
  63296. this._scene = scene;
  63297. this.soundCollection = new Array();
  63298. this._options = options;
  63299. if (!this._isMainTrack) {
  63300. this._scene.soundTracks.push(this);
  63301. this.id = this._scene.soundTracks.length - 1;
  63302. }
  63303. }
  63304. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63305. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63306. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63307. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63308. if (this._options) {
  63309. if (this._options.volume) {
  63310. this._outputAudioNode.gain.value = this._options.volume;
  63311. }
  63312. if (this._options.mainTrack) {
  63313. this._isMainTrack = this._options.mainTrack;
  63314. }
  63315. }
  63316. this._isInitialized = true;
  63317. }
  63318. };
  63319. SoundTrack.prototype.dispose = function () {
  63320. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63321. if (this._connectedAnalyser) {
  63322. this._connectedAnalyser.stopDebugCanvas();
  63323. }
  63324. while (this.soundCollection.length) {
  63325. this.soundCollection[0].dispose();
  63326. }
  63327. if (this._outputAudioNode) {
  63328. this._outputAudioNode.disconnect();
  63329. }
  63330. this._outputAudioNode = null;
  63331. }
  63332. };
  63333. SoundTrack.prototype.AddSound = function (sound) {
  63334. if (!this._isInitialized) {
  63335. this._initializeSoundTrackAudioGraph();
  63336. }
  63337. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63338. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63339. }
  63340. if (sound.soundTrackId) {
  63341. if (sound.soundTrackId === -1) {
  63342. this._scene.mainSoundTrack.RemoveSound(sound);
  63343. }
  63344. else {
  63345. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63346. }
  63347. }
  63348. this.soundCollection.push(sound);
  63349. sound.soundTrackId = this.id;
  63350. };
  63351. SoundTrack.prototype.RemoveSound = function (sound) {
  63352. var index = this.soundCollection.indexOf(sound);
  63353. if (index !== -1) {
  63354. this.soundCollection.splice(index, 1);
  63355. }
  63356. };
  63357. SoundTrack.prototype.setVolume = function (newVolume) {
  63358. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63359. this._outputAudioNode.gain.value = newVolume;
  63360. }
  63361. };
  63362. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63363. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63364. for (var i = 0; i < this.soundCollection.length; i++) {
  63365. this.soundCollection[i].switchPanningModelToHRTF();
  63366. }
  63367. }
  63368. };
  63369. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63370. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63371. for (var i = 0; i < this.soundCollection.length; i++) {
  63372. this.soundCollection[i].switchPanningModelToEqualPower();
  63373. }
  63374. }
  63375. };
  63376. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63377. if (this._connectedAnalyser) {
  63378. this._connectedAnalyser.stopDebugCanvas();
  63379. }
  63380. this._connectedAnalyser = analyser;
  63381. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63382. this._outputAudioNode.disconnect();
  63383. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63384. }
  63385. };
  63386. return SoundTrack;
  63387. }());
  63388. BABYLON.SoundTrack = SoundTrack;
  63389. })(BABYLON || (BABYLON = {}));
  63390. //# sourceMappingURL=babylon.soundtrack.js.map
  63391. var BABYLON;
  63392. (function (BABYLON) {
  63393. /**
  63394. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63395. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63396. */
  63397. var Analyser = /** @class */ (function () {
  63398. /**
  63399. * Creates a new analyser
  63400. * @param scene defines hosting scene
  63401. */
  63402. function Analyser(scene) {
  63403. /**
  63404. * Gets or sets the smoothing
  63405. * @ignorenaming
  63406. */
  63407. this.SMOOTHING = 0.75;
  63408. /**
  63409. * Gets or sets the FFT table size
  63410. * @ignorenaming
  63411. */
  63412. this.FFT_SIZE = 512;
  63413. /**
  63414. * Gets or sets the bar graph amplitude
  63415. * @ignorenaming
  63416. */
  63417. this.BARGRAPHAMPLITUDE = 256;
  63418. /**
  63419. * Gets or sets the position of the debug canvas
  63420. * @ignorenaming
  63421. */
  63422. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63423. /**
  63424. * Gets or sets the debug canvas size
  63425. * @ignorenaming
  63426. */
  63427. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63428. this._scene = scene;
  63429. this._audioEngine = BABYLON.Engine.audioEngine;
  63430. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63431. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63432. this._webAudioAnalyser.minDecibels = -140;
  63433. this._webAudioAnalyser.maxDecibels = 0;
  63434. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63435. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63436. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63437. }
  63438. }
  63439. /**
  63440. * Get the number of data values you will have to play with for the visualization
  63441. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63442. * @returns a number
  63443. */
  63444. Analyser.prototype.getFrequencyBinCount = function () {
  63445. if (this._audioEngine.canUseWebAudio) {
  63446. return this._webAudioAnalyser.frequencyBinCount;
  63447. }
  63448. else {
  63449. return 0;
  63450. }
  63451. };
  63452. /**
  63453. * Gets the current frequency data as a byte array
  63454. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63455. * @returns a Uint8Array
  63456. */
  63457. Analyser.prototype.getByteFrequencyData = function () {
  63458. if (this._audioEngine.canUseWebAudio) {
  63459. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63460. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63461. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63462. }
  63463. return this._byteFreqs;
  63464. };
  63465. /**
  63466. * Gets the current waveform as a byte array
  63467. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63468. * @returns a Uint8Array
  63469. */
  63470. Analyser.prototype.getByteTimeDomainData = function () {
  63471. if (this._audioEngine.canUseWebAudio) {
  63472. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63473. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63474. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63475. }
  63476. return this._byteTime;
  63477. };
  63478. /**
  63479. * Gets the current frequency data as a float array
  63480. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63481. * @returns a Float32Array
  63482. */
  63483. Analyser.prototype.getFloatFrequencyData = function () {
  63484. if (this._audioEngine.canUseWebAudio) {
  63485. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63486. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63487. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63488. }
  63489. return this._floatFreqs;
  63490. };
  63491. /**
  63492. * Renders the debug canvas
  63493. */
  63494. Analyser.prototype.drawDebugCanvas = function () {
  63495. var _this = this;
  63496. if (this._audioEngine.canUseWebAudio) {
  63497. if (!this._debugCanvas) {
  63498. this._debugCanvas = document.createElement("canvas");
  63499. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63500. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63501. this._debugCanvas.style.position = "absolute";
  63502. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63503. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63504. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63505. document.body.appendChild(this._debugCanvas);
  63506. this._registerFunc = function () {
  63507. _this.drawDebugCanvas();
  63508. };
  63509. this._scene.registerBeforeRender(this._registerFunc);
  63510. }
  63511. if (this._registerFunc && this._debugCanvasContext) {
  63512. var workingArray = this.getByteFrequencyData();
  63513. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63514. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63515. // Draw the frequency domain chart.
  63516. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63517. var value = workingArray[i];
  63518. var percent = value / this.BARGRAPHAMPLITUDE;
  63519. var height = this.DEBUGCANVASSIZE.height * percent;
  63520. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63521. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63522. var hue = i / this.getFrequencyBinCount() * 360;
  63523. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63524. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63525. }
  63526. }
  63527. }
  63528. };
  63529. /**
  63530. * Stops rendering the debug canvas and removes it
  63531. */
  63532. Analyser.prototype.stopDebugCanvas = function () {
  63533. if (this._debugCanvas) {
  63534. if (this._registerFunc) {
  63535. this._scene.unregisterBeforeRender(this._registerFunc);
  63536. this._registerFunc = null;
  63537. }
  63538. document.body.removeChild(this._debugCanvas);
  63539. this._debugCanvas = null;
  63540. this._debugCanvasContext = null;
  63541. }
  63542. };
  63543. /**
  63544. * Connects two audio nodes
  63545. * @param inputAudioNode defines first node to connect
  63546. * @param outputAudioNode defines second node to connect
  63547. */
  63548. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63549. if (this._audioEngine.canUseWebAudio) {
  63550. inputAudioNode.connect(this._webAudioAnalyser);
  63551. this._webAudioAnalyser.connect(outputAudioNode);
  63552. }
  63553. };
  63554. /**
  63555. * Releases all associated resources
  63556. */
  63557. Analyser.prototype.dispose = function () {
  63558. if (this._audioEngine.canUseWebAudio) {
  63559. this._webAudioAnalyser.disconnect();
  63560. }
  63561. };
  63562. return Analyser;
  63563. }());
  63564. BABYLON.Analyser = Analyser;
  63565. })(BABYLON || (BABYLON = {}));
  63566. //# sourceMappingURL=babylon.analyser.js.map
  63567. var BABYLON;
  63568. (function (BABYLON) {
  63569. var CubeTexture = /** @class */ (function (_super) {
  63570. __extends(CubeTexture, _super);
  63571. /**
  63572. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63573. * as prefiltered data.
  63574. * @param rootUrl defines the url of the texture or the root name of the six images
  63575. * @param scene defines the scene the texture is attached to
  63576. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63577. * @param noMipmap defines if mipmaps should be created or not
  63578. * @param files defines the six files to load for the different faces
  63579. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63580. * @param onError defines a callback triggered in case of error during load
  63581. * @param format defines the internal format to use for the texture once loaded
  63582. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63583. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63584. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63585. * @return the cube texture
  63586. */
  63587. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials) {
  63588. if (extensions === void 0) { extensions = null; }
  63589. if (noMipmap === void 0) { noMipmap = false; }
  63590. if (files === void 0) { files = null; }
  63591. if (onLoad === void 0) { onLoad = null; }
  63592. if (onError === void 0) { onError = null; }
  63593. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63594. if (prefiltered === void 0) { prefiltered = false; }
  63595. if (forcedExtension === void 0) { forcedExtension = null; }
  63596. if (createPolynomials === void 0) { createPolynomials = false; }
  63597. var _this = _super.call(this, scene) || this;
  63598. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63599. /**
  63600. * Gets or sets the center of the bounding box associated with the cube texture
  63601. * It must define where the camera used to render the texture was set
  63602. */
  63603. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63604. _this._rotationY = 0;
  63605. _this.name = rootUrl;
  63606. _this.url = rootUrl;
  63607. _this._noMipmap = noMipmap;
  63608. _this.hasAlpha = false;
  63609. _this._format = format;
  63610. _this._prefiltered = prefiltered;
  63611. _this.isCube = true;
  63612. _this._textureMatrix = BABYLON.Matrix.Identity();
  63613. _this._createPolynomials = createPolynomials;
  63614. if (prefiltered) {
  63615. _this.gammaSpace = false;
  63616. }
  63617. if (!rootUrl && !files) {
  63618. return _this;
  63619. }
  63620. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63621. var lastDot = rootUrl.lastIndexOf(".");
  63622. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63623. var isDDS = (extension === ".dds");
  63624. if (!files) {
  63625. if (!isDDS && !extensions) {
  63626. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63627. }
  63628. files = [];
  63629. if (extensions) {
  63630. for (var index = 0; index < extensions.length; index++) {
  63631. files.push(rootUrl + extensions[index]);
  63632. }
  63633. }
  63634. }
  63635. _this._files = files;
  63636. if (!_this._texture) {
  63637. if (!scene.useDelayedTextureLoading) {
  63638. if (prefiltered) {
  63639. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63640. }
  63641. else {
  63642. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63643. }
  63644. }
  63645. else {
  63646. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63647. }
  63648. }
  63649. else if (onLoad) {
  63650. if (_this._texture.isReady) {
  63651. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63652. }
  63653. else {
  63654. _this._texture.onLoadedObservable.add(onLoad);
  63655. }
  63656. }
  63657. return _this;
  63658. }
  63659. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63660. get: function () {
  63661. return this._boundingBoxSize;
  63662. },
  63663. /**
  63664. * Gets or sets the size of the bounding box associated with the cube texture
  63665. * When defined, the cubemap will switch to local mode
  63666. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63667. * @example https://www.babylonjs-playground.com/#RNASML
  63668. */
  63669. set: function (value) {
  63670. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63671. return;
  63672. }
  63673. this._boundingBoxSize = value;
  63674. var scene = this.getScene();
  63675. if (scene) {
  63676. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63677. }
  63678. },
  63679. enumerable: true,
  63680. configurable: true
  63681. });
  63682. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63683. /**
  63684. * Gets texture matrix rotation angle around Y axis radians.
  63685. */
  63686. get: function () {
  63687. return this._rotationY;
  63688. },
  63689. /**
  63690. * Sets texture matrix rotation angle around Y axis in radians.
  63691. */
  63692. set: function (value) {
  63693. this._rotationY = value;
  63694. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63695. },
  63696. enumerable: true,
  63697. configurable: true
  63698. });
  63699. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63700. var rootUrlKey = "";
  63701. files.forEach(function (url) { return rootUrlKey += url; });
  63702. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63703. };
  63704. /**
  63705. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63706. * @param url defines the url of the prefiltered texture
  63707. * @param scene defines the scene the texture is attached to
  63708. * @param forcedExtension defines the extension of the file if different from the url
  63709. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63710. * @return the prefiltered texture
  63711. */
  63712. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63713. if (forcedExtension === void 0) { forcedExtension = null; }
  63714. if (createPolynomials === void 0) { createPolynomials = true; }
  63715. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63716. };
  63717. // Methods
  63718. CubeTexture.prototype.delayLoad = function () {
  63719. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63720. return;
  63721. }
  63722. var scene = this.getScene();
  63723. if (!scene) {
  63724. return;
  63725. }
  63726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63727. this._texture = this._getFromCache(this.url, this._noMipmap);
  63728. if (!this._texture) {
  63729. if (this._prefiltered) {
  63730. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63731. }
  63732. else {
  63733. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63734. }
  63735. }
  63736. };
  63737. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63738. return this._textureMatrix;
  63739. };
  63740. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63741. this._textureMatrix = value;
  63742. };
  63743. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63744. var texture = BABYLON.SerializationHelper.Parse(function () {
  63745. var prefiltered = false;
  63746. if (parsedTexture.prefiltered) {
  63747. prefiltered = parsedTexture.prefiltered;
  63748. }
  63749. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63750. }, parsedTexture, scene);
  63751. // Local Cubemaps
  63752. if (parsedTexture.boundingBoxPosition) {
  63753. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63754. }
  63755. if (parsedTexture.boundingBoxSize) {
  63756. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63757. }
  63758. // Animations
  63759. if (parsedTexture.animations) {
  63760. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63761. var parsedAnimation = parsedTexture.animations[animationIndex];
  63762. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63763. }
  63764. }
  63765. return texture;
  63766. };
  63767. CubeTexture.prototype.clone = function () {
  63768. var _this = this;
  63769. return BABYLON.SerializationHelper.Clone(function () {
  63770. var scene = _this.getScene();
  63771. if (!scene) {
  63772. return _this;
  63773. }
  63774. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63775. }, this);
  63776. };
  63777. __decorate([
  63778. BABYLON.serialize("rotationY")
  63779. ], CubeTexture.prototype, "_rotationY", void 0);
  63780. return CubeTexture;
  63781. }(BABYLON.BaseTexture));
  63782. BABYLON.CubeTexture = CubeTexture;
  63783. })(BABYLON || (BABYLON = {}));
  63784. //# sourceMappingURL=babylon.cubeTexture.js.map
  63785. var BABYLON;
  63786. (function (BABYLON) {
  63787. var RenderTargetTexture = /** @class */ (function (_super) {
  63788. __extends(RenderTargetTexture, _super);
  63789. /**
  63790. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63791. * or used a shadow, depth texture...
  63792. * @param name The friendly name of the texture
  63793. * @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)
  63794. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63795. * @param generateMipMaps True if mip maps need to be generated after render.
  63796. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63797. * @param type The type of the buffer in the RTT (int, half float, float...)
  63798. * @param isCube True if a cube texture needs to be created
  63799. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63800. * @param generateDepthBuffer True to generate a depth buffer
  63801. * @param generateStencilBuffer True to generate a stencil buffer
  63802. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63803. */
  63804. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63805. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63806. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63807. if (isCube === void 0) { isCube = false; }
  63808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63809. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63810. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63811. if (isMulti === void 0) { isMulti = false; }
  63812. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63813. _this.isCube = isCube;
  63814. /**
  63815. * Use this list to define the list of mesh you want to render.
  63816. */
  63817. _this.renderList = new Array();
  63818. _this.renderParticles = true;
  63819. _this.renderSprites = false;
  63820. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63821. _this.ignoreCameraViewport = false;
  63822. // Events
  63823. /**
  63824. * An event triggered when the texture is unbind.
  63825. */
  63826. _this.onBeforeBindObservable = new BABYLON.Observable();
  63827. /**
  63828. * An event triggered when the texture is unbind.
  63829. */
  63830. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63831. /**
  63832. * An event triggered before rendering the texture
  63833. */
  63834. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63835. /**
  63836. * An event triggered after rendering the texture
  63837. */
  63838. _this.onAfterRenderObservable = new BABYLON.Observable();
  63839. /**
  63840. * An event triggered after the texture clear
  63841. */
  63842. _this.onClearObservable = new BABYLON.Observable();
  63843. _this._currentRefreshId = -1;
  63844. _this._refreshRate = 1;
  63845. _this._samples = 1;
  63846. /**
  63847. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63848. * It must define where the camera used to render the texture is set
  63849. */
  63850. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63851. scene = _this.getScene();
  63852. if (!scene) {
  63853. return _this;
  63854. }
  63855. _this._engine = scene.getEngine();
  63856. _this.name = name;
  63857. _this.isRenderTarget = true;
  63858. _this._initialSizeParameter = size;
  63859. _this._processSizeParameter(size);
  63860. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63861. });
  63862. _this._generateMipMaps = generateMipMaps ? true : false;
  63863. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63864. // Rendering groups
  63865. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63866. if (isMulti) {
  63867. return _this;
  63868. }
  63869. _this._renderTargetOptions = {
  63870. generateMipMaps: generateMipMaps,
  63871. type: type,
  63872. samplingMode: samplingMode,
  63873. generateDepthBuffer: generateDepthBuffer,
  63874. generateStencilBuffer: generateStencilBuffer
  63875. };
  63876. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63877. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63878. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63879. }
  63880. if (isCube) {
  63881. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63882. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63883. _this._textureMatrix = BABYLON.Matrix.Identity();
  63884. }
  63885. else {
  63886. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63887. }
  63888. return _this;
  63889. }
  63890. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63891. get: function () {
  63892. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63893. },
  63894. enumerable: true,
  63895. configurable: true
  63896. });
  63897. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63898. get: function () {
  63899. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63900. },
  63901. enumerable: true,
  63902. configurable: true
  63903. });
  63904. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63905. get: function () {
  63906. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63907. },
  63908. enumerable: true,
  63909. configurable: true
  63910. });
  63911. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63912. set: function (callback) {
  63913. if (this._onAfterUnbindObserver) {
  63914. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63915. }
  63916. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63917. },
  63918. enumerable: true,
  63919. configurable: true
  63920. });
  63921. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63922. set: function (callback) {
  63923. if (this._onBeforeRenderObserver) {
  63924. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63925. }
  63926. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63927. },
  63928. enumerable: true,
  63929. configurable: true
  63930. });
  63931. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63932. set: function (callback) {
  63933. if (this._onAfterRenderObserver) {
  63934. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63935. }
  63936. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63937. },
  63938. enumerable: true,
  63939. configurable: true
  63940. });
  63941. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63942. set: function (callback) {
  63943. if (this._onClearObserver) {
  63944. this.onClearObservable.remove(this._onClearObserver);
  63945. }
  63946. this._onClearObserver = this.onClearObservable.add(callback);
  63947. },
  63948. enumerable: true,
  63949. configurable: true
  63950. });
  63951. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63952. get: function () {
  63953. return this._renderTargetOptions;
  63954. },
  63955. enumerable: true,
  63956. configurable: true
  63957. });
  63958. RenderTargetTexture.prototype._onRatioRescale = function () {
  63959. if (this._sizeRatio) {
  63960. this.resize(this._initialSizeParameter);
  63961. }
  63962. };
  63963. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63964. get: function () {
  63965. return this._boundingBoxSize;
  63966. },
  63967. /**
  63968. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63969. * When defined, the cubemap will switch to local mode
  63970. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63971. * @example https://www.babylonjs-playground.com/#RNASML
  63972. */
  63973. set: function (value) {
  63974. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63975. return;
  63976. }
  63977. this._boundingBoxSize = value;
  63978. var scene = this.getScene();
  63979. if (scene) {
  63980. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63981. }
  63982. },
  63983. enumerable: true,
  63984. configurable: true
  63985. });
  63986. /**
  63987. * Creates a depth stencil texture.
  63988. * This is only available in WebGL 2 or with the depth texture extension available.
  63989. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63990. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63991. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63992. */
  63993. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63994. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63995. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63996. if (generateStencil === void 0) { generateStencil = false; }
  63997. if (!this.getScene()) {
  63998. return;
  63999. }
  64000. var engine = this.getScene().getEngine();
  64001. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64002. bilinearFiltering: bilinearFiltering,
  64003. comparisonFunction: comparisonFunction,
  64004. generateStencil: generateStencil,
  64005. isCube: this.isCube
  64006. });
  64007. engine.setFrameBufferDepthStencilTexture(this);
  64008. };
  64009. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64010. if (size.ratio) {
  64011. this._sizeRatio = size.ratio;
  64012. this._size = {
  64013. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64014. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64015. };
  64016. }
  64017. else {
  64018. this._size = size;
  64019. }
  64020. };
  64021. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64022. get: function () {
  64023. return this._samples;
  64024. },
  64025. set: function (value) {
  64026. if (this._samples === value) {
  64027. return;
  64028. }
  64029. var scene = this.getScene();
  64030. if (!scene) {
  64031. return;
  64032. }
  64033. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64034. },
  64035. enumerable: true,
  64036. configurable: true
  64037. });
  64038. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64039. this._currentRefreshId = -1;
  64040. };
  64041. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64042. get: function () {
  64043. return this._refreshRate;
  64044. },
  64045. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64046. set: function (value) {
  64047. this._refreshRate = value;
  64048. this.resetRefreshCounter();
  64049. },
  64050. enumerable: true,
  64051. configurable: true
  64052. });
  64053. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64054. if (!this._postProcessManager) {
  64055. var scene = this.getScene();
  64056. if (!scene) {
  64057. return;
  64058. }
  64059. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64060. this._postProcesses = new Array();
  64061. }
  64062. this._postProcesses.push(postProcess);
  64063. this._postProcesses[0].autoClear = false;
  64064. };
  64065. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64066. if (!this._postProcesses) {
  64067. return;
  64068. }
  64069. if (dispose) {
  64070. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64071. var postProcess = _a[_i];
  64072. postProcess.dispose();
  64073. }
  64074. }
  64075. this._postProcesses = [];
  64076. };
  64077. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64078. if (!this._postProcesses) {
  64079. return;
  64080. }
  64081. var index = this._postProcesses.indexOf(postProcess);
  64082. if (index === -1) {
  64083. return;
  64084. }
  64085. this._postProcesses.splice(index, 1);
  64086. if (this._postProcesses.length > 0) {
  64087. this._postProcesses[0].autoClear = false;
  64088. }
  64089. };
  64090. RenderTargetTexture.prototype._shouldRender = function () {
  64091. if (this._currentRefreshId === -1) { // At least render once
  64092. this._currentRefreshId = 1;
  64093. return true;
  64094. }
  64095. if (this.refreshRate === this._currentRefreshId) {
  64096. this._currentRefreshId = 1;
  64097. return true;
  64098. }
  64099. this._currentRefreshId++;
  64100. return false;
  64101. };
  64102. RenderTargetTexture.prototype.getRenderSize = function () {
  64103. if (this._size.width) {
  64104. return this._size.width;
  64105. }
  64106. return this._size;
  64107. };
  64108. RenderTargetTexture.prototype.getRenderWidth = function () {
  64109. if (this._size.width) {
  64110. return this._size.width;
  64111. }
  64112. return this._size;
  64113. };
  64114. RenderTargetTexture.prototype.getRenderHeight = function () {
  64115. if (this._size.width) {
  64116. return this._size.height;
  64117. }
  64118. return this._size;
  64119. };
  64120. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64121. get: function () {
  64122. return true;
  64123. },
  64124. enumerable: true,
  64125. configurable: true
  64126. });
  64127. RenderTargetTexture.prototype.scale = function (ratio) {
  64128. var newSize = this.getRenderSize() * ratio;
  64129. this.resize(newSize);
  64130. };
  64131. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64132. if (this.isCube) {
  64133. return this._textureMatrix;
  64134. }
  64135. return _super.prototype.getReflectionTextureMatrix.call(this);
  64136. };
  64137. RenderTargetTexture.prototype.resize = function (size) {
  64138. this.releaseInternalTexture();
  64139. var scene = this.getScene();
  64140. if (!scene) {
  64141. return;
  64142. }
  64143. this._processSizeParameter(size);
  64144. if (this.isCube) {
  64145. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64146. }
  64147. else {
  64148. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64149. }
  64150. };
  64151. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64152. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64153. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64154. var scene = this.getScene();
  64155. if (!scene) {
  64156. return;
  64157. }
  64158. var engine = scene.getEngine();
  64159. if (this.useCameraPostProcesses !== undefined) {
  64160. useCameraPostProcess = this.useCameraPostProcesses;
  64161. }
  64162. if (this._waitingRenderList) {
  64163. this.renderList = [];
  64164. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64165. var id = this._waitingRenderList[index];
  64166. var mesh_1 = scene.getMeshByID(id);
  64167. if (mesh_1) {
  64168. this.renderList.push(mesh_1);
  64169. }
  64170. }
  64171. delete this._waitingRenderList;
  64172. }
  64173. // Is predicate defined?
  64174. if (this.renderListPredicate) {
  64175. if (this.renderList) {
  64176. this.renderList.splice(0); // Clear previous renderList
  64177. }
  64178. else {
  64179. this.renderList = [];
  64180. }
  64181. var scene = this.getScene();
  64182. if (!scene) {
  64183. return;
  64184. }
  64185. var sceneMeshes = scene.meshes;
  64186. for (var index = 0; index < sceneMeshes.length; index++) {
  64187. var mesh = sceneMeshes[index];
  64188. if (this.renderListPredicate(mesh)) {
  64189. this.renderList.push(mesh);
  64190. }
  64191. }
  64192. }
  64193. this.onBeforeBindObservable.notifyObservers(this);
  64194. // Set custom projection.
  64195. // Needs to be before binding to prevent changing the aspect ratio.
  64196. var camera;
  64197. if (this.activeCamera) {
  64198. camera = this.activeCamera;
  64199. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64200. if (this.activeCamera !== scene.activeCamera) {
  64201. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64202. }
  64203. }
  64204. else {
  64205. camera = scene.activeCamera;
  64206. if (camera) {
  64207. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64208. }
  64209. }
  64210. // Prepare renderingManager
  64211. this._renderingManager.reset();
  64212. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64213. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64214. var sceneRenderId = scene.getRenderId();
  64215. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64216. var mesh = currentRenderList[meshIndex];
  64217. if (mesh) {
  64218. if (!mesh.isReady(this.refreshRate === 0)) {
  64219. this.resetRefreshCounter();
  64220. continue;
  64221. }
  64222. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64223. var isMasked = void 0;
  64224. if (!this.renderList && camera) {
  64225. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64226. }
  64227. else {
  64228. isMasked = false;
  64229. }
  64230. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64231. mesh._activate(sceneRenderId);
  64232. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64233. var subMesh = mesh.subMeshes[subIndex];
  64234. scene._activeIndices.addCount(subMesh.indexCount, false);
  64235. this._renderingManager.dispatch(subMesh, mesh);
  64236. }
  64237. }
  64238. }
  64239. }
  64240. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64241. var particleSystem = scene.particleSystems[particleIndex];
  64242. var emitter = particleSystem.emitter;
  64243. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64244. continue;
  64245. }
  64246. if (currentRenderList.indexOf(emitter) >= 0) {
  64247. this._renderingManager.dispatchParticles(particleSystem);
  64248. }
  64249. }
  64250. if (this.isCube) {
  64251. for (var face = 0; face < 6; face++) {
  64252. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64253. scene.incrementRenderId();
  64254. scene.resetCachedMaterial();
  64255. }
  64256. }
  64257. else {
  64258. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64259. }
  64260. this.onAfterUnbindObservable.notifyObservers(this);
  64261. if (scene.activeCamera) {
  64262. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64263. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64264. }
  64265. engine.setViewport(scene.activeCamera.viewport);
  64266. }
  64267. scene.resetCachedMaterial();
  64268. };
  64269. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64270. var minimum = 128;
  64271. var x = renderDimension * scale;
  64272. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64273. // Ensure we don't exceed the render dimension (while staying POT)
  64274. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64275. };
  64276. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64277. var _this = this;
  64278. if (!this._texture) {
  64279. return;
  64280. }
  64281. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64282. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64283. });
  64284. };
  64285. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64286. var scene = this.getScene();
  64287. if (!scene) {
  64288. return;
  64289. }
  64290. var engine = scene.getEngine();
  64291. if (!this._texture) {
  64292. return;
  64293. }
  64294. // Bind
  64295. if (this._postProcessManager) {
  64296. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64297. }
  64298. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64299. if (this._texture) {
  64300. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64301. }
  64302. }
  64303. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64304. // Clear
  64305. if (this.onClearObservable.hasObservers()) {
  64306. this.onClearObservable.notifyObservers(engine);
  64307. }
  64308. else {
  64309. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64310. }
  64311. if (!this._doNotChangeAspectRatio) {
  64312. scene.updateTransformMatrix(true);
  64313. }
  64314. // Render
  64315. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64316. if (this._postProcessManager) {
  64317. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64318. }
  64319. else if (useCameraPostProcess) {
  64320. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64321. }
  64322. if (!this._doNotChangeAspectRatio) {
  64323. scene.updateTransformMatrix(true);
  64324. }
  64325. // Dump ?
  64326. if (dumpForDebug) {
  64327. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64328. }
  64329. // Unbind
  64330. if (!this.isCube || faceIndex === 5) {
  64331. if (this.isCube) {
  64332. if (faceIndex === 5) {
  64333. engine.generateMipMapsForCubemap(this._texture);
  64334. }
  64335. }
  64336. this.unbindFrameBuffer(engine, faceIndex);
  64337. }
  64338. else {
  64339. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64340. }
  64341. };
  64342. /**
  64343. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64344. * This allowed control for front to back rendering or reversly depending of the special needs.
  64345. *
  64346. * @param renderingGroupId The rendering group id corresponding to its index
  64347. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64348. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64349. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64350. */
  64351. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64352. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64353. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64354. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64355. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64356. };
  64357. /**
  64358. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64359. *
  64360. * @param renderingGroupId The rendering group id corresponding to its index
  64361. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64362. */
  64363. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64364. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64365. };
  64366. RenderTargetTexture.prototype.clone = function () {
  64367. var textureSize = this.getSize();
  64368. 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);
  64369. // Base texture
  64370. newTexture.hasAlpha = this.hasAlpha;
  64371. newTexture.level = this.level;
  64372. // RenderTarget Texture
  64373. newTexture.coordinatesMode = this.coordinatesMode;
  64374. if (this.renderList) {
  64375. newTexture.renderList = this.renderList.slice(0);
  64376. }
  64377. return newTexture;
  64378. };
  64379. RenderTargetTexture.prototype.serialize = function () {
  64380. if (!this.name) {
  64381. return null;
  64382. }
  64383. var serializationObject = _super.prototype.serialize.call(this);
  64384. serializationObject.renderTargetSize = this.getRenderSize();
  64385. serializationObject.renderList = [];
  64386. if (this.renderList) {
  64387. for (var index = 0; index < this.renderList.length; index++) {
  64388. serializationObject.renderList.push(this.renderList[index].id);
  64389. }
  64390. }
  64391. return serializationObject;
  64392. };
  64393. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64394. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64395. var objBuffer = this.getInternalTexture();
  64396. var scene = this.getScene();
  64397. if (objBuffer && scene) {
  64398. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64399. }
  64400. };
  64401. RenderTargetTexture.prototype.dispose = function () {
  64402. if (this._postProcessManager) {
  64403. this._postProcessManager.dispose();
  64404. this._postProcessManager = null;
  64405. }
  64406. this.clearPostProcesses(true);
  64407. if (this._resizeObserver) {
  64408. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64409. this._resizeObserver = null;
  64410. }
  64411. this.renderList = null;
  64412. // Remove from custom render targets
  64413. var scene = this.getScene();
  64414. if (!scene) {
  64415. return;
  64416. }
  64417. var index = scene.customRenderTargets.indexOf(this);
  64418. if (index >= 0) {
  64419. scene.customRenderTargets.splice(index, 1);
  64420. }
  64421. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64422. var camera = _a[_i];
  64423. index = camera.customRenderTargets.indexOf(this);
  64424. if (index >= 0) {
  64425. camera.customRenderTargets.splice(index, 1);
  64426. }
  64427. }
  64428. _super.prototype.dispose.call(this);
  64429. };
  64430. RenderTargetTexture.prototype._rebuild = function () {
  64431. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64432. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64433. }
  64434. if (this._postProcessManager) {
  64435. this._postProcessManager._rebuild();
  64436. }
  64437. };
  64438. /**
  64439. * Clear the info related to rendering groups preventing retention point in material dispose.
  64440. */
  64441. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64442. if (this._renderingManager) {
  64443. this._renderingManager.freeRenderingGroups();
  64444. }
  64445. };
  64446. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64447. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64448. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64449. return RenderTargetTexture;
  64450. }(BABYLON.Texture));
  64451. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64452. })(BABYLON || (BABYLON = {}));
  64453. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64454. var BABYLON;
  64455. (function (BABYLON) {
  64456. ;
  64457. var MultiRenderTarget = /** @class */ (function (_super) {
  64458. __extends(MultiRenderTarget, _super);
  64459. function MultiRenderTarget(name, size, count, scene, options) {
  64460. var _this = this;
  64461. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64462. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64463. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64464. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64465. _this._engine = scene.getEngine();
  64466. if (!_this.isSupported) {
  64467. _this.dispose();
  64468. return;
  64469. }
  64470. var types = [];
  64471. var samplingModes = [];
  64472. for (var i = 0; i < count; i++) {
  64473. if (options && options.types && options.types[i] !== undefined) {
  64474. types.push(options.types[i]);
  64475. }
  64476. else {
  64477. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64478. }
  64479. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64480. samplingModes.push(options.samplingModes[i]);
  64481. }
  64482. else {
  64483. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64484. }
  64485. }
  64486. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64487. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64488. _this._size = size;
  64489. _this._multiRenderTargetOptions = {
  64490. samplingModes: samplingModes,
  64491. generateMipMaps: generateMipMaps,
  64492. generateDepthBuffer: generateDepthBuffer,
  64493. generateStencilBuffer: generateStencilBuffer,
  64494. generateDepthTexture: generateDepthTexture,
  64495. types: types,
  64496. textureCount: count
  64497. };
  64498. _this._createInternalTextures();
  64499. _this._createTextures();
  64500. return _this;
  64501. }
  64502. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64503. get: function () {
  64504. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64505. },
  64506. enumerable: true,
  64507. configurable: true
  64508. });
  64509. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64510. get: function () {
  64511. return this._textures;
  64512. },
  64513. enumerable: true,
  64514. configurable: true
  64515. });
  64516. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64517. get: function () {
  64518. return this._textures[this._textures.length - 1];
  64519. },
  64520. enumerable: true,
  64521. configurable: true
  64522. });
  64523. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64524. set: function (wrap) {
  64525. if (this._textures) {
  64526. for (var i = 0; i < this._textures.length; i++) {
  64527. this._textures[i].wrapU = wrap;
  64528. }
  64529. }
  64530. },
  64531. enumerable: true,
  64532. configurable: true
  64533. });
  64534. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64535. set: function (wrap) {
  64536. if (this._textures) {
  64537. for (var i = 0; i < this._textures.length; i++) {
  64538. this._textures[i].wrapV = wrap;
  64539. }
  64540. }
  64541. },
  64542. enumerable: true,
  64543. configurable: true
  64544. });
  64545. MultiRenderTarget.prototype._rebuild = function () {
  64546. this.releaseInternalTextures();
  64547. this._createInternalTextures();
  64548. for (var i = 0; i < this._internalTextures.length; i++) {
  64549. var texture = this._textures[i];
  64550. texture._texture = this._internalTextures[i];
  64551. }
  64552. // Keeps references to frame buffer and stencil/depth buffer
  64553. this._texture = this._internalTextures[0];
  64554. };
  64555. MultiRenderTarget.prototype._createInternalTextures = function () {
  64556. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64557. };
  64558. MultiRenderTarget.prototype._createTextures = function () {
  64559. this._textures = [];
  64560. for (var i = 0; i < this._internalTextures.length; i++) {
  64561. var texture = new BABYLON.Texture(null, this.getScene());
  64562. texture._texture = this._internalTextures[i];
  64563. this._textures.push(texture);
  64564. }
  64565. // Keeps references to frame buffer and stencil/depth buffer
  64566. this._texture = this._internalTextures[0];
  64567. };
  64568. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64569. get: function () {
  64570. return this._samples;
  64571. },
  64572. set: function (value) {
  64573. if (this._samples === value) {
  64574. return;
  64575. }
  64576. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64577. },
  64578. enumerable: true,
  64579. configurable: true
  64580. });
  64581. MultiRenderTarget.prototype.resize = function (size) {
  64582. this.releaseInternalTextures();
  64583. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64584. this._createInternalTextures();
  64585. };
  64586. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64587. var _this = this;
  64588. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64589. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64590. });
  64591. };
  64592. MultiRenderTarget.prototype.dispose = function () {
  64593. this.releaseInternalTextures();
  64594. _super.prototype.dispose.call(this);
  64595. };
  64596. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64597. if (!this._internalTextures) {
  64598. return;
  64599. }
  64600. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64601. if (this._internalTextures[i] !== undefined) {
  64602. this._internalTextures[i].dispose();
  64603. this._internalTextures.splice(i, 1);
  64604. }
  64605. }
  64606. };
  64607. return MultiRenderTarget;
  64608. }(BABYLON.RenderTargetTexture));
  64609. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64610. })(BABYLON || (BABYLON = {}));
  64611. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64612. var BABYLON;
  64613. (function (BABYLON) {
  64614. var MirrorTexture = /** @class */ (function (_super) {
  64615. __extends(MirrorTexture, _super);
  64616. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64617. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64619. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64620. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64621. _this.scene = scene;
  64622. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64623. _this._transformMatrix = BABYLON.Matrix.Zero();
  64624. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64625. _this._adaptiveBlurKernel = 0;
  64626. _this._blurKernelX = 0;
  64627. _this._blurKernelY = 0;
  64628. _this._blurRatio = 1.0;
  64629. _this.ignoreCameraViewport = true;
  64630. _this._updateGammaSpace();
  64631. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64632. _this._updateGammaSpace;
  64633. });
  64634. _this.onBeforeRenderObservable.add(function () {
  64635. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64636. _this._savedViewMatrix = scene.getViewMatrix();
  64637. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64638. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64639. scene.clipPlane = _this.mirrorPlane;
  64640. scene.getEngine().cullBackFaces = false;
  64641. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64642. });
  64643. _this.onAfterRenderObservable.add(function () {
  64644. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64645. scene.getEngine().cullBackFaces = true;
  64646. scene._mirroredCameraPosition = null;
  64647. delete scene.clipPlane;
  64648. });
  64649. return _this;
  64650. }
  64651. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64652. get: function () {
  64653. return this._blurRatio;
  64654. },
  64655. set: function (value) {
  64656. if (this._blurRatio === value) {
  64657. return;
  64658. }
  64659. this._blurRatio = value;
  64660. this._preparePostProcesses();
  64661. },
  64662. enumerable: true,
  64663. configurable: true
  64664. });
  64665. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64666. set: function (value) {
  64667. this._adaptiveBlurKernel = value;
  64668. this._autoComputeBlurKernel();
  64669. },
  64670. enumerable: true,
  64671. configurable: true
  64672. });
  64673. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64674. set: function (value) {
  64675. this.blurKernelX = value;
  64676. this.blurKernelY = value;
  64677. },
  64678. enumerable: true,
  64679. configurable: true
  64680. });
  64681. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64682. get: function () {
  64683. return this._blurKernelX;
  64684. },
  64685. set: function (value) {
  64686. if (this._blurKernelX === value) {
  64687. return;
  64688. }
  64689. this._blurKernelX = value;
  64690. this._preparePostProcesses();
  64691. },
  64692. enumerable: true,
  64693. configurable: true
  64694. });
  64695. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64696. get: function () {
  64697. return this._blurKernelY;
  64698. },
  64699. set: function (value) {
  64700. if (this._blurKernelY === value) {
  64701. return;
  64702. }
  64703. this._blurKernelY = value;
  64704. this._preparePostProcesses();
  64705. },
  64706. enumerable: true,
  64707. configurable: true
  64708. });
  64709. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64710. var engine = this.getScene().getEngine();
  64711. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64712. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64713. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64714. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64715. };
  64716. MirrorTexture.prototype._onRatioRescale = function () {
  64717. if (this._sizeRatio) {
  64718. this.resize(this._initialSizeParameter);
  64719. if (!this._adaptiveBlurKernel) {
  64720. this._preparePostProcesses();
  64721. }
  64722. }
  64723. if (this._adaptiveBlurKernel) {
  64724. this._autoComputeBlurKernel();
  64725. }
  64726. };
  64727. MirrorTexture.prototype._updateGammaSpace = function () {
  64728. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64729. };
  64730. MirrorTexture.prototype._preparePostProcesses = function () {
  64731. this.clearPostProcesses(true);
  64732. if (this._blurKernelX && this._blurKernelY) {
  64733. var engine = this.getScene().getEngine();
  64734. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64735. 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);
  64736. this._blurX.autoClear = false;
  64737. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64738. this._blurX.inputTexture = this._texture;
  64739. }
  64740. else {
  64741. this._blurX.alwaysForcePOT = true;
  64742. }
  64743. 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);
  64744. this._blurY.autoClear = false;
  64745. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64746. this.addPostProcess(this._blurX);
  64747. this.addPostProcess(this._blurY);
  64748. }
  64749. else {
  64750. if (this._blurY) {
  64751. this.removePostProcess(this._blurY);
  64752. this._blurY.dispose();
  64753. this._blurY = null;
  64754. }
  64755. if (this._blurX) {
  64756. this.removePostProcess(this._blurX);
  64757. this._blurX.dispose();
  64758. this._blurX = null;
  64759. }
  64760. }
  64761. };
  64762. MirrorTexture.prototype.clone = function () {
  64763. var scene = this.getScene();
  64764. if (!scene) {
  64765. return this;
  64766. }
  64767. var textureSize = this.getSize();
  64768. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64769. // Base texture
  64770. newTexture.hasAlpha = this.hasAlpha;
  64771. newTexture.level = this.level;
  64772. // Mirror Texture
  64773. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64774. if (this.renderList) {
  64775. newTexture.renderList = this.renderList.slice(0);
  64776. }
  64777. return newTexture;
  64778. };
  64779. MirrorTexture.prototype.serialize = function () {
  64780. if (!this.name) {
  64781. return null;
  64782. }
  64783. var serializationObject = _super.prototype.serialize.call(this);
  64784. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64785. return serializationObject;
  64786. };
  64787. MirrorTexture.prototype.dispose = function () {
  64788. _super.prototype.dispose.call(this);
  64789. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64790. };
  64791. return MirrorTexture;
  64792. }(BABYLON.RenderTargetTexture));
  64793. BABYLON.MirrorTexture = MirrorTexture;
  64794. })(BABYLON || (BABYLON = {}));
  64795. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64796. var BABYLON;
  64797. (function (BABYLON) {
  64798. /**
  64799. * Creates a refraction texture used by refraction channel of the standard material.
  64800. * @param name the texture name
  64801. * @param size size of the underlying texture
  64802. * @param scene root scene
  64803. */
  64804. var RefractionTexture = /** @class */ (function (_super) {
  64805. __extends(RefractionTexture, _super);
  64806. function RefractionTexture(name, size, scene, generateMipMaps) {
  64807. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64808. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64809. _this.depth = 2.0;
  64810. _this.onBeforeRenderObservable.add(function () {
  64811. scene.clipPlane = _this.refractionPlane;
  64812. });
  64813. _this.onAfterRenderObservable.add(function () {
  64814. delete scene.clipPlane;
  64815. });
  64816. return _this;
  64817. }
  64818. RefractionTexture.prototype.clone = function () {
  64819. var scene = this.getScene();
  64820. if (!scene) {
  64821. return this;
  64822. }
  64823. var textureSize = this.getSize();
  64824. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64825. // Base texture
  64826. newTexture.hasAlpha = this.hasAlpha;
  64827. newTexture.level = this.level;
  64828. // Refraction Texture
  64829. newTexture.refractionPlane = this.refractionPlane.clone();
  64830. if (this.renderList) {
  64831. newTexture.renderList = this.renderList.slice(0);
  64832. }
  64833. newTexture.depth = this.depth;
  64834. return newTexture;
  64835. };
  64836. RefractionTexture.prototype.serialize = function () {
  64837. if (!this.name) {
  64838. return null;
  64839. }
  64840. var serializationObject = _super.prototype.serialize.call(this);
  64841. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64842. serializationObject.depth = this.depth;
  64843. return serializationObject;
  64844. };
  64845. return RefractionTexture;
  64846. }(BABYLON.RenderTargetTexture));
  64847. BABYLON.RefractionTexture = RefractionTexture;
  64848. })(BABYLON || (BABYLON = {}));
  64849. //# sourceMappingURL=babylon.refractionTexture.js.map
  64850. var BABYLON;
  64851. (function (BABYLON) {
  64852. /**
  64853. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64854. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64855. */
  64856. var DynamicTexture = /** @class */ (function (_super) {
  64857. __extends(DynamicTexture, _super);
  64858. /**
  64859. * Creates a {BABYLON.DynamicTexture}
  64860. * @param name defines the name of the texture
  64861. * @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
  64862. * @param scene defines the scene where you want the texture
  64863. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64864. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64865. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64866. */
  64867. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64868. if (scene === void 0) { scene = null; }
  64869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64870. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64871. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64872. _this.name = name;
  64873. _this._engine = _this.getScene().getEngine();
  64874. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64875. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64876. _this._generateMipMaps = generateMipMaps;
  64877. if (options.getContext) {
  64878. _this._canvas = options;
  64879. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64880. }
  64881. else {
  64882. _this._canvas = document.createElement("canvas");
  64883. if (options.width || options.width === 0) {
  64884. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64885. }
  64886. else {
  64887. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64888. }
  64889. }
  64890. var textureSize = _this.getSize();
  64891. _this._canvas.width = textureSize.width;
  64892. _this._canvas.height = textureSize.height;
  64893. _this._context = _this._canvas.getContext("2d");
  64894. return _this;
  64895. }
  64896. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64897. /**
  64898. * Gets the current state of canRescale
  64899. */
  64900. get: function () {
  64901. return true;
  64902. },
  64903. enumerable: true,
  64904. configurable: true
  64905. });
  64906. DynamicTexture.prototype._recreate = function (textureSize) {
  64907. this._canvas.width = textureSize.width;
  64908. this._canvas.height = textureSize.height;
  64909. this.releaseInternalTexture();
  64910. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64911. };
  64912. /**
  64913. * Scales the texture
  64914. * @param ratio the scale factor to apply to both width and height
  64915. */
  64916. DynamicTexture.prototype.scale = function (ratio) {
  64917. var textureSize = this.getSize();
  64918. textureSize.width *= ratio;
  64919. textureSize.height *= ratio;
  64920. this._recreate(textureSize);
  64921. };
  64922. /**
  64923. * Resizes the texture
  64924. * @param width the new width
  64925. * @param height the new height
  64926. */
  64927. DynamicTexture.prototype.scaleTo = function (width, height) {
  64928. var textureSize = this.getSize();
  64929. textureSize.width = width;
  64930. textureSize.height = height;
  64931. this._recreate(textureSize);
  64932. };
  64933. /**
  64934. * Gets the context of the canvas used by the texture
  64935. * @returns the canvas context of the dynamic texture
  64936. */
  64937. DynamicTexture.prototype.getContext = function () {
  64938. return this._context;
  64939. };
  64940. /**
  64941. * Clears the texture
  64942. */
  64943. DynamicTexture.prototype.clear = function () {
  64944. var size = this.getSize();
  64945. this._context.fillRect(0, 0, size.width, size.height);
  64946. };
  64947. /**
  64948. * Updates the texture
  64949. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64950. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64951. */
  64952. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64953. if (premulAlpha === void 0) { premulAlpha = false; }
  64954. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64955. };
  64956. /**
  64957. * Draws text onto the texture
  64958. * @param text defines the text to be drawn
  64959. * @param x defines the placement of the text from the left
  64960. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64961. * @param font defines the font to be used with font-style, font-size, font-name
  64962. * @param color defines the color used for the text
  64963. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64964. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64965. * @param update defines whether texture is immediately update (default is true)
  64966. */
  64967. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64968. if (update === void 0) { update = true; }
  64969. var size = this.getSize();
  64970. if (clearColor) {
  64971. this._context.fillStyle = clearColor;
  64972. this._context.fillRect(0, 0, size.width, size.height);
  64973. }
  64974. this._context.font = font;
  64975. if (x === null || x === undefined) {
  64976. var textSize = this._context.measureText(text);
  64977. x = (size.width - textSize.width) / 2;
  64978. }
  64979. if (y === null || y === undefined) {
  64980. var fontSize = parseInt((font.replace(/\D/g, '')));
  64981. y = (size.height / 2) + (fontSize / 3.65);
  64982. }
  64983. this._context.fillStyle = color;
  64984. this._context.fillText(text, x, y);
  64985. if (update) {
  64986. this.update(invertY);
  64987. }
  64988. };
  64989. /**
  64990. * Clones the texture
  64991. * @returns the clone of the texture.
  64992. */
  64993. DynamicTexture.prototype.clone = function () {
  64994. var scene = this.getScene();
  64995. if (!scene) {
  64996. return this;
  64997. }
  64998. var textureSize = this.getSize();
  64999. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65000. // Base texture
  65001. newTexture.hasAlpha = this.hasAlpha;
  65002. newTexture.level = this.level;
  65003. // Dynamic Texture
  65004. newTexture.wrapU = this.wrapU;
  65005. newTexture.wrapV = this.wrapV;
  65006. return newTexture;
  65007. };
  65008. /** @hidden */
  65009. DynamicTexture.prototype._rebuild = function () {
  65010. this.update();
  65011. };
  65012. return DynamicTexture;
  65013. }(BABYLON.Texture));
  65014. BABYLON.DynamicTexture = DynamicTexture;
  65015. })(BABYLON || (BABYLON = {}));
  65016. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65017. var BABYLON;
  65018. (function (BABYLON) {
  65019. var VideoTexture = /** @class */ (function (_super) {
  65020. __extends(VideoTexture, _super);
  65021. /**
  65022. * Creates a video texture.
  65023. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65024. * @param {string | null} name optional name, will detect from video source, if not defined
  65025. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65026. * @param {BABYLON.Scene} scene is obviously the current scene.
  65027. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65028. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65029. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65030. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65031. */
  65032. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65033. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65034. if (invertY === void 0) { invertY = false; }
  65035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65036. if (settings === void 0) { settings = {
  65037. autoPlay: true,
  65038. loop: true,
  65039. autoUpdateTexture: true,
  65040. }; }
  65041. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65042. _this._stillImageCaptured = false;
  65043. _this._createInternalTexture = function () {
  65044. if (_this._texture != null) {
  65045. return;
  65046. }
  65047. if (!_this._engine.needPOTTextures ||
  65048. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65049. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65050. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65051. }
  65052. else {
  65053. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65054. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65055. _this._generateMipMaps = false;
  65056. }
  65057. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65058. if (!_this.video.autoplay) {
  65059. var oldHandler_1 = _this.video.onplaying;
  65060. _this.video.onplaying = function () {
  65061. _this.video.onplaying = oldHandler_1;
  65062. _this._texture.isReady = true;
  65063. _this._updateInternalTexture();
  65064. _this.video.pause();
  65065. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65066. _this.onLoadObservable.notifyObservers(_this);
  65067. }
  65068. };
  65069. _this.video.play();
  65070. }
  65071. else {
  65072. _this._texture.isReady = true;
  65073. _this._updateInternalTexture();
  65074. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65075. _this.onLoadObservable.notifyObservers(_this);
  65076. }
  65077. }
  65078. };
  65079. _this.reset = function () {
  65080. if (_this._texture == null) {
  65081. return;
  65082. }
  65083. _this._texture.dispose();
  65084. _this._texture = null;
  65085. };
  65086. _this._updateInternalTexture = function (e) {
  65087. if (_this._texture == null || !_this._texture.isReady) {
  65088. return;
  65089. }
  65090. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65091. return;
  65092. }
  65093. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65094. };
  65095. _this._engine = _this.getScene().getEngine();
  65096. _this._generateMipMaps = generateMipMaps;
  65097. _this._samplingMode = samplingMode;
  65098. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65099. _this.name = name || _this._getName(src);
  65100. _this.video = _this._getVideo(src);
  65101. if (settings.autoPlay !== undefined) {
  65102. _this.video.autoplay = settings.autoPlay;
  65103. }
  65104. if (settings.loop !== undefined) {
  65105. _this.video.loop = settings.loop;
  65106. }
  65107. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65108. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65109. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65110. _this.video.addEventListener("emptied", _this.reset);
  65111. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65112. _this._createInternalTexture();
  65113. }
  65114. return _this;
  65115. }
  65116. VideoTexture.prototype._getName = function (src) {
  65117. if (src instanceof HTMLVideoElement) {
  65118. return src.currentSrc;
  65119. }
  65120. if (typeof src === "object") {
  65121. return src.toString();
  65122. }
  65123. return src;
  65124. };
  65125. ;
  65126. VideoTexture.prototype._getVideo = function (src) {
  65127. if (src instanceof HTMLVideoElement) {
  65128. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65129. return src;
  65130. }
  65131. var video = document.createElement("video");
  65132. if (typeof src === "string") {
  65133. BABYLON.Tools.SetCorsBehavior(src, video);
  65134. video.src = src;
  65135. }
  65136. else {
  65137. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65138. src.forEach(function (url) {
  65139. var source = document.createElement("source");
  65140. source.src = url;
  65141. video.appendChild(source);
  65142. });
  65143. }
  65144. return video;
  65145. };
  65146. ;
  65147. /**
  65148. * Internal method to initiate `update`.
  65149. */
  65150. VideoTexture.prototype._rebuild = function () {
  65151. this.update();
  65152. };
  65153. /**
  65154. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65155. */
  65156. VideoTexture.prototype.update = function () {
  65157. if (!this.autoUpdateTexture) {
  65158. // Expecting user to call `updateTexture` manually
  65159. return;
  65160. }
  65161. this.updateTexture(true);
  65162. };
  65163. /**
  65164. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65165. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65166. */
  65167. VideoTexture.prototype.updateTexture = function (isVisible) {
  65168. if (!isVisible) {
  65169. return;
  65170. }
  65171. if (this.video.paused && this._stillImageCaptured) {
  65172. return;
  65173. }
  65174. this._stillImageCaptured = true;
  65175. this._updateInternalTexture();
  65176. };
  65177. /**
  65178. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65179. * @param url New url.
  65180. */
  65181. VideoTexture.prototype.updateURL = function (url) {
  65182. this.video.src = url;
  65183. };
  65184. VideoTexture.prototype.dispose = function () {
  65185. _super.prototype.dispose.call(this);
  65186. this.video.removeEventListener("canplay", this._createInternalTexture);
  65187. this.video.removeEventListener("paused", this._updateInternalTexture);
  65188. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65189. this.video.removeEventListener("emptied", this.reset);
  65190. this.video.pause();
  65191. };
  65192. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65193. var video = document.createElement("video");
  65194. var constraintsDeviceId;
  65195. if (constraints && constraints.deviceId) {
  65196. constraintsDeviceId = {
  65197. exact: constraints.deviceId,
  65198. };
  65199. }
  65200. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65201. if (navigator.mediaDevices) {
  65202. navigator.mediaDevices.getUserMedia({ video: constraints })
  65203. .then(function (stream) {
  65204. if (video.mozSrcObject !== undefined) {
  65205. // hack for Firefox < 19
  65206. video.mozSrcObject = stream;
  65207. }
  65208. else {
  65209. video.srcObject = stream;
  65210. }
  65211. var onPlaying = function () {
  65212. if (onReady) {
  65213. onReady(new VideoTexture("video", video, scene, true, true));
  65214. }
  65215. video.removeEventListener("playing", onPlaying);
  65216. };
  65217. video.addEventListener("playing", onPlaying);
  65218. video.play();
  65219. })
  65220. .catch(function (err) {
  65221. BABYLON.Tools.Error(err.name);
  65222. });
  65223. }
  65224. else {
  65225. navigator.getUserMedia =
  65226. navigator.getUserMedia ||
  65227. navigator.webkitGetUserMedia ||
  65228. navigator.mozGetUserMedia ||
  65229. navigator.msGetUserMedia;
  65230. if (navigator.getUserMedia) {
  65231. navigator.getUserMedia({
  65232. video: {
  65233. deviceId: constraintsDeviceId,
  65234. width: {
  65235. min: (constraints && constraints.minWidth) || 256,
  65236. max: (constraints && constraints.maxWidth) || 640,
  65237. },
  65238. height: {
  65239. min: (constraints && constraints.minHeight) || 256,
  65240. max: (constraints && constraints.maxHeight) || 480,
  65241. },
  65242. },
  65243. }, function (stream) {
  65244. if (video.mozSrcObject !== undefined) {
  65245. // hack for Firefox < 19
  65246. video.mozSrcObject = stream;
  65247. }
  65248. else {
  65249. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65250. }
  65251. video.play();
  65252. if (onReady) {
  65253. onReady(new VideoTexture("video", video, scene, true, true));
  65254. }
  65255. }, function (e) {
  65256. BABYLON.Tools.Error(e.name);
  65257. });
  65258. }
  65259. }
  65260. };
  65261. return VideoTexture;
  65262. }(BABYLON.Texture));
  65263. BABYLON.VideoTexture = VideoTexture;
  65264. })(BABYLON || (BABYLON = {}));
  65265. //# sourceMappingURL=babylon.videoTexture.js.map
  65266. var BABYLON;
  65267. (function (BABYLON) {
  65268. var RawTexture = /** @class */ (function (_super) {
  65269. __extends(RawTexture, _super);
  65270. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65271. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65272. if (invertY === void 0) { invertY = false; }
  65273. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65274. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65275. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65276. _this.format = format;
  65277. _this._engine = scene.getEngine();
  65278. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65279. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65280. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65281. return _this;
  65282. }
  65283. RawTexture.prototype.update = function (data) {
  65284. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65285. };
  65286. // Statics
  65287. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65288. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65289. if (invertY === void 0) { invertY = false; }
  65290. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65291. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65292. };
  65293. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65294. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65295. if (invertY === void 0) { invertY = false; }
  65296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65297. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65298. };
  65299. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65300. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65301. if (invertY === void 0) { invertY = false; }
  65302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65303. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65304. };
  65305. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65306. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65307. if (invertY === void 0) { invertY = false; }
  65308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65309. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65310. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65311. };
  65312. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65313. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65314. if (invertY === void 0) { invertY = false; }
  65315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65316. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65317. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65318. };
  65319. return RawTexture;
  65320. }(BABYLON.Texture));
  65321. BABYLON.RawTexture = RawTexture;
  65322. })(BABYLON || (BABYLON = {}));
  65323. //# sourceMappingURL=babylon.rawTexture.js.map
  65324. var BABYLON;
  65325. (function (BABYLON) {
  65326. /**
  65327. * Class used to store 3D textures containing user data
  65328. */
  65329. var RawTexture3D = /** @class */ (function (_super) {
  65330. __extends(RawTexture3D, _super);
  65331. /**
  65332. * Create a new RawTexture3D
  65333. * @param data defines the data of the texture
  65334. * @param width defines the width of the texture
  65335. * @param height defines the height of the texture
  65336. * @param depth defines the depth of the texture
  65337. * @param format defines the texture format to use
  65338. * @param scene defines the hosting scene
  65339. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65340. * @param invertY defines if texture must be stored with Y axis inverted
  65341. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65342. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65343. */
  65344. function RawTexture3D(data, width, height, depth,
  65345. /** Gets or sets the texture format to use */
  65346. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65347. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65348. if (invertY === void 0) { invertY = false; }
  65349. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65350. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65351. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65352. _this.format = format;
  65353. _this._engine = scene.getEngine();
  65354. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65355. _this.is3D = true;
  65356. return _this;
  65357. }
  65358. /**
  65359. * Update the texture with new data
  65360. * @param data defines the data to store in the texture
  65361. */
  65362. RawTexture3D.prototype.update = function (data) {
  65363. if (!this._texture) {
  65364. return;
  65365. }
  65366. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65367. };
  65368. return RawTexture3D;
  65369. }(BABYLON.Texture));
  65370. BABYLON.RawTexture3D = RawTexture3D;
  65371. })(BABYLON || (BABYLON = {}));
  65372. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65373. var BABYLON;
  65374. (function (BABYLON) {
  65375. /**
  65376. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65377. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65378. */
  65379. var PostProcess = /** @class */ (function () {
  65380. /**
  65381. * Creates a new instance PostProcess
  65382. * @param name The name of the PostProcess.
  65383. * @param fragmentUrl The url of the fragment shader to be used.
  65384. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65385. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65386. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65387. * @param camera The camera to apply the render pass to.
  65388. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65389. * @param engine The engine which the post process will be applied. (default: current engine)
  65390. * @param reusable If the post process can be reused on the same frame. (default: false)
  65391. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65392. * @param textureType Type of textures used when performing the post process. (default: 0)
  65393. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65394. * @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
  65395. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65396. */
  65397. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65398. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65399. if (defines === void 0) { defines = null; }
  65400. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65401. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65402. if (blockCompilation === void 0) { blockCompilation = false; }
  65403. this.name = name;
  65404. /**
  65405. * Width of the texture to apply the post process on
  65406. */
  65407. this.width = -1;
  65408. /**
  65409. * Height of the texture to apply the post process on
  65410. */
  65411. this.height = -1;
  65412. /**
  65413. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65414. */
  65415. this._outputTexture = null;
  65416. /**
  65417. * If the buffer needs to be cleared before applying the post process. (default: true)
  65418. * Should be set to false if shader will overwrite all previous pixels.
  65419. */
  65420. this.autoClear = true;
  65421. /**
  65422. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65423. */
  65424. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65425. /**
  65426. * Animations to be used for the post processing
  65427. */
  65428. this.animations = new Array();
  65429. /**
  65430. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65431. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65432. */
  65433. this.enablePixelPerfectMode = false;
  65434. /**
  65435. * Force the postprocess to be applied without taking in account viewport
  65436. */
  65437. this.forceFullscreenViewport = true;
  65438. /**
  65439. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65440. *
  65441. * | Value | Type | Description |
  65442. * | ----- | ----------------------------------- | ----------- |
  65443. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65444. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65445. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65446. *
  65447. */
  65448. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65449. /**
  65450. * Force textures to be a power of two (default: false)
  65451. */
  65452. this.alwaysForcePOT = false;
  65453. /**
  65454. * Number of sample textures (default: 1)
  65455. */
  65456. this.samples = 1;
  65457. /**
  65458. * Modify the scale of the post process to be the same as the viewport (default: false)
  65459. */
  65460. this.adaptScaleToCurrentViewport = false;
  65461. this._reusable = false;
  65462. /**
  65463. * Smart array of input and output textures for the post process.
  65464. */
  65465. this._textures = new BABYLON.SmartArray(2);
  65466. /**
  65467. * The index in _textures that corresponds to the output texture.
  65468. */
  65469. this._currentRenderTextureInd = 0;
  65470. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65471. this._texelSize = BABYLON.Vector2.Zero();
  65472. // Events
  65473. /**
  65474. * An event triggered when the postprocess is activated.
  65475. */
  65476. this.onActivateObservable = new BABYLON.Observable();
  65477. /**
  65478. * An event triggered when the postprocess changes its size.
  65479. */
  65480. this.onSizeChangedObservable = new BABYLON.Observable();
  65481. /**
  65482. * An event triggered when the postprocess applies its effect.
  65483. */
  65484. this.onApplyObservable = new BABYLON.Observable();
  65485. /**
  65486. * An event triggered before rendering the postprocess
  65487. */
  65488. this.onBeforeRenderObservable = new BABYLON.Observable();
  65489. /**
  65490. * An event triggered after rendering the postprocess
  65491. */
  65492. this.onAfterRenderObservable = new BABYLON.Observable();
  65493. if (camera != null) {
  65494. this._camera = camera;
  65495. this._scene = camera.getScene();
  65496. camera.attachPostProcess(this);
  65497. this._engine = this._scene.getEngine();
  65498. this._scene.postProcesses.push(this);
  65499. }
  65500. else if (engine) {
  65501. this._engine = engine;
  65502. this._engine.postProcesses.push(this);
  65503. }
  65504. this._options = options;
  65505. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65506. this._reusable = reusable || false;
  65507. this._textureType = textureType;
  65508. this._samplers = samplers || [];
  65509. this._samplers.push("textureSampler");
  65510. this._fragmentUrl = fragmentUrl;
  65511. this._vertexUrl = vertexUrl;
  65512. this._parameters = parameters || [];
  65513. this._parameters.push("scale");
  65514. this._indexParameters = indexParameters;
  65515. if (!blockCompilation) {
  65516. this.updateEffect(defines);
  65517. }
  65518. }
  65519. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65520. /**
  65521. * A function that is added to the onActivateObservable
  65522. */
  65523. set: function (callback) {
  65524. if (this._onActivateObserver) {
  65525. this.onActivateObservable.remove(this._onActivateObserver);
  65526. }
  65527. if (callback) {
  65528. this._onActivateObserver = this.onActivateObservable.add(callback);
  65529. }
  65530. },
  65531. enumerable: true,
  65532. configurable: true
  65533. });
  65534. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65535. /**
  65536. * A function that is added to the onSizeChangedObservable
  65537. */
  65538. set: function (callback) {
  65539. if (this._onSizeChangedObserver) {
  65540. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65541. }
  65542. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65543. },
  65544. enumerable: true,
  65545. configurable: true
  65546. });
  65547. Object.defineProperty(PostProcess.prototype, "onApply", {
  65548. /**
  65549. * A function that is added to the onApplyObservable
  65550. */
  65551. set: function (callback) {
  65552. if (this._onApplyObserver) {
  65553. this.onApplyObservable.remove(this._onApplyObserver);
  65554. }
  65555. this._onApplyObserver = this.onApplyObservable.add(callback);
  65556. },
  65557. enumerable: true,
  65558. configurable: true
  65559. });
  65560. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65561. /**
  65562. * A function that is added to the onBeforeRenderObservable
  65563. */
  65564. set: function (callback) {
  65565. if (this._onBeforeRenderObserver) {
  65566. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65567. }
  65568. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65574. /**
  65575. * A function that is added to the onAfterRenderObservable
  65576. */
  65577. set: function (callback) {
  65578. if (this._onAfterRenderObserver) {
  65579. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65580. }
  65581. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65582. },
  65583. enumerable: true,
  65584. configurable: true
  65585. });
  65586. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65587. /**
  65588. * 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
  65589. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65590. */
  65591. get: function () {
  65592. return this._textures.data[this._currentRenderTextureInd];
  65593. },
  65594. set: function (value) {
  65595. this._forcedOutputTexture = value;
  65596. },
  65597. enumerable: true,
  65598. configurable: true
  65599. });
  65600. /**
  65601. * Gets the camera which post process is applied to.
  65602. * @returns The camera the post process is applied to.
  65603. */
  65604. PostProcess.prototype.getCamera = function () {
  65605. return this._camera;
  65606. };
  65607. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65608. /**
  65609. * Gets the texel size of the postprocess.
  65610. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65611. */
  65612. get: function () {
  65613. if (this._shareOutputWithPostProcess) {
  65614. return this._shareOutputWithPostProcess.texelSize;
  65615. }
  65616. if (this._forcedOutputTexture) {
  65617. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65618. }
  65619. return this._texelSize;
  65620. },
  65621. enumerable: true,
  65622. configurable: true
  65623. });
  65624. /**
  65625. * Gets the engine which this post process belongs to.
  65626. * @returns The engine the post process was enabled with.
  65627. */
  65628. PostProcess.prototype.getEngine = function () {
  65629. return this._engine;
  65630. };
  65631. /**
  65632. * The effect that is created when initializing the post process.
  65633. * @returns The created effect corrisponding the the postprocess.
  65634. */
  65635. PostProcess.prototype.getEffect = function () {
  65636. return this._effect;
  65637. };
  65638. /**
  65639. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65640. * @param postProcess The post process to share the output with.
  65641. * @returns This post process.
  65642. */
  65643. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65644. this._disposeTextures();
  65645. this._shareOutputWithPostProcess = postProcess;
  65646. return this;
  65647. };
  65648. /**
  65649. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65650. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65651. */
  65652. PostProcess.prototype.useOwnOutput = function () {
  65653. if (this._textures.length == 0) {
  65654. this._textures = new BABYLON.SmartArray(2);
  65655. }
  65656. this._shareOutputWithPostProcess = null;
  65657. };
  65658. /**
  65659. * Updates the effect with the current post process compile time values and recompiles the shader.
  65660. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65661. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65662. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65663. * @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
  65664. * @param onCompiled Called when the shader has been compiled.
  65665. * @param onError Called if there is an error when compiling a shader.
  65666. */
  65667. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65668. if (defines === void 0) { defines = null; }
  65669. if (uniforms === void 0) { uniforms = null; }
  65670. if (samplers === void 0) { samplers = null; }
  65671. 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);
  65672. };
  65673. /**
  65674. * The post process is reusable if it can be used multiple times within one frame.
  65675. * @returns If the post process is reusable
  65676. */
  65677. PostProcess.prototype.isReusable = function () {
  65678. return this._reusable;
  65679. };
  65680. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65681. PostProcess.prototype.markTextureDirty = function () {
  65682. this.width = -1;
  65683. };
  65684. /**
  65685. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65686. * 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.
  65687. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65688. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65689. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65690. * @returns The target texture that was bound to be written to.
  65691. */
  65692. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65693. var _this = this;
  65694. if (sourceTexture === void 0) { sourceTexture = null; }
  65695. camera = camera || this._camera;
  65696. var scene = camera.getScene();
  65697. var engine = scene.getEngine();
  65698. var maxSize = engine.getCaps().maxTextureSize;
  65699. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65700. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65701. // 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
  65702. var webVRCamera = camera.parent;
  65703. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65704. requiredWidth /= 2;
  65705. }
  65706. var desiredWidth = (this._options.width || requiredWidth);
  65707. var desiredHeight = this._options.height || requiredHeight;
  65708. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65709. if (this.adaptScaleToCurrentViewport) {
  65710. var currentViewport = engine.currentViewport;
  65711. if (currentViewport) {
  65712. desiredWidth *= currentViewport.width;
  65713. desiredHeight *= currentViewport.height;
  65714. }
  65715. }
  65716. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65717. if (!this._options.width) {
  65718. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65719. }
  65720. if (!this._options.height) {
  65721. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65722. }
  65723. }
  65724. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65725. if (this._textures.length > 0) {
  65726. for (var i = 0; i < this._textures.length; i++) {
  65727. this._engine._releaseTexture(this._textures.data[i]);
  65728. }
  65729. this._textures.reset();
  65730. }
  65731. this.width = desiredWidth;
  65732. this.height = desiredHeight;
  65733. var textureSize = { width: this.width, height: this.height };
  65734. var textureOptions = {
  65735. generateMipMaps: false,
  65736. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65737. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65738. samplingMode: this.renderTargetSamplingMode,
  65739. type: this._textureType
  65740. };
  65741. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65742. if (this._reusable) {
  65743. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65744. }
  65745. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65746. this.onSizeChangedObservable.notifyObservers(this);
  65747. }
  65748. this._textures.forEach(function (texture) {
  65749. if (texture.samples !== _this.samples) {
  65750. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65751. }
  65752. });
  65753. }
  65754. var target;
  65755. if (this._shareOutputWithPostProcess) {
  65756. target = this._shareOutputWithPostProcess.inputTexture;
  65757. }
  65758. else if (this._forcedOutputTexture) {
  65759. target = this._forcedOutputTexture;
  65760. this.width = this._forcedOutputTexture.width;
  65761. this.height = this._forcedOutputTexture.height;
  65762. }
  65763. else {
  65764. target = this.inputTexture;
  65765. }
  65766. // Bind the input of this post process to be used as the output of the previous post process.
  65767. if (this.enablePixelPerfectMode) {
  65768. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65769. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65770. }
  65771. else {
  65772. this._scaleRatio.copyFromFloats(1, 1);
  65773. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65774. }
  65775. this.onActivateObservable.notifyObservers(camera);
  65776. // Clear
  65777. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65778. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65779. }
  65780. if (this._reusable) {
  65781. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65782. }
  65783. return target;
  65784. };
  65785. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65786. /**
  65787. * If the post process is supported.
  65788. */
  65789. get: function () {
  65790. return this._effect.isSupported;
  65791. },
  65792. enumerable: true,
  65793. configurable: true
  65794. });
  65795. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65796. /**
  65797. * The aspect ratio of the output texture.
  65798. */
  65799. get: function () {
  65800. if (this._shareOutputWithPostProcess) {
  65801. return this._shareOutputWithPostProcess.aspectRatio;
  65802. }
  65803. if (this._forcedOutputTexture) {
  65804. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65805. }
  65806. return this.width / this.height;
  65807. },
  65808. enumerable: true,
  65809. configurable: true
  65810. });
  65811. /**
  65812. * Get a value indicating if the post-process is ready to be used
  65813. * @returns true if the post-process is ready (shader is compiled)
  65814. */
  65815. PostProcess.prototype.isReady = function () {
  65816. return this._effect && this._effect.isReady();
  65817. };
  65818. /**
  65819. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65820. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65821. */
  65822. PostProcess.prototype.apply = function () {
  65823. // Check
  65824. if (!this._effect || !this._effect.isReady())
  65825. return null;
  65826. // States
  65827. this._engine.enableEffect(this._effect);
  65828. this._engine.setState(false);
  65829. this._engine.setDepthBuffer(false);
  65830. this._engine.setDepthWrite(false);
  65831. // Alpha
  65832. this._engine.setAlphaMode(this.alphaMode);
  65833. if (this.alphaConstants) {
  65834. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65835. }
  65836. // Bind the output texture of the preivous post process as the input to this post process.
  65837. var source;
  65838. if (this._shareOutputWithPostProcess) {
  65839. source = this._shareOutputWithPostProcess.inputTexture;
  65840. }
  65841. else if (this._forcedOutputTexture) {
  65842. source = this._forcedOutputTexture;
  65843. }
  65844. else {
  65845. source = this.inputTexture;
  65846. }
  65847. this._effect._bindTexture("textureSampler", source);
  65848. // Parameters
  65849. this._effect.setVector2("scale", this._scaleRatio);
  65850. this.onApplyObservable.notifyObservers(this._effect);
  65851. return this._effect;
  65852. };
  65853. PostProcess.prototype._disposeTextures = function () {
  65854. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65855. return;
  65856. }
  65857. if (this._textures.length > 0) {
  65858. for (var i = 0; i < this._textures.length; i++) {
  65859. this._engine._releaseTexture(this._textures.data[i]);
  65860. }
  65861. }
  65862. this._textures.dispose();
  65863. };
  65864. /**
  65865. * Disposes the post process.
  65866. * @param camera The camera to dispose the post process on.
  65867. */
  65868. PostProcess.prototype.dispose = function (camera) {
  65869. camera = camera || this._camera;
  65870. this._disposeTextures();
  65871. if (this._scene) {
  65872. var index_1 = this._scene.postProcesses.indexOf(this);
  65873. if (index_1 !== -1) {
  65874. this._scene.postProcesses.splice(index_1, 1);
  65875. }
  65876. }
  65877. else {
  65878. var index_2 = this._engine.postProcesses.indexOf(this);
  65879. if (index_2 !== -1) {
  65880. this._engine.postProcesses.splice(index_2, 1);
  65881. }
  65882. }
  65883. if (!camera) {
  65884. return;
  65885. }
  65886. camera.detachPostProcess(this);
  65887. var index = camera._postProcesses.indexOf(this);
  65888. if (index === 0 && camera._postProcesses.length > 0) {
  65889. var firstPostProcess = this._camera._getFirstPostProcess();
  65890. if (firstPostProcess) {
  65891. firstPostProcess.markTextureDirty();
  65892. }
  65893. }
  65894. this.onActivateObservable.clear();
  65895. this.onAfterRenderObservable.clear();
  65896. this.onApplyObservable.clear();
  65897. this.onBeforeRenderObservable.clear();
  65898. this.onSizeChangedObservable.clear();
  65899. };
  65900. return PostProcess;
  65901. }());
  65902. BABYLON.PostProcess = PostProcess;
  65903. })(BABYLON || (BABYLON = {}));
  65904. //# sourceMappingURL=babylon.postProcess.js.map
  65905. var BABYLON;
  65906. (function (BABYLON) {
  65907. var PassPostProcess = /** @class */ (function (_super) {
  65908. __extends(PassPostProcess, _super);
  65909. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65910. if (camera === void 0) { camera = null; }
  65911. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65912. if (blockCompilation === void 0) { blockCompilation = false; }
  65913. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65914. }
  65915. return PassPostProcess;
  65916. }(BABYLON.PostProcess));
  65917. BABYLON.PassPostProcess = PassPostProcess;
  65918. })(BABYLON || (BABYLON = {}));
  65919. //# sourceMappingURL=babylon.passPostProcess.js.map
  65920. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65921. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65922. s = arguments[i];
  65923. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65924. t[p] = s[p];
  65925. }
  65926. return t;
  65927. };
  65928. var BABYLON;
  65929. (function (BABYLON) {
  65930. /**
  65931. * Default implementation IShadowGenerator.
  65932. * This is the main object responsible of generating shadows in the framework.
  65933. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65934. */
  65935. var ShadowGenerator = /** @class */ (function () {
  65936. /**
  65937. * Creates a ShadowGenerator object.
  65938. * A ShadowGenerator is the required tool to use the shadows.
  65939. * Each light casting shadows needs to use its own ShadowGenerator.
  65940. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65941. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65942. * @param light The light object generating the shadows.
  65943. * @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.
  65944. */
  65945. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65946. this._bias = 0.00005;
  65947. this._normalBias = 0;
  65948. this._blurBoxOffset = 1;
  65949. this._blurScale = 2;
  65950. this._blurKernel = 1;
  65951. this._useKernelBlur = false;
  65952. this._filter = ShadowGenerator.FILTER_NONE;
  65953. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65954. this._contactHardeningLightSizeUVRatio = 0.1;
  65955. this._darkness = 0;
  65956. this._transparencyShadow = false;
  65957. /**
  65958. * Controls the extent to which the shadows fade out at the edge of the frustum
  65959. * Used only by directionals and spots
  65960. */
  65961. this.frustumEdgeFalloff = 0;
  65962. /**
  65963. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65964. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65965. * It might on the other hand introduce peter panning.
  65966. */
  65967. this.forceBackFacesOnly = false;
  65968. this._lightDirection = BABYLON.Vector3.Zero();
  65969. this._viewMatrix = BABYLON.Matrix.Zero();
  65970. this._projectionMatrix = BABYLON.Matrix.Zero();
  65971. this._transformMatrix = BABYLON.Matrix.Zero();
  65972. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65973. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65974. this._currentFaceIndex = 0;
  65975. this._currentFaceIndexCache = 0;
  65976. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65977. this._mapSize = mapSize;
  65978. this._light = light;
  65979. this._scene = light.getScene();
  65980. light._shadowGenerator = this;
  65981. // Texture type fallback from float to int if not supported.
  65982. var caps = this._scene.getEngine().getCaps();
  65983. if (!useFullFloatFirst) {
  65984. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65985. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65986. }
  65987. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65988. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65989. }
  65990. else {
  65991. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65992. }
  65993. }
  65994. else {
  65995. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65996. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65997. }
  65998. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65999. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66000. }
  66001. else {
  66002. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66003. }
  66004. }
  66005. this._initializeGenerator();
  66006. this._applyFilterValues();
  66007. }
  66008. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66009. /**
  66010. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66011. */
  66012. get: function () {
  66013. return this._bias;
  66014. },
  66015. /**
  66016. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66017. */
  66018. set: function (bias) {
  66019. this._bias = bias;
  66020. },
  66021. enumerable: true,
  66022. configurable: true
  66023. });
  66024. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66025. /**
  66026. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66027. */
  66028. get: function () {
  66029. return this._normalBias;
  66030. },
  66031. /**
  66032. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66033. */
  66034. set: function (normalBias) {
  66035. this._normalBias = normalBias;
  66036. },
  66037. enumerable: true,
  66038. configurable: true
  66039. });
  66040. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66041. /**
  66042. * Gets the blur box offset: offset applied during the blur pass.
  66043. * Only usefull if useKernelBlur = false
  66044. */
  66045. get: function () {
  66046. return this._blurBoxOffset;
  66047. },
  66048. /**
  66049. * Sets the blur box offset: offset applied during the blur pass.
  66050. * Only usefull if useKernelBlur = false
  66051. */
  66052. set: function (value) {
  66053. if (this._blurBoxOffset === value) {
  66054. return;
  66055. }
  66056. this._blurBoxOffset = value;
  66057. this._disposeBlurPostProcesses();
  66058. },
  66059. enumerable: true,
  66060. configurable: true
  66061. });
  66062. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66063. /**
  66064. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66065. * 2 means half of the size.
  66066. */
  66067. get: function () {
  66068. return this._blurScale;
  66069. },
  66070. /**
  66071. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66072. * 2 means half of the size.
  66073. */
  66074. set: function (value) {
  66075. if (this._blurScale === value) {
  66076. return;
  66077. }
  66078. this._blurScale = value;
  66079. this._disposeBlurPostProcesses();
  66080. },
  66081. enumerable: true,
  66082. configurable: true
  66083. });
  66084. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66085. /**
  66086. * Gets the blur kernel: kernel size of the blur pass.
  66087. * Only usefull if useKernelBlur = true
  66088. */
  66089. get: function () {
  66090. return this._blurKernel;
  66091. },
  66092. /**
  66093. * Sets the blur kernel: kernel size of the blur pass.
  66094. * Only usefull if useKernelBlur = true
  66095. */
  66096. set: function (value) {
  66097. if (this._blurKernel === value) {
  66098. return;
  66099. }
  66100. this._blurKernel = value;
  66101. this._disposeBlurPostProcesses();
  66102. },
  66103. enumerable: true,
  66104. configurable: true
  66105. });
  66106. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66107. /**
  66108. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66109. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66110. */
  66111. get: function () {
  66112. return this._useKernelBlur;
  66113. },
  66114. /**
  66115. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66116. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66117. */
  66118. set: function (value) {
  66119. if (this._useKernelBlur === value) {
  66120. return;
  66121. }
  66122. this._useKernelBlur = value;
  66123. this._disposeBlurPostProcesses();
  66124. },
  66125. enumerable: true,
  66126. configurable: true
  66127. });
  66128. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66129. /**
  66130. * Gets the depth scale used in ESM mode.
  66131. */
  66132. get: function () {
  66133. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66134. },
  66135. /**
  66136. * Sets the depth scale used in ESM mode.
  66137. * This can override the scale stored on the light.
  66138. */
  66139. set: function (value) {
  66140. this._depthScale = value;
  66141. },
  66142. enumerable: true,
  66143. configurable: true
  66144. });
  66145. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66146. /**
  66147. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66148. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66149. */
  66150. get: function () {
  66151. return this._filter;
  66152. },
  66153. /**
  66154. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66155. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66156. */
  66157. set: function (value) {
  66158. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66159. if (this._light.needCube()) {
  66160. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66161. this.useExponentialShadowMap = true;
  66162. return;
  66163. }
  66164. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66165. this.useCloseExponentialShadowMap = true;
  66166. return;
  66167. }
  66168. // PCF on cubemap would also be expensive
  66169. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66170. this.usePoissonSampling = true;
  66171. return;
  66172. }
  66173. }
  66174. // Weblg1 fallback for PCF.
  66175. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66176. if (this._scene.getEngine().webGLVersion === 1) {
  66177. this.usePoissonSampling = true;
  66178. return;
  66179. }
  66180. }
  66181. if (this._filter === value) {
  66182. return;
  66183. }
  66184. this._filter = value;
  66185. this._disposeBlurPostProcesses();
  66186. this._applyFilterValues();
  66187. this._light._markMeshesAsLightDirty();
  66188. },
  66189. enumerable: true,
  66190. configurable: true
  66191. });
  66192. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66193. /**
  66194. * Gets if the current filter is set to Poisson Sampling.
  66195. */
  66196. get: function () {
  66197. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66198. },
  66199. /**
  66200. * Sets the current filter to Poisson Sampling.
  66201. */
  66202. set: function (value) {
  66203. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66204. return;
  66205. }
  66206. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66207. },
  66208. enumerable: true,
  66209. configurable: true
  66210. });
  66211. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66212. /**
  66213. * Gets if the current filter is set to VSM.
  66214. * DEPRECATED. Should use useExponentialShadowMap instead.
  66215. */
  66216. get: function () {
  66217. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66218. return this.useExponentialShadowMap;
  66219. },
  66220. /**
  66221. * Sets the current filter is to VSM.
  66222. * DEPRECATED. Should use useExponentialShadowMap instead.
  66223. */
  66224. set: function (value) {
  66225. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66226. this.useExponentialShadowMap = value;
  66227. },
  66228. enumerable: true,
  66229. configurable: true
  66230. });
  66231. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66232. /**
  66233. * Gets if the current filter is set to blurred VSM.
  66234. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66235. */
  66236. get: function () {
  66237. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66238. return this.useBlurExponentialShadowMap;
  66239. },
  66240. /**
  66241. * Sets the current filter is to blurred VSM.
  66242. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66243. */
  66244. set: function (value) {
  66245. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66246. this.useBlurExponentialShadowMap = value;
  66247. },
  66248. enumerable: true,
  66249. configurable: true
  66250. });
  66251. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66252. /**
  66253. * Gets if the current filter is set to ESM.
  66254. */
  66255. get: function () {
  66256. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66257. },
  66258. /**
  66259. * Sets the current filter is to ESM.
  66260. */
  66261. set: function (value) {
  66262. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66263. return;
  66264. }
  66265. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66266. },
  66267. enumerable: true,
  66268. configurable: true
  66269. });
  66270. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66271. /**
  66272. * Gets if the current filter is set to filtered ESM.
  66273. */
  66274. get: function () {
  66275. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66276. },
  66277. /**
  66278. * Gets if the current filter is set to filtered ESM.
  66279. */
  66280. set: function (value) {
  66281. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66282. return;
  66283. }
  66284. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66285. },
  66286. enumerable: true,
  66287. configurable: true
  66288. });
  66289. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66290. /**
  66291. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66292. * exponential to prevent steep falloff artifacts).
  66293. */
  66294. get: function () {
  66295. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66296. },
  66297. /**
  66298. * Sets the current filter to "close ESM" (using the inverse of the
  66299. * exponential to prevent steep falloff artifacts).
  66300. */
  66301. set: function (value) {
  66302. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66303. return;
  66304. }
  66305. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66306. },
  66307. enumerable: true,
  66308. configurable: true
  66309. });
  66310. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66311. /**
  66312. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66313. * exponential to prevent steep falloff artifacts).
  66314. */
  66315. get: function () {
  66316. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66317. },
  66318. /**
  66319. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66320. * exponential to prevent steep falloff artifacts).
  66321. */
  66322. set: function (value) {
  66323. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66324. return;
  66325. }
  66326. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66327. },
  66328. enumerable: true,
  66329. configurable: true
  66330. });
  66331. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66332. /**
  66333. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66334. */
  66335. get: function () {
  66336. return this.filter === ShadowGenerator.FILTER_PCF;
  66337. },
  66338. /**
  66339. * Sets the current filter to "PCF" (percentage closer filtering).
  66340. */
  66341. set: function (value) {
  66342. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66343. return;
  66344. }
  66345. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66346. },
  66347. enumerable: true,
  66348. configurable: true
  66349. });
  66350. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66351. /**
  66352. * Gets the PCF or PCSS Quality.
  66353. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66354. */
  66355. get: function () {
  66356. return this._filteringQuality;
  66357. },
  66358. /**
  66359. * Sets the PCF or PCSS Quality.
  66360. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66361. */
  66362. set: function (filteringQuality) {
  66363. this._filteringQuality = filteringQuality;
  66364. },
  66365. enumerable: true,
  66366. configurable: true
  66367. });
  66368. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66369. /**
  66370. * Gets if the current filter is set to "PCSS" (contact hardening).
  66371. */
  66372. get: function () {
  66373. return this.filter === ShadowGenerator.FILTER_PCSS;
  66374. },
  66375. /**
  66376. * Sets the current filter to "PCSS" (contact hardening).
  66377. */
  66378. set: function (value) {
  66379. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66380. return;
  66381. }
  66382. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66383. },
  66384. enumerable: true,
  66385. configurable: true
  66386. });
  66387. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66388. /**
  66389. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66390. * Using a ratio helps keeping shape stability independently of the map size.
  66391. *
  66392. * It does not account for the light projection as it was having too much
  66393. * instability during the light setup or during light position changes.
  66394. *
  66395. * Only valid if useContactHardeningShadow is true.
  66396. */
  66397. get: function () {
  66398. return this._contactHardeningLightSizeUVRatio;
  66399. },
  66400. /**
  66401. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66402. * Using a ratio helps keeping shape stability independently of the map size.
  66403. *
  66404. * It does not account for the light projection as it was having too much
  66405. * instability during the light setup or during light position changes.
  66406. *
  66407. * Only valid if useContactHardeningShadow is true.
  66408. */
  66409. set: function (contactHardeningLightSizeUVRatio) {
  66410. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66411. },
  66412. enumerable: true,
  66413. configurable: true
  66414. });
  66415. /**
  66416. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66417. * 0 means strongest and 1 would means no shadow.
  66418. * @returns the darkness.
  66419. */
  66420. ShadowGenerator.prototype.getDarkness = function () {
  66421. return this._darkness;
  66422. };
  66423. /**
  66424. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66425. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66426. * @returns the shadow generator allowing fluent coding.
  66427. */
  66428. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66429. if (darkness >= 1.0)
  66430. this._darkness = 1.0;
  66431. else if (darkness <= 0.0)
  66432. this._darkness = 0.0;
  66433. else
  66434. this._darkness = darkness;
  66435. return this;
  66436. };
  66437. /**
  66438. * Sets the ability to have transparent shadow (boolean).
  66439. * @param transparent True if transparent else False
  66440. * @returns the shadow generator allowing fluent coding
  66441. */
  66442. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66443. this._transparencyShadow = transparent;
  66444. return this;
  66445. };
  66446. /**
  66447. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66448. * @returns The render target texture if present otherwise, null
  66449. */
  66450. ShadowGenerator.prototype.getShadowMap = function () {
  66451. return this._shadowMap;
  66452. };
  66453. /**
  66454. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66455. * @returns The render target texture if the shadow map is present otherwise, null
  66456. */
  66457. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66458. if (this._shadowMap2) {
  66459. return this._shadowMap2;
  66460. }
  66461. return this._shadowMap;
  66462. };
  66463. /**
  66464. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66465. * @param mesh Mesh to add
  66466. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66467. * @returns the Shadow Generator itself
  66468. */
  66469. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66470. if (includeDescendants === void 0) { includeDescendants = true; }
  66471. if (!this._shadowMap) {
  66472. return this;
  66473. }
  66474. if (!this._shadowMap.renderList) {
  66475. this._shadowMap.renderList = [];
  66476. }
  66477. this._shadowMap.renderList.push(mesh);
  66478. if (includeDescendants) {
  66479. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66480. }
  66481. return this;
  66482. var _a;
  66483. };
  66484. /**
  66485. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66486. * @param mesh Mesh to remove
  66487. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66488. * @returns the Shadow Generator itself
  66489. */
  66490. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66491. if (includeDescendants === void 0) { includeDescendants = true; }
  66492. if (!this._shadowMap || !this._shadowMap.renderList) {
  66493. return this;
  66494. }
  66495. var index = this._shadowMap.renderList.indexOf(mesh);
  66496. if (index !== -1) {
  66497. this._shadowMap.renderList.splice(index, 1);
  66498. }
  66499. if (includeDescendants) {
  66500. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66501. var child = _a[_i];
  66502. this.removeShadowCaster(child);
  66503. }
  66504. }
  66505. return this;
  66506. };
  66507. /**
  66508. * Returns the associated light object.
  66509. * @returns the light generating the shadow
  66510. */
  66511. ShadowGenerator.prototype.getLight = function () {
  66512. return this._light;
  66513. };
  66514. ShadowGenerator.prototype._initializeGenerator = function () {
  66515. this._light._markMeshesAsLightDirty();
  66516. this._initializeShadowMap();
  66517. };
  66518. ShadowGenerator.prototype._initializeShadowMap = function () {
  66519. var _this = this;
  66520. // Render target
  66521. var engine = this._scene.getEngine();
  66522. if (engine.webGLVersion > 1) {
  66523. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66524. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66525. }
  66526. else {
  66527. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66528. }
  66529. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66530. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66531. this._shadowMap.anisotropicFilteringLevel = 1;
  66532. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66533. this._shadowMap.renderParticles = false;
  66534. this._shadowMap.ignoreCameraViewport = true;
  66535. // Record Face Index before render.
  66536. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66537. _this._currentFaceIndex = faceIndex;
  66538. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66539. engine.setColorWrite(false);
  66540. }
  66541. });
  66542. // Custom render function.
  66543. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66544. // Blur if required afer render.
  66545. this._shadowMap.onAfterUnbindObservable.add(function () {
  66546. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66547. engine.setColorWrite(true);
  66548. }
  66549. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66550. return;
  66551. }
  66552. var shadowMap = _this.getShadowMapForRendering();
  66553. if (shadowMap) {
  66554. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66555. }
  66556. });
  66557. // Clear according to the chosen filter.
  66558. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66559. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66560. this._shadowMap.onClearObservable.add(function (engine) {
  66561. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66562. engine.clear(clearOne, false, true, false);
  66563. }
  66564. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66565. engine.clear(clearZero, true, true, false);
  66566. }
  66567. else {
  66568. engine.clear(clearOne, true, true, false);
  66569. }
  66570. });
  66571. };
  66572. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66573. var _this = this;
  66574. var engine = this._scene.getEngine();
  66575. var targetSize = this._mapSize / this.blurScale;
  66576. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66577. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66578. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66579. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66580. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66581. }
  66582. if (this.useKernelBlur) {
  66583. 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);
  66584. this._kernelBlurXPostprocess.width = targetSize;
  66585. this._kernelBlurXPostprocess.height = targetSize;
  66586. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66587. effect.setTexture("textureSampler", _this._shadowMap);
  66588. });
  66589. 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);
  66590. this._kernelBlurXPostprocess.autoClear = false;
  66591. this._kernelBlurYPostprocess.autoClear = false;
  66592. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66593. this._kernelBlurXPostprocess.packedFloat = true;
  66594. this._kernelBlurYPostprocess.packedFloat = true;
  66595. }
  66596. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66597. }
  66598. else {
  66599. 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);
  66600. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66601. effect.setFloat2("screenSize", targetSize, targetSize);
  66602. effect.setTexture("textureSampler", _this._shadowMap);
  66603. });
  66604. this._boxBlurPostprocess.autoClear = false;
  66605. this._blurPostProcesses = [this._boxBlurPostprocess];
  66606. }
  66607. };
  66608. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66609. var index;
  66610. var engine = this._scene.getEngine();
  66611. if (depthOnlySubMeshes.length) {
  66612. engine.setColorWrite(false);
  66613. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66614. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66615. }
  66616. engine.setColorWrite(true);
  66617. }
  66618. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66619. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66620. }
  66621. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66622. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66623. }
  66624. if (this._transparencyShadow) {
  66625. for (index = 0; index < transparentSubMeshes.length; index++) {
  66626. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66627. }
  66628. }
  66629. };
  66630. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66631. var _this = this;
  66632. var mesh = subMesh.getRenderingMesh();
  66633. var scene = this._scene;
  66634. var engine = scene.getEngine();
  66635. var material = subMesh.getMaterial();
  66636. if (!material) {
  66637. return;
  66638. }
  66639. // Culling
  66640. engine.setState(material.backFaceCulling);
  66641. // Managing instances
  66642. var batch = mesh._getInstancesRenderList(subMesh._id);
  66643. if (batch.mustReturn) {
  66644. return;
  66645. }
  66646. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66647. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66648. engine.enableEffect(this._effect);
  66649. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66650. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66651. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66652. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66653. this._effect.setVector3("lightData", this._cachedDirection);
  66654. }
  66655. else {
  66656. this._effect.setVector3("lightData", this._cachedPosition);
  66657. }
  66658. if (scene.activeCamera) {
  66659. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66660. }
  66661. // Alpha test
  66662. if (material && material.needAlphaTesting()) {
  66663. var alphaTexture = material.getAlphaTestTexture();
  66664. if (alphaTexture) {
  66665. this._effect.setTexture("diffuseSampler", alphaTexture);
  66666. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66667. }
  66668. }
  66669. // Bones
  66670. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66671. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66672. }
  66673. // Morph targets
  66674. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66675. if (this.forceBackFacesOnly) {
  66676. engine.setState(true, 0, false, true);
  66677. }
  66678. // Draw
  66679. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66680. if (this.forceBackFacesOnly) {
  66681. engine.setState(true, 0, false, false);
  66682. }
  66683. }
  66684. else {
  66685. // Need to reset refresh rate of the shadowMap
  66686. if (this._shadowMap) {
  66687. this._shadowMap.resetRefreshCounter();
  66688. }
  66689. }
  66690. };
  66691. ShadowGenerator.prototype._applyFilterValues = function () {
  66692. if (!this._shadowMap) {
  66693. return;
  66694. }
  66695. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66696. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66697. }
  66698. else {
  66699. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66700. }
  66701. };
  66702. /**
  66703. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66704. * @param onCompiled Callback triggered at the and of the effects compilation
  66705. * @param options Sets of optional options forcing the compilation with different modes
  66706. */
  66707. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66708. var _this = this;
  66709. var localOptions = __assign({ useInstances: false }, options);
  66710. var shadowMap = this.getShadowMap();
  66711. if (!shadowMap) {
  66712. if (onCompiled) {
  66713. onCompiled(this);
  66714. }
  66715. return;
  66716. }
  66717. var renderList = shadowMap.renderList;
  66718. if (!renderList) {
  66719. if (onCompiled) {
  66720. onCompiled(this);
  66721. }
  66722. return;
  66723. }
  66724. var subMeshes = new Array();
  66725. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66726. var mesh = renderList_1[_i];
  66727. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66728. }
  66729. if (subMeshes.length === 0) {
  66730. if (onCompiled) {
  66731. onCompiled(this);
  66732. }
  66733. return;
  66734. }
  66735. var currentIndex = 0;
  66736. var checkReady = function () {
  66737. if (!_this._scene || !_this._scene.getEngine()) {
  66738. return;
  66739. }
  66740. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66741. currentIndex++;
  66742. if (currentIndex >= subMeshes.length) {
  66743. if (onCompiled) {
  66744. onCompiled(_this);
  66745. }
  66746. return;
  66747. }
  66748. }
  66749. setTimeout(checkReady, 16);
  66750. };
  66751. checkReady();
  66752. };
  66753. /**
  66754. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66755. * @param options Sets of optional options forcing the compilation with different modes
  66756. * @returns A promise that resolves when the compilation completes
  66757. */
  66758. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66759. var _this = this;
  66760. return new Promise(function (resolve) {
  66761. _this.forceCompilation(function () {
  66762. resolve();
  66763. }, options);
  66764. });
  66765. };
  66766. /**
  66767. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66768. * @param subMesh The submesh we want to render in the shadow map
  66769. * @param useInstances Defines wether will draw in the map using instances
  66770. * @returns true if ready otherwise, false
  66771. */
  66772. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66773. var defines = [];
  66774. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66775. defines.push("#define FLOAT");
  66776. }
  66777. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66778. defines.push("#define ESM");
  66779. }
  66780. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66781. defines.push("#define DEPTHTEXTURE");
  66782. }
  66783. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66784. var mesh = subMesh.getMesh();
  66785. var material = subMesh.getMaterial();
  66786. // Normal bias.
  66787. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66788. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66789. defines.push("#define NORMAL");
  66790. if (mesh.nonUniformScaling) {
  66791. defines.push("#define NONUNIFORMSCALING");
  66792. }
  66793. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66794. defines.push("#define DIRECTIONINLIGHTDATA");
  66795. }
  66796. }
  66797. // Alpha test
  66798. if (material && material.needAlphaTesting()) {
  66799. var alphaTexture = material.getAlphaTestTexture();
  66800. if (alphaTexture) {
  66801. defines.push("#define ALPHATEST");
  66802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66803. attribs.push(BABYLON.VertexBuffer.UVKind);
  66804. defines.push("#define UV1");
  66805. }
  66806. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66807. if (alphaTexture.coordinatesIndex === 1) {
  66808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66809. defines.push("#define UV2");
  66810. }
  66811. }
  66812. }
  66813. }
  66814. // Bones
  66815. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66816. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66817. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66818. if (mesh.numBoneInfluencers > 4) {
  66819. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66820. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66821. }
  66822. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66823. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66824. }
  66825. else {
  66826. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66827. }
  66828. // Morph targets
  66829. var manager = mesh.morphTargetManager;
  66830. var morphInfluencers = 0;
  66831. if (manager) {
  66832. if (manager.numInfluencers > 0) {
  66833. defines.push("#define MORPHTARGETS");
  66834. morphInfluencers = manager.numInfluencers;
  66835. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66836. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66837. }
  66838. }
  66839. // Instances
  66840. if (useInstances) {
  66841. defines.push("#define INSTANCES");
  66842. attribs.push("world0");
  66843. attribs.push("world1");
  66844. attribs.push("world2");
  66845. attribs.push("world3");
  66846. }
  66847. // Get correct effect
  66848. var join = defines.join("\n");
  66849. if (this._cachedDefines !== join) {
  66850. this._cachedDefines = join;
  66851. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66852. }
  66853. if (!this._effect.isReady()) {
  66854. return false;
  66855. }
  66856. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66857. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66858. this._initializeBlurRTTAndPostProcesses();
  66859. }
  66860. }
  66861. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66862. return false;
  66863. }
  66864. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66865. return false;
  66866. }
  66867. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66868. return false;
  66869. }
  66870. return true;
  66871. };
  66872. /**
  66873. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66874. * @param defines Defines of the material we want to update
  66875. * @param lightIndex Index of the light in the enabled light list of the material
  66876. */
  66877. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66878. var scene = this._scene;
  66879. var light = this._light;
  66880. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66881. return;
  66882. }
  66883. defines["SHADOW" + lightIndex] = true;
  66884. if (this.useContactHardeningShadow) {
  66885. defines["SHADOWPCSS" + lightIndex] = true;
  66886. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66887. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66888. }
  66889. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66890. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66891. }
  66892. // else default to high.
  66893. }
  66894. if (this.usePercentageCloserFiltering) {
  66895. defines["SHADOWPCF" + lightIndex] = true;
  66896. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66897. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66898. }
  66899. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66900. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66901. }
  66902. // else default to high.
  66903. }
  66904. else if (this.usePoissonSampling) {
  66905. defines["SHADOWPOISSON" + lightIndex] = true;
  66906. }
  66907. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66908. defines["SHADOWESM" + lightIndex] = true;
  66909. }
  66910. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66911. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66912. }
  66913. if (light.needCube()) {
  66914. defines["SHADOWCUBE" + lightIndex] = true;
  66915. }
  66916. };
  66917. /**
  66918. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66919. * defined in the generator but impacting the effect).
  66920. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66921. * @param effect The effect we are binfing the information for
  66922. */
  66923. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66924. var light = this._light;
  66925. var scene = this._scene;
  66926. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66927. return;
  66928. }
  66929. var camera = scene.activeCamera;
  66930. if (!camera) {
  66931. return;
  66932. }
  66933. var shadowMap = this.getShadowMap();
  66934. if (!shadowMap) {
  66935. return;
  66936. }
  66937. if (!light.needCube()) {
  66938. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66939. }
  66940. // Only PCF uses depth stencil texture.
  66941. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66942. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66943. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66944. }
  66945. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66946. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66947. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66948. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66949. }
  66950. else {
  66951. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66952. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66953. }
  66954. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66955. };
  66956. /**
  66957. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66958. * (eq to shadow prjection matrix * light transform matrix)
  66959. * @returns The transform matrix used to create the shadow map
  66960. */
  66961. ShadowGenerator.prototype.getTransformMatrix = function () {
  66962. var scene = this._scene;
  66963. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66964. return this._transformMatrix;
  66965. }
  66966. this._currentRenderID = scene.getRenderId();
  66967. this._currentFaceIndexCache = this._currentFaceIndex;
  66968. var lightPosition = this._light.position;
  66969. if (this._light.computeTransformedInformation()) {
  66970. lightPosition = this._light.transformedPosition;
  66971. }
  66972. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66973. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66974. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66975. }
  66976. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66977. this._cachedPosition.copyFrom(lightPosition);
  66978. this._cachedDirection.copyFrom(this._lightDirection);
  66979. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66980. var shadowMap = this.getShadowMap();
  66981. if (shadowMap) {
  66982. var renderList = shadowMap.renderList;
  66983. if (renderList) {
  66984. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66985. }
  66986. }
  66987. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66988. }
  66989. return this._transformMatrix;
  66990. };
  66991. /**
  66992. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66993. * Cube and 2D textures for instance.
  66994. */
  66995. ShadowGenerator.prototype.recreateShadowMap = function () {
  66996. var shadowMap = this._shadowMap;
  66997. if (!shadowMap) {
  66998. return;
  66999. }
  67000. // Track render list.
  67001. var renderList = shadowMap.renderList;
  67002. // Clean up existing data.
  67003. this._disposeRTTandPostProcesses();
  67004. // Reinitializes.
  67005. this._initializeGenerator();
  67006. // Reaffect the filter to ensure a correct fallback if necessary.
  67007. this.filter = this.filter;
  67008. // Reaffect the filter.
  67009. this._applyFilterValues();
  67010. // Reaffect Render List.
  67011. this._shadowMap.renderList = renderList;
  67012. };
  67013. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67014. if (this._shadowMap2) {
  67015. this._shadowMap2.dispose();
  67016. this._shadowMap2 = null;
  67017. }
  67018. if (this._boxBlurPostprocess) {
  67019. this._boxBlurPostprocess.dispose();
  67020. this._boxBlurPostprocess = null;
  67021. }
  67022. if (this._kernelBlurXPostprocess) {
  67023. this._kernelBlurXPostprocess.dispose();
  67024. this._kernelBlurXPostprocess = null;
  67025. }
  67026. if (this._kernelBlurYPostprocess) {
  67027. this._kernelBlurYPostprocess.dispose();
  67028. this._kernelBlurYPostprocess = null;
  67029. }
  67030. this._blurPostProcesses = [];
  67031. };
  67032. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67033. if (this._shadowMap) {
  67034. this._shadowMap.dispose();
  67035. this._shadowMap = null;
  67036. }
  67037. this._disposeBlurPostProcesses();
  67038. };
  67039. /**
  67040. * Disposes the ShadowGenerator.
  67041. * Returns nothing.
  67042. */
  67043. ShadowGenerator.prototype.dispose = function () {
  67044. this._disposeRTTandPostProcesses();
  67045. if (this._light) {
  67046. this._light._shadowGenerator = null;
  67047. this._light._markMeshesAsLightDirty();
  67048. }
  67049. };
  67050. /**
  67051. * Serializes the shadow generator setup to a json object.
  67052. * @returns The serialized JSON object
  67053. */
  67054. ShadowGenerator.prototype.serialize = function () {
  67055. var serializationObject = {};
  67056. var shadowMap = this.getShadowMap();
  67057. if (!shadowMap) {
  67058. return serializationObject;
  67059. }
  67060. serializationObject.lightId = this._light.id;
  67061. serializationObject.mapSize = shadowMap.getRenderSize();
  67062. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67063. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67064. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67065. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67066. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67067. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67068. serializationObject.depthScale = this.depthScale;
  67069. serializationObject.darkness = this.getDarkness();
  67070. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67071. serializationObject.blurKernel = this.blurKernel;
  67072. serializationObject.blurScale = this.blurScale;
  67073. serializationObject.useKernelBlur = this.useKernelBlur;
  67074. serializationObject.transparencyShadow = this._transparencyShadow;
  67075. serializationObject.bias = this.bias;
  67076. serializationObject.normalBias = this.normalBias;
  67077. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67078. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67079. serializationObject.filteringQuality = this.filteringQuality;
  67080. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67081. serializationObject.renderList = [];
  67082. if (shadowMap.renderList) {
  67083. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67084. var mesh = shadowMap.renderList[meshIndex];
  67085. serializationObject.renderList.push(mesh.id);
  67086. }
  67087. }
  67088. return serializationObject;
  67089. };
  67090. /**
  67091. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67092. * @param parsedShadowGenerator The JSON object to parse
  67093. * @param scene The scene to create the shadow map for
  67094. * @returns The parsed shadow generator
  67095. */
  67096. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67097. //casting to point light, as light is missing the position attr and typescript complains.
  67098. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67099. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67100. var shadowMap = shadowGenerator.getShadowMap();
  67101. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67102. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67103. meshes.forEach(function (mesh) {
  67104. if (!shadowMap) {
  67105. return;
  67106. }
  67107. if (!shadowMap.renderList) {
  67108. shadowMap.renderList = [];
  67109. }
  67110. shadowMap.renderList.push(mesh);
  67111. });
  67112. }
  67113. if (parsedShadowGenerator.usePoissonSampling) {
  67114. shadowGenerator.usePoissonSampling = true;
  67115. }
  67116. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67117. shadowGenerator.useExponentialShadowMap = true;
  67118. }
  67119. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67120. shadowGenerator.useBlurExponentialShadowMap = true;
  67121. }
  67122. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67123. shadowGenerator.useCloseExponentialShadowMap = true;
  67124. }
  67125. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67126. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67127. }
  67128. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67129. shadowGenerator.usePercentageCloserFiltering = true;
  67130. }
  67131. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67132. shadowGenerator.useContactHardeningShadow = true;
  67133. }
  67134. if (parsedShadowGenerator.filteringQuality) {
  67135. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67136. }
  67137. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67138. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67139. }
  67140. // Backward compat
  67141. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67142. shadowGenerator.useExponentialShadowMap = true;
  67143. }
  67144. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67145. shadowGenerator.useBlurExponentialShadowMap = true;
  67146. }
  67147. if (parsedShadowGenerator.depthScale) {
  67148. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67149. }
  67150. if (parsedShadowGenerator.blurScale) {
  67151. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67152. }
  67153. if (parsedShadowGenerator.blurBoxOffset) {
  67154. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67155. }
  67156. if (parsedShadowGenerator.useKernelBlur) {
  67157. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67158. }
  67159. if (parsedShadowGenerator.blurKernel) {
  67160. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67161. }
  67162. if (parsedShadowGenerator.bias !== undefined) {
  67163. shadowGenerator.bias = parsedShadowGenerator.bias;
  67164. }
  67165. if (parsedShadowGenerator.normalBias !== undefined) {
  67166. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67167. }
  67168. if (parsedShadowGenerator.darkness) {
  67169. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67170. }
  67171. if (parsedShadowGenerator.transparencyShadow) {
  67172. shadowGenerator.setTransparencyShadow(true);
  67173. }
  67174. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67175. return shadowGenerator;
  67176. };
  67177. /**
  67178. * Shadow generator mode None: no filtering applied.
  67179. */
  67180. ShadowGenerator.FILTER_NONE = 0;
  67181. /**
  67182. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67183. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67184. */
  67185. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67186. /**
  67187. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67188. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67189. */
  67190. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67191. /**
  67192. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67193. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67194. */
  67195. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67196. /**
  67197. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67198. * edge artifacts on steep falloff.
  67199. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67200. */
  67201. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67202. /**
  67203. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67204. * edge artifacts on steep falloff.
  67205. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67206. */
  67207. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67208. /**
  67209. * Shadow generator mode PCF: Percentage Closer Filtering
  67210. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67211. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67212. */
  67213. ShadowGenerator.FILTER_PCF = 6;
  67214. /**
  67215. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67216. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67217. * Contact Hardening
  67218. */
  67219. ShadowGenerator.FILTER_PCSS = 7;
  67220. /**
  67221. * Reserved for PCF and PCSS
  67222. * Highest Quality.
  67223. *
  67224. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67225. *
  67226. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67227. */
  67228. ShadowGenerator.QUALITY_HIGH = 0;
  67229. /**
  67230. * Reserved for PCF and PCSS
  67231. * Good tradeoff for quality/perf cross devices
  67232. *
  67233. * Execute PCF on a 3*3 kernel.
  67234. *
  67235. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67236. */
  67237. ShadowGenerator.QUALITY_MEDIUM = 1;
  67238. /**
  67239. * Reserved for PCF and PCSS
  67240. * The lowest quality but the fastest.
  67241. *
  67242. * Execute PCF on a 1*1 kernel.
  67243. *
  67244. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67245. */
  67246. ShadowGenerator.QUALITY_LOW = 2;
  67247. return ShadowGenerator;
  67248. }());
  67249. BABYLON.ShadowGenerator = ShadowGenerator;
  67250. })(BABYLON || (BABYLON = {}));
  67251. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67252. var BABYLON;
  67253. (function (BABYLON) {
  67254. var DefaultLoadingScreen = /** @class */ (function () {
  67255. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67256. if (_loadingText === void 0) { _loadingText = ""; }
  67257. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67258. var _this = this;
  67259. this._renderingCanvas = _renderingCanvas;
  67260. this._loadingText = _loadingText;
  67261. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67262. // Resize
  67263. this._resizeLoadingUI = function () {
  67264. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67265. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67266. if (!_this._loadingDiv) {
  67267. return;
  67268. }
  67269. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67270. _this._loadingDiv.style.left = canvasRect.left + "px";
  67271. _this._loadingDiv.style.top = canvasRect.top + "px";
  67272. _this._loadingDiv.style.width = canvasRect.width + "px";
  67273. _this._loadingDiv.style.height = canvasRect.height + "px";
  67274. };
  67275. }
  67276. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67277. if (this._loadingDiv) {
  67278. // Do not add a loading screen if there is already one
  67279. return;
  67280. }
  67281. this._loadingDiv = document.createElement("div");
  67282. this._loadingDiv.id = "babylonjsLoadingDiv";
  67283. this._loadingDiv.style.opacity = "0";
  67284. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67285. this._loadingDiv.style.pointerEvents = "none";
  67286. // Loading text
  67287. this._loadingTextDiv = document.createElement("div");
  67288. this._loadingTextDiv.style.position = "absolute";
  67289. this._loadingTextDiv.style.left = "0";
  67290. this._loadingTextDiv.style.top = "50%";
  67291. this._loadingTextDiv.style.marginTop = "80px";
  67292. this._loadingTextDiv.style.width = "100%";
  67293. this._loadingTextDiv.style.height = "20px";
  67294. this._loadingTextDiv.style.fontFamily = "Arial";
  67295. this._loadingTextDiv.style.fontSize = "14px";
  67296. this._loadingTextDiv.style.color = "white";
  67297. this._loadingTextDiv.style.textAlign = "center";
  67298. this._loadingTextDiv.innerHTML = "Loading";
  67299. this._loadingDiv.appendChild(this._loadingTextDiv);
  67300. //set the predefined text
  67301. this._loadingTextDiv.innerHTML = this._loadingText;
  67302. // Generating keyframes
  67303. var style = document.createElement('style');
  67304. style.type = 'text/css';
  67305. 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 }";
  67306. style.innerHTML = keyFrames;
  67307. document.getElementsByTagName('head')[0].appendChild(style);
  67308. // Loading img
  67309. var imgBack = new Image();
  67310. 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";
  67311. imgBack.style.position = "absolute";
  67312. imgBack.style.left = "50%";
  67313. imgBack.style.top = "50%";
  67314. imgBack.style.marginLeft = "-60px";
  67315. imgBack.style.marginTop = "-60px";
  67316. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67317. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67318. imgBack.style.transformOrigin = "50% 50%";
  67319. imgBack.style.webkitTransformOrigin = "50% 50%";
  67320. this._loadingDiv.appendChild(imgBack);
  67321. this._resizeLoadingUI();
  67322. window.addEventListener("resize", this._resizeLoadingUI);
  67323. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67324. document.body.appendChild(this._loadingDiv);
  67325. this._loadingDiv.style.opacity = "1";
  67326. };
  67327. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67328. var _this = this;
  67329. if (!this._loadingDiv) {
  67330. return;
  67331. }
  67332. var onTransitionEnd = function () {
  67333. if (!_this._loadingDiv) {
  67334. return;
  67335. }
  67336. document.body.removeChild(_this._loadingDiv);
  67337. window.removeEventListener("resize", _this._resizeLoadingUI);
  67338. _this._loadingDiv = null;
  67339. };
  67340. this._loadingDiv.style.opacity = "0";
  67341. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67342. };
  67343. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67344. set: function (text) {
  67345. this._loadingText = text;
  67346. if (this._loadingTextDiv) {
  67347. this._loadingTextDiv.innerHTML = this._loadingText;
  67348. }
  67349. },
  67350. enumerable: true,
  67351. configurable: true
  67352. });
  67353. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67354. get: function () {
  67355. return this._loadingDivBackgroundColor;
  67356. },
  67357. set: function (color) {
  67358. this._loadingDivBackgroundColor = color;
  67359. if (!this._loadingDiv) {
  67360. return;
  67361. }
  67362. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67363. },
  67364. enumerable: true,
  67365. configurable: true
  67366. });
  67367. return DefaultLoadingScreen;
  67368. }());
  67369. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67370. })(BABYLON || (BABYLON = {}));
  67371. //# sourceMappingURL=babylon.loadingScreen.js.map
  67372. var BABYLON;
  67373. (function (BABYLON) {
  67374. var SceneLoaderProgressEvent = /** @class */ (function () {
  67375. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67376. this.lengthComputable = lengthComputable;
  67377. this.loaded = loaded;
  67378. this.total = total;
  67379. }
  67380. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67381. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67382. };
  67383. return SceneLoaderProgressEvent;
  67384. }());
  67385. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67386. var SceneLoader = /** @class */ (function () {
  67387. function SceneLoader() {
  67388. }
  67389. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67390. get: function () {
  67391. return 0;
  67392. },
  67393. enumerable: true,
  67394. configurable: true
  67395. });
  67396. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67397. get: function () {
  67398. return 1;
  67399. },
  67400. enumerable: true,
  67401. configurable: true
  67402. });
  67403. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67404. get: function () {
  67405. return 2;
  67406. },
  67407. enumerable: true,
  67408. configurable: true
  67409. });
  67410. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67411. get: function () {
  67412. return 3;
  67413. },
  67414. enumerable: true,
  67415. configurable: true
  67416. });
  67417. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67418. get: function () {
  67419. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67420. },
  67421. set: function (value) {
  67422. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67423. },
  67424. enumerable: true,
  67425. configurable: true
  67426. });
  67427. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67428. get: function () {
  67429. return SceneLoader._ShowLoadingScreen;
  67430. },
  67431. set: function (value) {
  67432. SceneLoader._ShowLoadingScreen = value;
  67433. },
  67434. enumerable: true,
  67435. configurable: true
  67436. });
  67437. Object.defineProperty(SceneLoader, "loggingLevel", {
  67438. get: function () {
  67439. return SceneLoader._loggingLevel;
  67440. },
  67441. set: function (value) {
  67442. SceneLoader._loggingLevel = value;
  67443. },
  67444. enumerable: true,
  67445. configurable: true
  67446. });
  67447. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67448. get: function () {
  67449. return SceneLoader._CleanBoneMatrixWeights;
  67450. },
  67451. set: function (value) {
  67452. SceneLoader._CleanBoneMatrixWeights = value;
  67453. },
  67454. enumerable: true,
  67455. configurable: true
  67456. });
  67457. SceneLoader._getDefaultPlugin = function () {
  67458. return SceneLoader._registeredPlugins[".babylon"];
  67459. };
  67460. SceneLoader._getPluginForExtension = function (extension) {
  67461. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67462. if (registeredPlugin) {
  67463. return registeredPlugin;
  67464. }
  67465. 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");
  67466. return SceneLoader._getDefaultPlugin();
  67467. };
  67468. SceneLoader._getPluginForDirectLoad = function (data) {
  67469. for (var extension in SceneLoader._registeredPlugins) {
  67470. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67471. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67472. return SceneLoader._registeredPlugins[extension];
  67473. }
  67474. }
  67475. return SceneLoader._getDefaultPlugin();
  67476. };
  67477. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67478. if (sceneFilename.name) {
  67479. sceneFilename = sceneFilename.name;
  67480. }
  67481. var queryStringPosition = sceneFilename.indexOf("?");
  67482. if (queryStringPosition !== -1) {
  67483. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67484. }
  67485. var dotPosition = sceneFilename.lastIndexOf(".");
  67486. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67487. return SceneLoader._getPluginForExtension(extension);
  67488. };
  67489. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67490. SceneLoader._getDirectLoad = function (sceneFilename) {
  67491. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67492. return sceneFilename.substr(5);
  67493. }
  67494. return null;
  67495. };
  67496. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67497. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67498. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67499. var plugin;
  67500. if (registeredPlugin.plugin.createPlugin) {
  67501. plugin = registeredPlugin.plugin.createPlugin();
  67502. }
  67503. else {
  67504. plugin = registeredPlugin.plugin;
  67505. }
  67506. var useArrayBuffer = registeredPlugin.isBinary;
  67507. var database;
  67508. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67509. var dataCallback = function (data, responseURL) {
  67510. if (scene.isDisposed) {
  67511. onError("Scene has been disposed");
  67512. return;
  67513. }
  67514. scene.database = database;
  67515. onSuccess(plugin, data, responseURL);
  67516. };
  67517. var request = null;
  67518. var pluginDisposed = false;
  67519. var onDisposeObservable = plugin.onDisposeObservable;
  67520. if (onDisposeObservable) {
  67521. onDisposeObservable.add(function () {
  67522. pluginDisposed = true;
  67523. if (request) {
  67524. request.abort();
  67525. request = null;
  67526. }
  67527. onDispose();
  67528. });
  67529. }
  67530. var manifestChecked = function () {
  67531. if (pluginDisposed) {
  67532. return;
  67533. }
  67534. var url = rootUrl + sceneFilename;
  67535. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67536. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67537. } : undefined, database, useArrayBuffer, function (request, exception) {
  67538. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67539. });
  67540. };
  67541. if (directLoad) {
  67542. dataCallback(directLoad);
  67543. return plugin;
  67544. }
  67545. if (rootUrl.indexOf("file:") === -1) {
  67546. var engine = scene.getEngine();
  67547. var canUseOfflineSupport = engine.enableOfflineSupport;
  67548. if (canUseOfflineSupport) {
  67549. // Also check for exceptions
  67550. var exceptionFound = false;
  67551. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67552. var regex = _a[_i];
  67553. if (regex.test(rootUrl + sceneFilename)) {
  67554. exceptionFound = true;
  67555. break;
  67556. }
  67557. }
  67558. canUseOfflineSupport = !exceptionFound;
  67559. }
  67560. if (canUseOfflineSupport) {
  67561. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67562. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67563. }
  67564. else {
  67565. manifestChecked();
  67566. }
  67567. }
  67568. // Loading file from disk via input file or drag'n'drop
  67569. else {
  67570. var fileOrString = sceneFilename;
  67571. if (fileOrString.name) { // File
  67572. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67573. }
  67574. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67575. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67576. }
  67577. else {
  67578. onError("Unable to find file named " + sceneFilename);
  67579. }
  67580. }
  67581. return plugin;
  67582. };
  67583. // Public functions
  67584. SceneLoader.GetPluginForExtension = function (extension) {
  67585. return SceneLoader._getPluginForExtension(extension).plugin;
  67586. };
  67587. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67588. return !!SceneLoader._registeredPlugins[extension];
  67589. };
  67590. SceneLoader.RegisterPlugin = function (plugin) {
  67591. if (typeof plugin.extensions === "string") {
  67592. var extension = plugin.extensions;
  67593. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67594. plugin: plugin,
  67595. isBinary: false
  67596. };
  67597. }
  67598. else {
  67599. var extensions = plugin.extensions;
  67600. Object.keys(extensions).forEach(function (extension) {
  67601. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67602. plugin: plugin,
  67603. isBinary: extensions[extension].isBinary
  67604. };
  67605. });
  67606. }
  67607. };
  67608. /**
  67609. * Import meshes into a scene
  67610. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67611. * @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)
  67612. * @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)
  67613. * @param scene the instance of BABYLON.Scene to append to
  67614. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67615. * @param onProgress a callback with a progress event for each file being loaded
  67616. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67617. * @param pluginExtension the extension used to determine the plugin
  67618. * @returns The loaded plugin
  67619. */
  67620. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67621. if (sceneFilename === void 0) { sceneFilename = ""; }
  67622. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67623. if (onSuccess === void 0) { onSuccess = null; }
  67624. if (onProgress === void 0) { onProgress = null; }
  67625. if (onError === void 0) { onError = null; }
  67626. if (pluginExtension === void 0) { pluginExtension = null; }
  67627. if (!scene) {
  67628. BABYLON.Tools.Error("No scene available to import mesh to");
  67629. return null;
  67630. }
  67631. if (!sceneFilename) {
  67632. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67633. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67634. }
  67635. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67636. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67637. return null;
  67638. }
  67639. var loadingToken = {};
  67640. scene._addPendingData(loadingToken);
  67641. var disposeHandler = function () {
  67642. scene._removePendingData(loadingToken);
  67643. };
  67644. var errorHandler = function (message, exception) {
  67645. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67646. if (onError) {
  67647. onError(scene, errorMessage, exception);
  67648. }
  67649. else {
  67650. BABYLON.Tools.Error(errorMessage);
  67651. // should the exception be thrown?
  67652. }
  67653. disposeHandler();
  67654. };
  67655. var progressHandler = onProgress ? function (event) {
  67656. try {
  67657. onProgress(event);
  67658. }
  67659. catch (e) {
  67660. errorHandler("Error in onProgress callback", e);
  67661. }
  67662. } : undefined;
  67663. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67664. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67665. if (onSuccess) {
  67666. try {
  67667. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67668. }
  67669. catch (e) {
  67670. errorHandler("Error in onSuccess callback", e);
  67671. }
  67672. }
  67673. scene._removePendingData(loadingToken);
  67674. };
  67675. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67676. if (plugin.rewriteRootURL) {
  67677. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67678. }
  67679. if (sceneFilename === "") {
  67680. if (sceneFilename === "") {
  67681. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67682. }
  67683. }
  67684. if (plugin.importMesh) {
  67685. var syncedPlugin = plugin;
  67686. var meshes = new Array();
  67687. var particleSystems = new Array();
  67688. var skeletons = new Array();
  67689. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67690. return;
  67691. }
  67692. scene.loadingPluginName = plugin.name;
  67693. successHandler(meshes, particleSystems, skeletons, []);
  67694. }
  67695. else {
  67696. var asyncedPlugin = plugin;
  67697. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67698. scene.loadingPluginName = plugin.name;
  67699. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67700. }).catch(function (error) {
  67701. errorHandler(error.message, error);
  67702. });
  67703. }
  67704. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67705. };
  67706. /**
  67707. * Import meshes into a scene
  67708. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67709. * @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)
  67710. * @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)
  67711. * @param scene the instance of BABYLON.Scene to append to
  67712. * @param onProgress a callback with a progress event for each file being loaded
  67713. * @param pluginExtension the extension used to determine the plugin
  67714. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67715. */
  67716. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67717. if (sceneFilename === void 0) { sceneFilename = ""; }
  67718. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67719. if (onProgress === void 0) { onProgress = null; }
  67720. if (pluginExtension === void 0) { pluginExtension = null; }
  67721. return new Promise(function (resolve, reject) {
  67722. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67723. resolve({
  67724. meshes: meshes,
  67725. particleSystems: particleSystems,
  67726. skeletons: skeletons,
  67727. animationGroups: animationGroups
  67728. });
  67729. }, onProgress, function (scene, message, exception) {
  67730. reject(exception || new Error(message));
  67731. }, pluginExtension);
  67732. });
  67733. };
  67734. /**
  67735. * Load a scene
  67736. * @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)
  67737. * @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)
  67738. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67739. * @param onSuccess a callback with the scene when import succeeds
  67740. * @param onProgress a callback with a progress event for each file being loaded
  67741. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67742. * @param pluginExtension the extension used to determine the plugin
  67743. * @returns The loaded plugin
  67744. */
  67745. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67746. if (onSuccess === void 0) { onSuccess = null; }
  67747. if (onProgress === void 0) { onProgress = null; }
  67748. if (onError === void 0) { onError = null; }
  67749. if (pluginExtension === void 0) { pluginExtension = null; }
  67750. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67751. };
  67752. /**
  67753. * Load a scene
  67754. * @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)
  67755. * @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)
  67756. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67757. * @param onProgress a callback with a progress event for each file being loaded
  67758. * @param pluginExtension the extension used to determine the plugin
  67759. * @returns The loaded scene
  67760. */
  67761. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67762. if (onProgress === void 0) { onProgress = null; }
  67763. if (pluginExtension === void 0) { pluginExtension = null; }
  67764. return new Promise(function (resolve, reject) {
  67765. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67766. resolve(scene);
  67767. }, onProgress, function (scene, message, exception) {
  67768. reject(exception || new Error(message));
  67769. }, pluginExtension);
  67770. });
  67771. };
  67772. /**
  67773. * Append a scene
  67774. * @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)
  67775. * @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)
  67776. * @param scene is the instance of BABYLON.Scene to append to
  67777. * @param onSuccess a callback with the scene when import succeeds
  67778. * @param onProgress a callback with a progress event for each file being loaded
  67779. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67780. * @param pluginExtension the extension used to determine the plugin
  67781. * @returns The loaded plugin
  67782. */
  67783. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67784. if (sceneFilename === void 0) { sceneFilename = ""; }
  67785. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67786. if (onSuccess === void 0) { onSuccess = null; }
  67787. if (onProgress === void 0) { onProgress = null; }
  67788. if (onError === void 0) { onError = null; }
  67789. if (pluginExtension === void 0) { pluginExtension = null; }
  67790. if (!scene) {
  67791. BABYLON.Tools.Error("No scene available to append to");
  67792. return null;
  67793. }
  67794. if (!sceneFilename) {
  67795. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67796. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67797. }
  67798. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67799. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67800. return null;
  67801. }
  67802. if (SceneLoader.ShowLoadingScreen) {
  67803. scene.getEngine().displayLoadingUI();
  67804. }
  67805. var loadingToken = {};
  67806. scene._addPendingData(loadingToken);
  67807. var disposeHandler = function () {
  67808. scene._removePendingData(loadingToken);
  67809. scene.getEngine().hideLoadingUI();
  67810. };
  67811. var errorHandler = function (message, exception) {
  67812. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67813. if (onError) {
  67814. onError(scene, errorMessage, exception);
  67815. }
  67816. else {
  67817. BABYLON.Tools.Error(errorMessage);
  67818. // should the exception be thrown?
  67819. }
  67820. disposeHandler();
  67821. };
  67822. var progressHandler = onProgress ? function (event) {
  67823. try {
  67824. onProgress(event);
  67825. }
  67826. catch (e) {
  67827. errorHandler("Error in onProgress callback", e);
  67828. }
  67829. } : undefined;
  67830. var successHandler = function () {
  67831. if (onSuccess) {
  67832. try {
  67833. onSuccess(scene);
  67834. }
  67835. catch (e) {
  67836. errorHandler("Error in onSuccess callback", e);
  67837. }
  67838. }
  67839. scene._removePendingData(loadingToken);
  67840. };
  67841. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67842. if (sceneFilename === "") {
  67843. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67844. }
  67845. if (plugin.load) {
  67846. var syncedPlugin = plugin;
  67847. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67848. return;
  67849. }
  67850. scene.loadingPluginName = plugin.name;
  67851. successHandler();
  67852. }
  67853. else {
  67854. var asyncedPlugin = plugin;
  67855. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67856. scene.loadingPluginName = plugin.name;
  67857. successHandler();
  67858. }).catch(function (error) {
  67859. errorHandler(error.message, error);
  67860. });
  67861. }
  67862. if (SceneLoader.ShowLoadingScreen) {
  67863. scene.executeWhenReady(function () {
  67864. scene.getEngine().hideLoadingUI();
  67865. });
  67866. }
  67867. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67868. };
  67869. /**
  67870. * Append a scene
  67871. * @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)
  67872. * @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)
  67873. * @param scene is the instance of BABYLON.Scene to append to
  67874. * @param onProgress a callback with a progress event for each file being loaded
  67875. * @param pluginExtension the extension used to determine the plugin
  67876. * @returns The given scene
  67877. */
  67878. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67879. if (sceneFilename === void 0) { sceneFilename = ""; }
  67880. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67881. if (onProgress === void 0) { onProgress = null; }
  67882. if (pluginExtension === void 0) { pluginExtension = null; }
  67883. return new Promise(function (resolve, reject) {
  67884. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67885. resolve(scene);
  67886. }, onProgress, function (scene, message, exception) {
  67887. reject(exception || new Error(message));
  67888. }, pluginExtension);
  67889. });
  67890. };
  67891. /**
  67892. * Load a scene into an asset container
  67893. * @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)
  67894. * @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)
  67895. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67896. * @param onSuccess a callback with the scene when import succeeds
  67897. * @param onProgress a callback with a progress event for each file being loaded
  67898. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67899. * @param pluginExtension the extension used to determine the plugin
  67900. * @returns The loaded plugin
  67901. */
  67902. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67903. if (sceneFilename === void 0) { sceneFilename = ""; }
  67904. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67905. if (onSuccess === void 0) { onSuccess = null; }
  67906. if (onProgress === void 0) { onProgress = null; }
  67907. if (onError === void 0) { onError = null; }
  67908. if (pluginExtension === void 0) { pluginExtension = null; }
  67909. if (!scene) {
  67910. BABYLON.Tools.Error("No scene available to load asset container to");
  67911. return null;
  67912. }
  67913. if (!sceneFilename) {
  67914. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67915. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67916. }
  67917. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67918. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67919. return null;
  67920. }
  67921. var loadingToken = {};
  67922. scene._addPendingData(loadingToken);
  67923. var disposeHandler = function () {
  67924. scene._removePendingData(loadingToken);
  67925. };
  67926. var errorHandler = function (message, exception) {
  67927. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67928. if (onError) {
  67929. onError(scene, errorMessage, exception);
  67930. }
  67931. else {
  67932. BABYLON.Tools.Error(errorMessage);
  67933. // should the exception be thrown?
  67934. }
  67935. disposeHandler();
  67936. };
  67937. var progressHandler = onProgress ? function (event) {
  67938. try {
  67939. onProgress(event);
  67940. }
  67941. catch (e) {
  67942. errorHandler("Error in onProgress callback", e);
  67943. }
  67944. } : undefined;
  67945. var successHandler = function (assets) {
  67946. if (onSuccess) {
  67947. try {
  67948. onSuccess(assets);
  67949. }
  67950. catch (e) {
  67951. errorHandler("Error in onSuccess callback", e);
  67952. }
  67953. }
  67954. scene._removePendingData(loadingToken);
  67955. };
  67956. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67957. if (plugin.loadAssetContainer) {
  67958. var syncedPlugin = plugin;
  67959. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67960. if (!assetContainer) {
  67961. return;
  67962. }
  67963. scene.loadingPluginName = plugin.name;
  67964. successHandler(assetContainer);
  67965. }
  67966. else if (plugin.loadAssetContainerAsync) {
  67967. var asyncedPlugin = plugin;
  67968. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67969. scene.loadingPluginName = plugin.name;
  67970. successHandler(assetContainer);
  67971. }).catch(function (error) {
  67972. errorHandler(error.message, error);
  67973. });
  67974. }
  67975. else {
  67976. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67977. }
  67978. if (SceneLoader.ShowLoadingScreen) {
  67979. scene.executeWhenReady(function () {
  67980. scene.getEngine().hideLoadingUI();
  67981. });
  67982. }
  67983. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67984. };
  67985. /**
  67986. * Load a scene into an asset container
  67987. * @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)
  67988. * @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)
  67989. * @param scene is the instance of BABYLON.Scene to append to
  67990. * @param onProgress a callback with a progress event for each file being loaded
  67991. * @param pluginExtension the extension used to determine the plugin
  67992. * @returns The loaded asset container
  67993. */
  67994. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67995. if (sceneFilename === void 0) { sceneFilename = ""; }
  67996. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67997. if (onProgress === void 0) { onProgress = null; }
  67998. if (pluginExtension === void 0) { pluginExtension = null; }
  67999. return new Promise(function (resolve, reject) {
  68000. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68001. resolve(assetContainer);
  68002. }, onProgress, function (scene, message, exception) {
  68003. reject(exception || new Error(message));
  68004. }, pluginExtension);
  68005. });
  68006. };
  68007. // Flags
  68008. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68009. SceneLoader._ShowLoadingScreen = true;
  68010. SceneLoader._CleanBoneMatrixWeights = false;
  68011. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68012. // Members
  68013. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68014. SceneLoader._registeredPlugins = {};
  68015. return SceneLoader;
  68016. }());
  68017. BABYLON.SceneLoader = SceneLoader;
  68018. ;
  68019. })(BABYLON || (BABYLON = {}));
  68020. //# sourceMappingURL=babylon.sceneLoader.js.map
  68021. var BABYLON;
  68022. (function (BABYLON) {
  68023. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68024. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68025. var parsedMaterial = parsedData.materials[index];
  68026. if (parsedMaterial.id === id) {
  68027. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68028. }
  68029. }
  68030. return null;
  68031. };
  68032. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68033. for (var i in names) {
  68034. if (mesh.name === names[i]) {
  68035. hierarchyIds.push(mesh.id);
  68036. return true;
  68037. }
  68038. }
  68039. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68040. hierarchyIds.push(mesh.id);
  68041. return true;
  68042. }
  68043. return false;
  68044. };
  68045. var logOperation = function (operation, producer) {
  68046. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68047. };
  68048. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68049. if (addToScene === void 0) { addToScene = false; }
  68050. var container = new BABYLON.AssetContainer(scene);
  68051. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68052. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68053. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68054. // and avoid problems with multiple concurrent .babylon loads.
  68055. var log = "importScene has failed JSON parse";
  68056. try {
  68057. var parsedData = JSON.parse(data);
  68058. log = "";
  68059. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68060. var index;
  68061. var cache;
  68062. // Lights
  68063. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68064. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68065. var parsedLight = parsedData.lights[index];
  68066. var light = BABYLON.Light.Parse(parsedLight, scene);
  68067. if (light) {
  68068. container.lights.push(light);
  68069. log += (index === 0 ? "\n\tLights:" : "");
  68070. log += "\n\t\t" + light.toString(fullDetails);
  68071. }
  68072. }
  68073. }
  68074. // Animations
  68075. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68076. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68077. var parsedAnimation = parsedData.animations[index];
  68078. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68079. scene.animations.push(animation);
  68080. container.animations.push(animation);
  68081. log += (index === 0 ? "\n\tAnimations:" : "");
  68082. log += "\n\t\t" + animation.toString(fullDetails);
  68083. }
  68084. }
  68085. // Materials
  68086. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68087. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68088. var parsedMaterial = parsedData.materials[index];
  68089. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68090. container.materials.push(mat);
  68091. log += (index === 0 ? "\n\tMaterials:" : "");
  68092. log += "\n\t\t" + mat.toString(fullDetails);
  68093. }
  68094. }
  68095. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68096. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68097. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68098. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68099. container.multiMaterials.push(mmat);
  68100. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68101. log += "\n\t\t" + mmat.toString(fullDetails);
  68102. }
  68103. }
  68104. // Morph targets
  68105. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68106. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68107. var managerData = _a[_i];
  68108. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68109. }
  68110. }
  68111. // Skeletons
  68112. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68113. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68114. var parsedSkeleton = parsedData.skeletons[index];
  68115. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68116. container.skeletons.push(skeleton);
  68117. log += (index === 0 ? "\n\tSkeletons:" : "");
  68118. log += "\n\t\t" + skeleton.toString(fullDetails);
  68119. }
  68120. }
  68121. // Geometries
  68122. var geometries = parsedData.geometries;
  68123. if (geometries !== undefined && geometries !== null) {
  68124. var addedGeometry = new Array();
  68125. // Boxes
  68126. var boxes = geometries.boxes;
  68127. if (boxes !== undefined && boxes !== null) {
  68128. for (index = 0, cache = boxes.length; index < cache; index++) {
  68129. var parsedBox = boxes[index];
  68130. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68131. }
  68132. }
  68133. // Spheres
  68134. var spheres = geometries.spheres;
  68135. if (spheres !== undefined && spheres !== null) {
  68136. for (index = 0, cache = spheres.length; index < cache; index++) {
  68137. var parsedSphere = spheres[index];
  68138. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68139. }
  68140. }
  68141. // Cylinders
  68142. var cylinders = geometries.cylinders;
  68143. if (cylinders !== undefined && cylinders !== null) {
  68144. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68145. var parsedCylinder = cylinders[index];
  68146. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68147. }
  68148. }
  68149. // Toruses
  68150. var toruses = geometries.toruses;
  68151. if (toruses !== undefined && toruses !== null) {
  68152. for (index = 0, cache = toruses.length; index < cache; index++) {
  68153. var parsedTorus = toruses[index];
  68154. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68155. }
  68156. }
  68157. // Grounds
  68158. var grounds = geometries.grounds;
  68159. if (grounds !== undefined && grounds !== null) {
  68160. for (index = 0, cache = grounds.length; index < cache; index++) {
  68161. var parsedGround = grounds[index];
  68162. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68163. }
  68164. }
  68165. // Planes
  68166. var planes = geometries.planes;
  68167. if (planes !== undefined && planes !== null) {
  68168. for (index = 0, cache = planes.length; index < cache; index++) {
  68169. var parsedPlane = planes[index];
  68170. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68171. }
  68172. }
  68173. // TorusKnots
  68174. var torusKnots = geometries.torusKnots;
  68175. if (torusKnots !== undefined && torusKnots !== null) {
  68176. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68177. var parsedTorusKnot = torusKnots[index];
  68178. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68179. }
  68180. }
  68181. // VertexData
  68182. var vertexData = geometries.vertexData;
  68183. if (vertexData !== undefined && vertexData !== null) {
  68184. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68185. var parsedVertexData = vertexData[index];
  68186. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68187. }
  68188. }
  68189. addedGeometry.forEach(function (g) {
  68190. if (g) {
  68191. container.geometries.push(g);
  68192. }
  68193. });
  68194. }
  68195. // Transform nodes
  68196. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68197. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68198. var parsedTransformNode = parsedData.transformNodes[index];
  68199. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68200. container.transformNodes.push(node);
  68201. }
  68202. }
  68203. // Meshes
  68204. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68205. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68206. var parsedMesh = parsedData.meshes[index];
  68207. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68208. container.meshes.push(mesh);
  68209. log += (index === 0 ? "\n\tMeshes:" : "");
  68210. log += "\n\t\t" + mesh.toString(fullDetails);
  68211. }
  68212. }
  68213. // Cameras
  68214. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68215. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68216. var parsedCamera = parsedData.cameras[index];
  68217. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68218. container.cameras.push(camera);
  68219. log += (index === 0 ? "\n\tCameras:" : "");
  68220. log += "\n\t\t" + camera.toString(fullDetails);
  68221. }
  68222. }
  68223. // Browsing all the graph to connect the dots
  68224. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68225. var camera = scene.cameras[index];
  68226. if (camera._waitingParentId) {
  68227. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68228. camera._waitingParentId = null;
  68229. }
  68230. }
  68231. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68232. var light_1 = scene.lights[index];
  68233. if (light_1 && light_1._waitingParentId) {
  68234. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68235. light_1._waitingParentId = null;
  68236. }
  68237. }
  68238. // Sounds
  68239. // TODO: add sound
  68240. var loadedSounds = [];
  68241. var loadedSound;
  68242. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68243. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68244. var parsedSound = parsedData.sounds[index];
  68245. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68246. if (!parsedSound.url)
  68247. parsedSound.url = parsedSound.name;
  68248. if (!loadedSounds[parsedSound.url]) {
  68249. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68250. loadedSounds[parsedSound.url] = loadedSound;
  68251. container.sounds.push(loadedSound);
  68252. }
  68253. else {
  68254. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68255. }
  68256. }
  68257. else {
  68258. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68259. }
  68260. }
  68261. }
  68262. loadedSounds = [];
  68263. // Connect parents & children and parse actions
  68264. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68265. var transformNode = scene.transformNodes[index];
  68266. if (transformNode._waitingParentId) {
  68267. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68268. transformNode._waitingParentId = null;
  68269. }
  68270. }
  68271. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68272. var mesh = scene.meshes[index];
  68273. if (mesh._waitingParentId) {
  68274. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68275. mesh._waitingParentId = null;
  68276. }
  68277. if (mesh._waitingActions) {
  68278. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68279. mesh._waitingActions = null;
  68280. }
  68281. }
  68282. // freeze world matrix application
  68283. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68284. var currentMesh = scene.meshes[index];
  68285. if (currentMesh._waitingFreezeWorldMatrix) {
  68286. currentMesh.freezeWorldMatrix();
  68287. currentMesh._waitingFreezeWorldMatrix = null;
  68288. }
  68289. else {
  68290. currentMesh.computeWorldMatrix(true);
  68291. }
  68292. }
  68293. // Particles Systems
  68294. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68295. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68296. var parsedParticleSystem = parsedData.particleSystems[index];
  68297. if (parsedParticleSystem.activeParticleCount) {
  68298. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68299. container.particleSystems.push(ps);
  68300. }
  68301. else {
  68302. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68303. container.particleSystems.push(ps);
  68304. }
  68305. }
  68306. }
  68307. // Lens flares
  68308. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68309. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68310. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68311. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68312. container.lensFlareSystems.push(lf);
  68313. }
  68314. }
  68315. // Shadows
  68316. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68317. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68318. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68319. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68320. container.shadowGenerators.push(sg);
  68321. }
  68322. }
  68323. // Lights exclusions / inclusions
  68324. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68325. var light_2 = scene.lights[index];
  68326. // Excluded check
  68327. if (light_2._excludedMeshesIds.length > 0) {
  68328. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68329. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68330. if (excludedMesh) {
  68331. light_2.excludedMeshes.push(excludedMesh);
  68332. }
  68333. }
  68334. light_2._excludedMeshesIds = [];
  68335. }
  68336. // Included check
  68337. if (light_2._includedOnlyMeshesIds.length > 0) {
  68338. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68339. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68340. if (includedOnlyMesh) {
  68341. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68342. }
  68343. }
  68344. light_2._includedOnlyMeshesIds = [];
  68345. }
  68346. }
  68347. // Effect layers
  68348. if (parsedData.effectLayers) {
  68349. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68350. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68351. container.effectLayers.push(effectLayer);
  68352. }
  68353. }
  68354. // Actions (scene)
  68355. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68356. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68357. }
  68358. if (!addToScene) {
  68359. container.removeAllFromScene();
  68360. }
  68361. }
  68362. catch (err) {
  68363. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68364. if (onError) {
  68365. onError(msg, err);
  68366. }
  68367. else {
  68368. BABYLON.Tools.Log(msg);
  68369. throw err;
  68370. }
  68371. }
  68372. finally {
  68373. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68374. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68375. }
  68376. }
  68377. return container;
  68378. };
  68379. BABYLON.SceneLoader.RegisterPlugin({
  68380. name: "babylon.js",
  68381. extensions: ".babylon",
  68382. canDirectLoad: function (data) {
  68383. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68384. return true;
  68385. }
  68386. return false;
  68387. },
  68388. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68389. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68390. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68391. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68392. // and avoid problems with multiple concurrent .babylon loads.
  68393. var log = "importMesh has failed JSON parse";
  68394. try {
  68395. var parsedData = JSON.parse(data);
  68396. log = "";
  68397. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68398. if (!meshesNames) {
  68399. meshesNames = null;
  68400. }
  68401. else if (!Array.isArray(meshesNames)) {
  68402. meshesNames = [meshesNames];
  68403. }
  68404. var hierarchyIds = new Array();
  68405. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68406. var loadedSkeletonsIds = [];
  68407. var loadedMaterialsIds = [];
  68408. var index;
  68409. var cache;
  68410. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68411. var parsedMesh = parsedData.meshes[index];
  68412. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68413. if (meshesNames !== null) {
  68414. // Remove found mesh name from list.
  68415. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68416. }
  68417. //Geometry?
  68418. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68419. //does the file contain geometries?
  68420. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68421. //find the correct geometry and add it to the scene
  68422. var found = false;
  68423. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68424. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68425. return;
  68426. }
  68427. else {
  68428. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68429. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68430. switch (geometryType) {
  68431. case "boxes":
  68432. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68433. break;
  68434. case "spheres":
  68435. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68436. break;
  68437. case "cylinders":
  68438. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68439. break;
  68440. case "toruses":
  68441. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68442. break;
  68443. case "grounds":
  68444. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68445. break;
  68446. case "planes":
  68447. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68448. break;
  68449. case "torusKnots":
  68450. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68451. break;
  68452. case "vertexData":
  68453. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68454. break;
  68455. }
  68456. found = true;
  68457. }
  68458. });
  68459. }
  68460. });
  68461. if (found === false) {
  68462. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68463. }
  68464. }
  68465. }
  68466. // Material ?
  68467. if (parsedMesh.materialId) {
  68468. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68469. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68470. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68471. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68472. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68473. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68474. var subMatId = parsedMultiMaterial.materials[matIndex];
  68475. loadedMaterialsIds.push(subMatId);
  68476. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68477. if (mat) {
  68478. log += "\n\tMaterial " + mat.toString(fullDetails);
  68479. }
  68480. }
  68481. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68482. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68483. if (mmat) {
  68484. materialFound = true;
  68485. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68486. }
  68487. break;
  68488. }
  68489. }
  68490. }
  68491. if (materialFound === false) {
  68492. loadedMaterialsIds.push(parsedMesh.materialId);
  68493. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68494. if (!mat) {
  68495. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68496. }
  68497. else {
  68498. log += "\n\tMaterial " + mat.toString(fullDetails);
  68499. }
  68500. }
  68501. }
  68502. // Skeleton ?
  68503. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68504. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68505. if (skeletonAlreadyLoaded === false) {
  68506. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68507. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68508. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68509. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68510. skeletons.push(skeleton);
  68511. loadedSkeletonsIds.push(parsedSkeleton.id);
  68512. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68513. }
  68514. }
  68515. }
  68516. }
  68517. // Morph targets ?
  68518. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68519. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68520. var managerData = _a[_i];
  68521. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68522. }
  68523. }
  68524. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68525. meshes.push(mesh);
  68526. log += "\n\tMesh " + mesh.toString(fullDetails);
  68527. }
  68528. }
  68529. // Connecting parents
  68530. var currentMesh;
  68531. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68532. currentMesh = scene.meshes[index];
  68533. if (currentMesh._waitingParentId) {
  68534. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68535. currentMesh._waitingParentId = null;
  68536. }
  68537. }
  68538. // freeze and compute world matrix application
  68539. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68540. currentMesh = scene.meshes[index];
  68541. if (currentMesh._waitingFreezeWorldMatrix) {
  68542. currentMesh.freezeWorldMatrix();
  68543. currentMesh._waitingFreezeWorldMatrix = null;
  68544. }
  68545. else {
  68546. currentMesh.computeWorldMatrix(true);
  68547. }
  68548. }
  68549. }
  68550. // Particles
  68551. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68552. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68553. var parsedParticleSystem = parsedData.particleSystems[index];
  68554. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68555. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68556. }
  68557. }
  68558. }
  68559. return true;
  68560. }
  68561. catch (err) {
  68562. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68563. if (onError) {
  68564. onError(msg, err);
  68565. }
  68566. else {
  68567. BABYLON.Tools.Log(msg);
  68568. throw err;
  68569. }
  68570. }
  68571. finally {
  68572. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68573. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68574. }
  68575. }
  68576. return false;
  68577. },
  68578. load: function (scene, data, rootUrl, onError) {
  68579. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68580. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68581. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68582. // and avoid problems with multiple concurrent .babylon loads.
  68583. var log = "importScene has failed JSON parse";
  68584. try {
  68585. var parsedData = JSON.parse(data);
  68586. log = "";
  68587. // Scene
  68588. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68589. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68590. }
  68591. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68592. scene.autoClear = parsedData.autoClear;
  68593. }
  68594. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68595. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68596. }
  68597. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68598. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68599. }
  68600. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68601. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68602. }
  68603. // Fog
  68604. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68605. scene.fogMode = parsedData.fogMode;
  68606. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68607. scene.fogStart = parsedData.fogStart;
  68608. scene.fogEnd = parsedData.fogEnd;
  68609. scene.fogDensity = parsedData.fogDensity;
  68610. log += "\tFog mode for scene: ";
  68611. switch (scene.fogMode) {
  68612. // getters not compiling, so using hardcoded
  68613. case 1:
  68614. log += "exp\n";
  68615. break;
  68616. case 2:
  68617. log += "exp2\n";
  68618. break;
  68619. case 3:
  68620. log += "linear\n";
  68621. break;
  68622. }
  68623. }
  68624. //Physics
  68625. if (parsedData.physicsEnabled) {
  68626. var physicsPlugin;
  68627. if (parsedData.physicsEngine === "cannon") {
  68628. physicsPlugin = new BABYLON.CannonJSPlugin();
  68629. }
  68630. else if (parsedData.physicsEngine === "oimo") {
  68631. physicsPlugin = new BABYLON.OimoJSPlugin();
  68632. }
  68633. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68634. //else - default engine, which is currently oimo
  68635. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68636. scene.enablePhysics(physicsGravity, physicsPlugin);
  68637. }
  68638. // Metadata
  68639. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68640. scene.metadata = parsedData.metadata;
  68641. }
  68642. //collisions, if defined. otherwise, default is true
  68643. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68644. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68645. }
  68646. scene.workerCollisions = !!parsedData.workerCollisions;
  68647. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68648. if (!container) {
  68649. return false;
  68650. }
  68651. if (parsedData.autoAnimate) {
  68652. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68653. }
  68654. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68655. scene.setActiveCameraByID(parsedData.activeCameraID);
  68656. }
  68657. // Environment texture
  68658. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68659. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68660. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68661. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68662. if (parsedData.environmentTextureRotationY) {
  68663. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68664. }
  68665. scene.environmentTexture = hdrTexture;
  68666. }
  68667. else {
  68668. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68669. if (parsedData.environmentTextureRotationY) {
  68670. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68671. }
  68672. scene.environmentTexture = cubeTexture;
  68673. }
  68674. if (parsedData.createDefaultSkybox === true) {
  68675. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68676. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68677. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68678. }
  68679. }
  68680. // Finish
  68681. return true;
  68682. }
  68683. catch (err) {
  68684. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68685. if (onError) {
  68686. onError(msg, err);
  68687. }
  68688. else {
  68689. BABYLON.Tools.Log(msg);
  68690. throw err;
  68691. }
  68692. }
  68693. finally {
  68694. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68695. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68696. }
  68697. }
  68698. return false;
  68699. },
  68700. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68701. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68702. return container;
  68703. }
  68704. });
  68705. })(BABYLON || (BABYLON = {}));
  68706. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68707. var BABYLON;
  68708. (function (BABYLON) {
  68709. var FilesInput = /** @class */ (function () {
  68710. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68711. this.onProcessFileCallback = function () { return true; };
  68712. this._engine = engine;
  68713. this._currentScene = scene;
  68714. this._sceneLoadedCallback = sceneLoadedCallback;
  68715. this._progressCallback = progressCallback;
  68716. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68717. this._textureLoadingCallback = textureLoadingCallback;
  68718. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68719. this._onReloadCallback = onReloadCallback;
  68720. this._errorCallback = errorCallback;
  68721. }
  68722. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68723. var _this = this;
  68724. if (elementToMonitor) {
  68725. this._elementToMonitor = elementToMonitor;
  68726. this._dragEnterHandler = function (e) { _this.drag(e); };
  68727. this._dragOverHandler = function (e) { _this.drag(e); };
  68728. this._dropHandler = function (e) { _this.drop(e); };
  68729. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68730. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68731. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68732. }
  68733. };
  68734. FilesInput.prototype.dispose = function () {
  68735. if (!this._elementToMonitor) {
  68736. return;
  68737. }
  68738. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68739. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68740. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68741. };
  68742. FilesInput.prototype.renderFunction = function () {
  68743. if (this._additionalRenderLoopLogicCallback) {
  68744. this._additionalRenderLoopLogicCallback();
  68745. }
  68746. if (this._currentScene) {
  68747. if (this._textureLoadingCallback) {
  68748. var remaining = this._currentScene.getWaitingItemsCount();
  68749. if (remaining > 0) {
  68750. this._textureLoadingCallback(remaining);
  68751. }
  68752. }
  68753. this._currentScene.render();
  68754. }
  68755. };
  68756. FilesInput.prototype.drag = function (e) {
  68757. e.stopPropagation();
  68758. e.preventDefault();
  68759. };
  68760. FilesInput.prototype.drop = function (eventDrop) {
  68761. eventDrop.stopPropagation();
  68762. eventDrop.preventDefault();
  68763. this.loadFiles(eventDrop);
  68764. };
  68765. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68766. var _this = this;
  68767. var reader = folder.createReader();
  68768. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68769. reader.readEntries(function (entries) {
  68770. remaining.count += entries.length;
  68771. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68772. var entry = entries_1[_i];
  68773. if (entry.isFile) {
  68774. entry.file(function (file) {
  68775. file.correctName = relativePath + file.name;
  68776. files.push(file);
  68777. if (--remaining.count === 0) {
  68778. callback();
  68779. }
  68780. });
  68781. }
  68782. else if (entry.isDirectory) {
  68783. _this._traverseFolder(entry, files, remaining, callback);
  68784. }
  68785. }
  68786. if (--remaining.count) {
  68787. callback();
  68788. }
  68789. });
  68790. };
  68791. FilesInput.prototype._processFiles = function (files) {
  68792. for (var i = 0; i < files.length; i++) {
  68793. var name = files[i].correctName.toLowerCase();
  68794. var extension = name.split('.').pop();
  68795. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68796. continue;
  68797. }
  68798. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68799. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68800. this._sceneFileToLoad = files[i];
  68801. }
  68802. else {
  68803. FilesInput.FilesToLoad[name] = files[i];
  68804. }
  68805. }
  68806. };
  68807. FilesInput.prototype.loadFiles = function (event) {
  68808. var _this = this;
  68809. if (this._startingProcessingFilesCallback)
  68810. this._startingProcessingFilesCallback();
  68811. // Handling data transfer via drag'n'drop
  68812. if (event && event.dataTransfer && event.dataTransfer.files) {
  68813. this._filesToLoad = event.dataTransfer.files;
  68814. }
  68815. // Handling files from input files
  68816. if (event && event.target && event.target.files) {
  68817. this._filesToLoad = event.target.files;
  68818. }
  68819. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68820. var files_1 = new Array();
  68821. var folders = [];
  68822. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68823. for (var i = 0; i < this._filesToLoad.length; i++) {
  68824. var fileToLoad = this._filesToLoad[i];
  68825. var name_1 = fileToLoad.name.toLowerCase();
  68826. var entry = void 0;
  68827. fileToLoad.correctName = name_1;
  68828. if (items) {
  68829. var item = items[i];
  68830. if (item.getAsEntry) {
  68831. entry = item.getAsEntry();
  68832. }
  68833. else if (item.webkitGetAsEntry) {
  68834. entry = item.webkitGetAsEntry();
  68835. }
  68836. }
  68837. if (!entry) {
  68838. files_1.push(fileToLoad);
  68839. }
  68840. else {
  68841. if (entry.isDirectory) {
  68842. folders.push(entry);
  68843. }
  68844. else {
  68845. files_1.push(fileToLoad);
  68846. }
  68847. }
  68848. }
  68849. if (folders.length === 0) {
  68850. this._processFiles(files_1);
  68851. this._processReload();
  68852. }
  68853. else {
  68854. var remaining = { count: folders.length };
  68855. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68856. var folder = folders_1[_i];
  68857. this._traverseFolder(folder, files_1, remaining, function () {
  68858. _this._processFiles(files_1);
  68859. if (remaining.count === 0) {
  68860. _this._processReload();
  68861. }
  68862. });
  68863. }
  68864. }
  68865. }
  68866. };
  68867. FilesInput.prototype._processReload = function () {
  68868. if (this._onReloadCallback) {
  68869. this._onReloadCallback(this._sceneFileToLoad);
  68870. }
  68871. else {
  68872. this.reload();
  68873. }
  68874. };
  68875. FilesInput.prototype.reload = function () {
  68876. var _this = this;
  68877. // If a scene file has been provided
  68878. if (this._sceneFileToLoad) {
  68879. if (this._currentScene) {
  68880. if (BABYLON.Tools.errorsCount > 0) {
  68881. BABYLON.Tools.ClearLogCache();
  68882. }
  68883. this._engine.stopRenderLoop();
  68884. }
  68885. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68886. if (_this._progressCallback) {
  68887. _this._progressCallback(progress);
  68888. }
  68889. }).then(function (scene) {
  68890. if (_this._currentScene) {
  68891. _this._currentScene.dispose();
  68892. }
  68893. _this._currentScene = scene;
  68894. if (_this._sceneLoadedCallback) {
  68895. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68896. }
  68897. // Wait for textures and shaders to be ready
  68898. _this._currentScene.executeWhenReady(function () {
  68899. _this._engine.runRenderLoop(function () {
  68900. _this.renderFunction();
  68901. });
  68902. });
  68903. }).catch(function (error) {
  68904. if (_this._errorCallback) {
  68905. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68906. }
  68907. });
  68908. }
  68909. else {
  68910. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68911. }
  68912. };
  68913. FilesInput.FilesToLoad = {};
  68914. return FilesInput;
  68915. }());
  68916. BABYLON.FilesInput = FilesInput;
  68917. })(BABYLON || (BABYLON = {}));
  68918. //# sourceMappingURL=babylon.filesInput.js.map
  68919. var BABYLON;
  68920. (function (BABYLON) {
  68921. /**
  68922. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68923. * The underlying implementation relies on an associative array to ensure the best performances.
  68924. * The value can be anything including 'null' but except 'undefined'
  68925. */
  68926. var StringDictionary = /** @class */ (function () {
  68927. function StringDictionary() {
  68928. this._count = 0;
  68929. this._data = {};
  68930. }
  68931. /**
  68932. * This will clear this dictionary and copy the content from the 'source' one.
  68933. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68934. * @param source the dictionary to take the content from and copy to this dictionary
  68935. */
  68936. StringDictionary.prototype.copyFrom = function (source) {
  68937. var _this = this;
  68938. this.clear();
  68939. source.forEach(function (t, v) { return _this.add(t, v); });
  68940. };
  68941. /**
  68942. * Get a value based from its key
  68943. * @param key the given key to get the matching value from
  68944. * @return the value if found, otherwise undefined is returned
  68945. */
  68946. StringDictionary.prototype.get = function (key) {
  68947. var val = this._data[key];
  68948. if (val !== undefined) {
  68949. return val;
  68950. }
  68951. return undefined;
  68952. };
  68953. /**
  68954. * Get a value from its key or add it if it doesn't exist.
  68955. * This method will ensure you that a given key/data will be present in the dictionary.
  68956. * @param key the given key to get the matching value from
  68957. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68958. * The factory will only be invoked if there's no data for the given key.
  68959. * @return the value corresponding to the key.
  68960. */
  68961. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68962. var val = this.get(key);
  68963. if (val !== undefined) {
  68964. return val;
  68965. }
  68966. val = factory(key);
  68967. if (val) {
  68968. this.add(key, val);
  68969. }
  68970. return val;
  68971. };
  68972. /**
  68973. * Get a value from its key if present in the dictionary otherwise add it
  68974. * @param key the key to get the value from
  68975. * @param val if there's no such key/value pair in the dictionary add it with this value
  68976. * @return the value corresponding to the key
  68977. */
  68978. StringDictionary.prototype.getOrAdd = function (key, val) {
  68979. var curVal = this.get(key);
  68980. if (curVal !== undefined) {
  68981. return curVal;
  68982. }
  68983. this.add(key, val);
  68984. return val;
  68985. };
  68986. /**
  68987. * Check if there's a given key in the dictionary
  68988. * @param key the key to check for
  68989. * @return true if the key is present, false otherwise
  68990. */
  68991. StringDictionary.prototype.contains = function (key) {
  68992. return this._data[key] !== undefined;
  68993. };
  68994. /**
  68995. * Add a new key and its corresponding value
  68996. * @param key the key to add
  68997. * @param value the value corresponding to the key
  68998. * @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
  68999. */
  69000. StringDictionary.prototype.add = function (key, value) {
  69001. if (this._data[key] !== undefined) {
  69002. return false;
  69003. }
  69004. this._data[key] = value;
  69005. ++this._count;
  69006. return true;
  69007. };
  69008. StringDictionary.prototype.set = function (key, value) {
  69009. if (this._data[key] === undefined) {
  69010. return false;
  69011. }
  69012. this._data[key] = value;
  69013. return true;
  69014. };
  69015. /**
  69016. * Get the element of the given key and remove it from the dictionary
  69017. * @param key
  69018. */
  69019. StringDictionary.prototype.getAndRemove = function (key) {
  69020. var val = this.get(key);
  69021. if (val !== undefined) {
  69022. delete this._data[key];
  69023. --this._count;
  69024. return val;
  69025. }
  69026. return null;
  69027. };
  69028. /**
  69029. * Remove a key/value from the dictionary.
  69030. * @param key the key to remove
  69031. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69032. */
  69033. StringDictionary.prototype.remove = function (key) {
  69034. if (this.contains(key)) {
  69035. delete this._data[key];
  69036. --this._count;
  69037. return true;
  69038. }
  69039. return false;
  69040. };
  69041. /**
  69042. * Clear the whole content of the dictionary
  69043. */
  69044. StringDictionary.prototype.clear = function () {
  69045. this._data = {};
  69046. this._count = 0;
  69047. };
  69048. Object.defineProperty(StringDictionary.prototype, "count", {
  69049. get: function () {
  69050. return this._count;
  69051. },
  69052. enumerable: true,
  69053. configurable: true
  69054. });
  69055. /**
  69056. * Execute a callback on each key/val of the dictionary.
  69057. * Note that you can remove any element in this dictionary in the callback implementation
  69058. * @param callback the callback to execute on a given key/value pair
  69059. */
  69060. StringDictionary.prototype.forEach = function (callback) {
  69061. for (var cur in this._data) {
  69062. var val = this._data[cur];
  69063. callback(cur, val);
  69064. }
  69065. };
  69066. /**
  69067. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69068. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69069. * Note that you can remove any element in this dictionary in the callback implementation
  69070. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69071. */
  69072. StringDictionary.prototype.first = function (callback) {
  69073. for (var cur in this._data) {
  69074. var val = this._data[cur];
  69075. var res = callback(cur, val);
  69076. if (res) {
  69077. return res;
  69078. }
  69079. }
  69080. return null;
  69081. };
  69082. return StringDictionary;
  69083. }());
  69084. BABYLON.StringDictionary = StringDictionary;
  69085. })(BABYLON || (BABYLON = {}));
  69086. //# sourceMappingURL=babylon.stringDictionary.js.map
  69087. var BABYLON;
  69088. (function (BABYLON) {
  69089. var Tags = /** @class */ (function () {
  69090. function Tags() {
  69091. }
  69092. Tags.EnableFor = function (obj) {
  69093. obj._tags = obj._tags || {};
  69094. obj.hasTags = function () {
  69095. return Tags.HasTags(obj);
  69096. };
  69097. obj.addTags = function (tagsString) {
  69098. return Tags.AddTagsTo(obj, tagsString);
  69099. };
  69100. obj.removeTags = function (tagsString) {
  69101. return Tags.RemoveTagsFrom(obj, tagsString);
  69102. };
  69103. obj.matchesTagsQuery = function (tagsQuery) {
  69104. return Tags.MatchesQuery(obj, tagsQuery);
  69105. };
  69106. };
  69107. Tags.DisableFor = function (obj) {
  69108. delete obj._tags;
  69109. delete obj.hasTags;
  69110. delete obj.addTags;
  69111. delete obj.removeTags;
  69112. delete obj.matchesTagsQuery;
  69113. };
  69114. Tags.HasTags = function (obj) {
  69115. if (!obj._tags) {
  69116. return false;
  69117. }
  69118. return !BABYLON.Tools.IsEmpty(obj._tags);
  69119. };
  69120. Tags.GetTags = function (obj, asString) {
  69121. if (asString === void 0) { asString = true; }
  69122. if (!obj._tags) {
  69123. return null;
  69124. }
  69125. if (asString) {
  69126. var tagsArray = [];
  69127. for (var tag in obj._tags) {
  69128. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69129. tagsArray.push(tag);
  69130. }
  69131. }
  69132. return tagsArray.join(" ");
  69133. }
  69134. else {
  69135. return obj._tags;
  69136. }
  69137. };
  69138. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69139. // a tag cannot start with '||', '&&', and '!'
  69140. // it cannot contain whitespaces
  69141. Tags.AddTagsTo = function (obj, tagsString) {
  69142. if (!tagsString) {
  69143. return;
  69144. }
  69145. if (typeof tagsString !== "string") {
  69146. return;
  69147. }
  69148. var tags = tagsString.split(" ");
  69149. tags.forEach(function (tag, index, array) {
  69150. Tags._AddTagTo(obj, tag);
  69151. });
  69152. };
  69153. Tags._AddTagTo = function (obj, tag) {
  69154. tag = tag.trim();
  69155. if (tag === "" || tag === "true" || tag === "false") {
  69156. return;
  69157. }
  69158. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69159. return;
  69160. }
  69161. Tags.EnableFor(obj);
  69162. obj._tags[tag] = true;
  69163. };
  69164. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69165. if (!Tags.HasTags(obj)) {
  69166. return;
  69167. }
  69168. var tags = tagsString.split(" ");
  69169. for (var t in tags) {
  69170. Tags._RemoveTagFrom(obj, tags[t]);
  69171. }
  69172. };
  69173. Tags._RemoveTagFrom = function (obj, tag) {
  69174. delete obj._tags[tag];
  69175. };
  69176. Tags.MatchesQuery = function (obj, tagsQuery) {
  69177. if (tagsQuery === undefined) {
  69178. return true;
  69179. }
  69180. if (tagsQuery === "") {
  69181. return Tags.HasTags(obj);
  69182. }
  69183. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69184. };
  69185. return Tags;
  69186. }());
  69187. BABYLON.Tags = Tags;
  69188. })(BABYLON || (BABYLON = {}));
  69189. //# sourceMappingURL=babylon.tags.js.map
  69190. var BABYLON;
  69191. (function (BABYLON) {
  69192. /**
  69193. * Class used to evalaute queries containing `and` and `or` operators
  69194. */
  69195. var AndOrNotEvaluator = /** @class */ (function () {
  69196. function AndOrNotEvaluator() {
  69197. }
  69198. /**
  69199. * Evaluate a query
  69200. * @param query defines the query to evaluate
  69201. * @param evaluateCallback defines the callback used to filter result
  69202. * @returns true if the query matches
  69203. */
  69204. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69205. if (!query.match(/\([^\(\)]*\)/g)) {
  69206. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69207. }
  69208. else {
  69209. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69210. // remove parenthesis
  69211. r = r.slice(1, r.length - 1);
  69212. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69213. });
  69214. }
  69215. if (query === "true") {
  69216. return true;
  69217. }
  69218. if (query === "false") {
  69219. return false;
  69220. }
  69221. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69222. };
  69223. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69224. evaluateCallback = evaluateCallback || (function (r) {
  69225. return r === "true" ? true : false;
  69226. });
  69227. var result;
  69228. var or = parenthesisContent.split("||");
  69229. for (var i in or) {
  69230. if (or.hasOwnProperty(i)) {
  69231. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69232. var and = ori.split("&&");
  69233. if (and.length > 1) {
  69234. for (var j = 0; j < and.length; ++j) {
  69235. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69236. if (andj !== "true" && andj !== "false") {
  69237. if (andj[0] === "!") {
  69238. result = !evaluateCallback(andj.substring(1));
  69239. }
  69240. else {
  69241. result = evaluateCallback(andj);
  69242. }
  69243. }
  69244. else {
  69245. result = andj === "true" ? true : false;
  69246. }
  69247. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69248. ori = "false";
  69249. break;
  69250. }
  69251. }
  69252. }
  69253. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69254. result = true;
  69255. break;
  69256. }
  69257. // result equals false (or undefined)
  69258. if (ori !== "true" && ori !== "false") {
  69259. if (ori[0] === "!") {
  69260. result = !evaluateCallback(ori.substring(1));
  69261. }
  69262. else {
  69263. result = evaluateCallback(ori);
  69264. }
  69265. }
  69266. else {
  69267. result = ori === "true" ? true : false;
  69268. }
  69269. }
  69270. }
  69271. // the whole parenthesis scope is replaced by 'true' or 'false'
  69272. return result ? "true" : "false";
  69273. };
  69274. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69275. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69276. // remove whitespaces
  69277. r = r.replace(/[\s]/g, function () { return ""; });
  69278. return r.length % 2 ? "!" : "";
  69279. });
  69280. booleanString = booleanString.trim();
  69281. if (booleanString === "!true") {
  69282. booleanString = "false";
  69283. }
  69284. else if (booleanString === "!false") {
  69285. booleanString = "true";
  69286. }
  69287. return booleanString;
  69288. };
  69289. return AndOrNotEvaluator;
  69290. }());
  69291. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69292. })(BABYLON || (BABYLON = {}));
  69293. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69294. var BABYLON;
  69295. (function (BABYLON) {
  69296. /**
  69297. * Class used to enable access to IndexedDB
  69298. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69299. */
  69300. var Database = /** @class */ (function () {
  69301. /**
  69302. * Creates a new Database
  69303. * @param urlToScene defines the url to load the scene
  69304. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69305. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69306. */
  69307. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69308. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69309. var _this = this;
  69310. // Handling various flavors of prefixed version of IndexedDB
  69311. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69312. this.callbackManifestChecked = callbackManifestChecked;
  69313. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69314. this.db = null;
  69315. this._enableSceneOffline = false;
  69316. this._enableTexturesOffline = false;
  69317. this.manifestVersionFound = 0;
  69318. this.mustUpdateRessources = false;
  69319. this.hasReachedQuota = false;
  69320. if (!Database.IDBStorageEnabled) {
  69321. this.callbackManifestChecked(true);
  69322. }
  69323. else {
  69324. if (disableManifestCheck) {
  69325. this._enableSceneOffline = true;
  69326. this._enableTexturesOffline = true;
  69327. this.manifestVersionFound = 1;
  69328. BABYLON.Tools.SetImmediate(function () {
  69329. _this.callbackManifestChecked(true);
  69330. });
  69331. }
  69332. else {
  69333. this._checkManifestFile();
  69334. }
  69335. }
  69336. }
  69337. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69338. /**
  69339. * Gets a boolean indicating if scene must be saved in the database
  69340. */
  69341. get: function () {
  69342. return this._enableSceneOffline;
  69343. },
  69344. enumerable: true,
  69345. configurable: true
  69346. });
  69347. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69348. /**
  69349. * Gets a boolean indicating if textures must be saved in the database
  69350. */
  69351. get: function () {
  69352. return this._enableTexturesOffline;
  69353. },
  69354. enumerable: true,
  69355. configurable: true
  69356. });
  69357. Database.prototype._checkManifestFile = function () {
  69358. var _this = this;
  69359. var noManifestFile = function () {
  69360. _this._enableSceneOffline = false;
  69361. _this._enableTexturesOffline = false;
  69362. _this.callbackManifestChecked(false);
  69363. };
  69364. var timeStampUsed = false;
  69365. var manifestURL = this.currentSceneUrl + ".manifest";
  69366. var xhr = new XMLHttpRequest();
  69367. if (navigator.onLine) {
  69368. // Adding a timestamp to by-pass browsers' cache
  69369. timeStampUsed = true;
  69370. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69371. }
  69372. xhr.open("GET", manifestURL, true);
  69373. xhr.addEventListener("load", function () {
  69374. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69375. try {
  69376. var manifestFile = JSON.parse(xhr.response);
  69377. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69378. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69379. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69380. _this.manifestVersionFound = manifestFile.version;
  69381. }
  69382. if (_this.callbackManifestChecked) {
  69383. _this.callbackManifestChecked(true);
  69384. }
  69385. }
  69386. catch (ex) {
  69387. noManifestFile();
  69388. }
  69389. }
  69390. else {
  69391. noManifestFile();
  69392. }
  69393. }, false);
  69394. xhr.addEventListener("error", function (event) {
  69395. if (timeStampUsed) {
  69396. timeStampUsed = false;
  69397. // Let's retry without the timeStamp
  69398. // It could fail when coupled with HTML5 Offline API
  69399. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69400. xhr.open("GET", retryManifestURL, true);
  69401. xhr.send();
  69402. }
  69403. else {
  69404. noManifestFile();
  69405. }
  69406. }, false);
  69407. try {
  69408. xhr.send();
  69409. }
  69410. catch (ex) {
  69411. BABYLON.Tools.Error("Error on XHR send request.");
  69412. this.callbackManifestChecked(false);
  69413. }
  69414. };
  69415. /**
  69416. * Open the database and make it available
  69417. * @param successCallback defines the callback to call on success
  69418. * @param errorCallback defines the callback to call on error
  69419. */
  69420. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69421. var _this = this;
  69422. var handleError = function () {
  69423. _this.isSupported = false;
  69424. if (errorCallback)
  69425. errorCallback();
  69426. };
  69427. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69428. // Your browser doesn't support IndexedDB
  69429. this.isSupported = false;
  69430. if (errorCallback)
  69431. errorCallback();
  69432. }
  69433. else {
  69434. // If the DB hasn't been opened or created yet
  69435. if (!this.db) {
  69436. this.hasReachedQuota = false;
  69437. this.isSupported = true;
  69438. var request = this.idbFactory.open("babylonjs", 1);
  69439. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69440. request.onerror = function (event) {
  69441. handleError();
  69442. };
  69443. // executes when a version change transaction cannot complete due to other active transactions
  69444. request.onblocked = function (event) {
  69445. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69446. handleError();
  69447. };
  69448. // DB has been opened successfully
  69449. request.onsuccess = function (event) {
  69450. _this.db = request.result;
  69451. successCallback();
  69452. };
  69453. // Initialization of the DB. Creating Scenes & Textures stores
  69454. request.onupgradeneeded = function (event) {
  69455. _this.db = (event.target).result;
  69456. if (_this.db) {
  69457. try {
  69458. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69459. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69460. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69461. }
  69462. catch (ex) {
  69463. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69464. handleError();
  69465. }
  69466. }
  69467. };
  69468. }
  69469. // DB has already been created and opened
  69470. else {
  69471. if (successCallback)
  69472. successCallback();
  69473. }
  69474. }
  69475. };
  69476. /**
  69477. * Loads an image from the database
  69478. * @param url defines the url to load from
  69479. * @param image defines the target DOM image
  69480. */
  69481. Database.prototype.loadImageFromDB = function (url, image) {
  69482. var _this = this;
  69483. var completeURL = Database._ReturnFullUrlLocation(url);
  69484. var saveAndLoadImage = function () {
  69485. if (!_this.hasReachedQuota && _this.db !== null) {
  69486. // the texture is not yet in the DB, let's try to save it
  69487. _this._saveImageIntoDBAsync(completeURL, image);
  69488. }
  69489. // If the texture is not in the DB and we've reached the DB quota limit
  69490. // let's load it directly from the web
  69491. else {
  69492. image.src = url;
  69493. }
  69494. };
  69495. if (!this.mustUpdateRessources) {
  69496. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69497. }
  69498. // First time we're download the images or update requested in the manifest file by a version change
  69499. else {
  69500. saveAndLoadImage();
  69501. }
  69502. };
  69503. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69504. if (this.isSupported && this.db !== null) {
  69505. var texture;
  69506. var transaction = this.db.transaction(["textures"]);
  69507. transaction.onabort = function (event) {
  69508. image.src = url;
  69509. };
  69510. transaction.oncomplete = function (event) {
  69511. var blobTextureURL;
  69512. if (texture) {
  69513. var URL = window.URL || window.webkitURL;
  69514. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69515. image.onerror = function () {
  69516. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69517. image.src = url;
  69518. };
  69519. image.src = blobTextureURL;
  69520. }
  69521. else {
  69522. notInDBCallback();
  69523. }
  69524. };
  69525. var getRequest = transaction.objectStore("textures").get(url);
  69526. getRequest.onsuccess = function (event) {
  69527. texture = (event.target).result;
  69528. };
  69529. getRequest.onerror = function (event) {
  69530. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69531. image.src = url;
  69532. };
  69533. }
  69534. else {
  69535. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69536. image.src = url;
  69537. }
  69538. };
  69539. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69540. var _this = this;
  69541. if (this.isSupported) {
  69542. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69543. var generateBlobUrl = function () {
  69544. var blobTextureURL;
  69545. if (blob) {
  69546. var URL = window.URL || window.webkitURL;
  69547. try {
  69548. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69549. }
  69550. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69551. catch (ex) {
  69552. blobTextureURL = URL.createObjectURL(blob);
  69553. }
  69554. }
  69555. if (blobTextureURL) {
  69556. image.src = blobTextureURL;
  69557. }
  69558. };
  69559. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69560. var xhr = new XMLHttpRequest(), blob;
  69561. xhr.open("GET", url, true);
  69562. xhr.responseType = "blob";
  69563. xhr.addEventListener("load", function () {
  69564. if (xhr.status === 200 && _this.db) {
  69565. // Blob as response (XHR2)
  69566. blob = xhr.response;
  69567. var transaction = _this.db.transaction(["textures"], "readwrite");
  69568. // the transaction could abort because of a QuotaExceededError error
  69569. transaction.onabort = function (event) {
  69570. try {
  69571. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69572. var srcElement = (event.srcElement || event.target);
  69573. var error = srcElement.error;
  69574. if (error && error.name === "QuotaExceededError") {
  69575. _this.hasReachedQuota = true;
  69576. }
  69577. }
  69578. catch (ex) { }
  69579. generateBlobUrl();
  69580. };
  69581. transaction.oncomplete = function (event) {
  69582. generateBlobUrl();
  69583. };
  69584. var newTexture = { textureUrl: url, data: blob };
  69585. try {
  69586. // Put the blob into the dabase
  69587. var addRequest = transaction.objectStore("textures").put(newTexture);
  69588. addRequest.onsuccess = function (event) {
  69589. };
  69590. addRequest.onerror = function (event) {
  69591. generateBlobUrl();
  69592. };
  69593. }
  69594. catch (ex) {
  69595. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69596. if (ex.code === 25) {
  69597. Database.IsUASupportingBlobStorage = false;
  69598. }
  69599. image.src = url;
  69600. }
  69601. }
  69602. else {
  69603. image.src = url;
  69604. }
  69605. }, false);
  69606. xhr.addEventListener("error", function (event) {
  69607. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69608. image.src = url;
  69609. }, false);
  69610. xhr.send();
  69611. }
  69612. else {
  69613. image.src = url;
  69614. }
  69615. }
  69616. else {
  69617. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69618. image.src = url;
  69619. }
  69620. };
  69621. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69622. var _this = this;
  69623. var updateVersion = function () {
  69624. // the version is not yet in the DB or we need to update it
  69625. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69626. };
  69627. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69628. };
  69629. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69630. var _this = this;
  69631. if (this.isSupported && this.db) {
  69632. var version;
  69633. try {
  69634. var transaction = this.db.transaction(["versions"]);
  69635. transaction.oncomplete = function (event) {
  69636. if (version) {
  69637. // If the version in the JSON file is different from the version in DB
  69638. if (_this.manifestVersionFound !== version.data) {
  69639. _this.mustUpdateRessources = true;
  69640. updateInDBCallback();
  69641. }
  69642. else {
  69643. callback(version.data);
  69644. }
  69645. }
  69646. // version was not found in DB
  69647. else {
  69648. _this.mustUpdateRessources = true;
  69649. updateInDBCallback();
  69650. }
  69651. };
  69652. transaction.onabort = function (event) {
  69653. callback(-1);
  69654. };
  69655. var getRequest = transaction.objectStore("versions").get(url);
  69656. getRequest.onsuccess = function (event) {
  69657. version = (event.target).result;
  69658. };
  69659. getRequest.onerror = function (event) {
  69660. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69661. callback(-1);
  69662. };
  69663. }
  69664. catch (ex) {
  69665. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69666. callback(-1);
  69667. }
  69668. }
  69669. else {
  69670. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69671. callback(-1);
  69672. }
  69673. };
  69674. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69675. var _this = this;
  69676. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69677. try {
  69678. // Open a transaction to the database
  69679. var transaction = this.db.transaction(["versions"], "readwrite");
  69680. // the transaction could abort because of a QuotaExceededError error
  69681. transaction.onabort = function (event) {
  69682. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69683. var error = event.srcElement['error'];
  69684. if (error && error.name === "QuotaExceededError") {
  69685. _this.hasReachedQuota = true;
  69686. }
  69687. }
  69688. catch (ex) { }
  69689. callback(-1);
  69690. };
  69691. transaction.oncomplete = function (event) {
  69692. callback(_this.manifestVersionFound);
  69693. };
  69694. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69695. // Put the scene into the database
  69696. var addRequest = transaction.objectStore("versions").put(newVersion);
  69697. addRequest.onsuccess = function (event) {
  69698. };
  69699. addRequest.onerror = function (event) {
  69700. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69701. };
  69702. }
  69703. catch (ex) {
  69704. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69705. callback(-1);
  69706. }
  69707. }
  69708. else {
  69709. callback(-1);
  69710. }
  69711. };
  69712. /**
  69713. * Loads a file from database
  69714. * @param url defines the URL to load from
  69715. * @param sceneLoaded defines a callback to call on success
  69716. * @param progressCallBack defines a callback to call when progress changed
  69717. * @param errorCallback defines a callback to call on error
  69718. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69719. */
  69720. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69721. var _this = this;
  69722. var completeUrl = Database._ReturnFullUrlLocation(url);
  69723. var saveAndLoadFile = function () {
  69724. // the scene is not yet in the DB, let's try to save it
  69725. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69726. };
  69727. this._checkVersionFromDB(completeUrl, function (version) {
  69728. if (version !== -1) {
  69729. if (!_this.mustUpdateRessources) {
  69730. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69731. }
  69732. else {
  69733. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69734. }
  69735. }
  69736. else {
  69737. if (errorCallback) {
  69738. errorCallback();
  69739. }
  69740. }
  69741. });
  69742. };
  69743. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69744. if (this.isSupported && this.db) {
  69745. var targetStore;
  69746. if (url.indexOf(".babylon") !== -1) {
  69747. targetStore = "scenes";
  69748. }
  69749. else {
  69750. targetStore = "textures";
  69751. }
  69752. var file;
  69753. var transaction = this.db.transaction([targetStore]);
  69754. transaction.oncomplete = function (event) {
  69755. if (file) {
  69756. callback(file.data);
  69757. }
  69758. // file was not found in DB
  69759. else {
  69760. notInDBCallback();
  69761. }
  69762. };
  69763. transaction.onabort = function (event) {
  69764. notInDBCallback();
  69765. };
  69766. var getRequest = transaction.objectStore(targetStore).get(url);
  69767. getRequest.onsuccess = function (event) {
  69768. file = (event.target).result;
  69769. };
  69770. getRequest.onerror = function (event) {
  69771. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69772. notInDBCallback();
  69773. };
  69774. }
  69775. else {
  69776. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69777. callback();
  69778. }
  69779. };
  69780. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69781. var _this = this;
  69782. if (this.isSupported) {
  69783. var targetStore;
  69784. if (url.indexOf(".babylon") !== -1) {
  69785. targetStore = "scenes";
  69786. }
  69787. else {
  69788. targetStore = "textures";
  69789. }
  69790. // Create XHR
  69791. var xhr = new XMLHttpRequest();
  69792. var fileData;
  69793. xhr.open("GET", url, true);
  69794. if (useArrayBuffer) {
  69795. xhr.responseType = "arraybuffer";
  69796. }
  69797. if (progressCallback) {
  69798. xhr.onprogress = progressCallback;
  69799. }
  69800. xhr.addEventListener("load", function () {
  69801. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69802. // Blob as response (XHR2)
  69803. //fileData = xhr.responseText;
  69804. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69805. if (!_this.hasReachedQuota && _this.db) {
  69806. // Open a transaction to the database
  69807. var transaction = _this.db.transaction([targetStore], "readwrite");
  69808. // the transaction could abort because of a QuotaExceededError error
  69809. transaction.onabort = function (event) {
  69810. try {
  69811. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69812. var error = event.srcElement['error'];
  69813. if (error && error.name === "QuotaExceededError") {
  69814. _this.hasReachedQuota = true;
  69815. }
  69816. }
  69817. catch (ex) { }
  69818. callback(fileData);
  69819. };
  69820. transaction.oncomplete = function (event) {
  69821. callback(fileData);
  69822. };
  69823. var newFile;
  69824. if (targetStore === "scenes") {
  69825. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69826. }
  69827. else {
  69828. newFile = { textureUrl: url, data: fileData };
  69829. }
  69830. try {
  69831. // Put the scene into the database
  69832. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69833. addRequest.onsuccess = function (event) {
  69834. };
  69835. addRequest.onerror = function (event) {
  69836. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69837. };
  69838. }
  69839. catch (ex) {
  69840. callback(fileData);
  69841. }
  69842. }
  69843. else {
  69844. callback(fileData);
  69845. }
  69846. }
  69847. else {
  69848. callback();
  69849. }
  69850. }, false);
  69851. xhr.addEventListener("error", function (event) {
  69852. BABYLON.Tools.Error("error on XHR request.");
  69853. callback();
  69854. }, false);
  69855. xhr.send();
  69856. }
  69857. else {
  69858. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69859. callback();
  69860. }
  69861. };
  69862. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69863. Database.IsUASupportingBlobStorage = true;
  69864. /** Gets a boolean indicating if Database storate is enabled */
  69865. Database.IDBStorageEnabled = true;
  69866. Database._ParseURL = function (url) {
  69867. var a = document.createElement('a');
  69868. a.href = url;
  69869. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69870. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69871. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69872. return absLocation;
  69873. };
  69874. Database._ReturnFullUrlLocation = function (url) {
  69875. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69876. return (Database._ParseURL(window.location.href) + url);
  69877. }
  69878. else {
  69879. return url;
  69880. }
  69881. };
  69882. return Database;
  69883. }());
  69884. BABYLON.Database = Database;
  69885. })(BABYLON || (BABYLON = {}));
  69886. //# sourceMappingURL=babylon.database.js.map
  69887. var BABYLON;
  69888. (function (BABYLON) {
  69889. var FresnelParameters = /** @class */ (function () {
  69890. function FresnelParameters() {
  69891. this._isEnabled = true;
  69892. this.leftColor = BABYLON.Color3.White();
  69893. this.rightColor = BABYLON.Color3.Black();
  69894. this.bias = 0;
  69895. this.power = 1;
  69896. }
  69897. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69898. get: function () {
  69899. return this._isEnabled;
  69900. },
  69901. set: function (value) {
  69902. if (this._isEnabled === value) {
  69903. return;
  69904. }
  69905. this._isEnabled = value;
  69906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69907. },
  69908. enumerable: true,
  69909. configurable: true
  69910. });
  69911. FresnelParameters.prototype.clone = function () {
  69912. var newFresnelParameters = new FresnelParameters();
  69913. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69914. return newFresnelParameters;
  69915. };
  69916. FresnelParameters.prototype.serialize = function () {
  69917. var serializationObject = {};
  69918. serializationObject.isEnabled = this.isEnabled;
  69919. serializationObject.leftColor = this.leftColor.asArray();
  69920. serializationObject.rightColor = this.rightColor.asArray();
  69921. serializationObject.bias = this.bias;
  69922. serializationObject.power = this.power;
  69923. return serializationObject;
  69924. };
  69925. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69926. var fresnelParameters = new FresnelParameters();
  69927. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69928. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69929. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69930. fresnelParameters.bias = parsedFresnelParameters.bias;
  69931. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69932. return fresnelParameters;
  69933. };
  69934. return FresnelParameters;
  69935. }());
  69936. BABYLON.FresnelParameters = FresnelParameters;
  69937. })(BABYLON || (BABYLON = {}));
  69938. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69939. var BABYLON;
  69940. (function (BABYLON) {
  69941. var MultiMaterial = /** @class */ (function (_super) {
  69942. __extends(MultiMaterial, _super);
  69943. function MultiMaterial(name, scene) {
  69944. var _this = _super.call(this, name, scene, true) || this;
  69945. scene.multiMaterials.push(_this);
  69946. _this.subMaterials = new Array();
  69947. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69948. return _this;
  69949. }
  69950. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69951. get: function () {
  69952. return this._subMaterials;
  69953. },
  69954. set: function (value) {
  69955. this._subMaterials = value;
  69956. this._hookArray(value);
  69957. },
  69958. enumerable: true,
  69959. configurable: true
  69960. });
  69961. MultiMaterial.prototype._hookArray = function (array) {
  69962. var _this = this;
  69963. var oldPush = array.push;
  69964. array.push = function () {
  69965. var items = [];
  69966. for (var _i = 0; _i < arguments.length; _i++) {
  69967. items[_i] = arguments[_i];
  69968. }
  69969. var result = oldPush.apply(array, items);
  69970. _this._markAllSubMeshesAsTexturesDirty();
  69971. return result;
  69972. };
  69973. var oldSplice = array.splice;
  69974. array.splice = function (index, deleteCount) {
  69975. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69976. _this._markAllSubMeshesAsTexturesDirty();
  69977. return deleted;
  69978. };
  69979. };
  69980. // Properties
  69981. MultiMaterial.prototype.getSubMaterial = function (index) {
  69982. if (index < 0 || index >= this.subMaterials.length) {
  69983. return this.getScene().defaultMaterial;
  69984. }
  69985. return this.subMaterials[index];
  69986. };
  69987. MultiMaterial.prototype.getActiveTextures = function () {
  69988. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69989. if (subMaterial) {
  69990. return subMaterial.getActiveTextures();
  69991. }
  69992. else {
  69993. return [];
  69994. }
  69995. }));
  69996. var _a;
  69997. };
  69998. // Methods
  69999. MultiMaterial.prototype.getClassName = function () {
  70000. return "MultiMaterial";
  70001. };
  70002. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70003. for (var index = 0; index < this.subMaterials.length; index++) {
  70004. var subMaterial = this.subMaterials[index];
  70005. if (subMaterial) {
  70006. if (subMaterial.storeEffectOnSubMeshes) {
  70007. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70008. return false;
  70009. }
  70010. continue;
  70011. }
  70012. if (!subMaterial.isReady(mesh)) {
  70013. return false;
  70014. }
  70015. }
  70016. }
  70017. return true;
  70018. };
  70019. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70020. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70021. for (var index = 0; index < this.subMaterials.length; index++) {
  70022. var subMaterial = null;
  70023. var current = this.subMaterials[index];
  70024. if (cloneChildren && current) {
  70025. subMaterial = current.clone(name + "-" + current.name);
  70026. }
  70027. else {
  70028. subMaterial = this.subMaterials[index];
  70029. }
  70030. newMultiMaterial.subMaterials.push(subMaterial);
  70031. }
  70032. return newMultiMaterial;
  70033. };
  70034. MultiMaterial.prototype.serialize = function () {
  70035. var serializationObject = {};
  70036. serializationObject.name = this.name;
  70037. serializationObject.id = this.id;
  70038. if (BABYLON.Tags) {
  70039. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70040. }
  70041. serializationObject.materials = [];
  70042. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70043. var subMat = this.subMaterials[matIndex];
  70044. if (subMat) {
  70045. serializationObject.materials.push(subMat.id);
  70046. }
  70047. else {
  70048. serializationObject.materials.push(null);
  70049. }
  70050. }
  70051. return serializationObject;
  70052. };
  70053. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70054. var scene = this.getScene();
  70055. if (!scene) {
  70056. return;
  70057. }
  70058. var index = scene.multiMaterials.indexOf(this);
  70059. if (index >= 0) {
  70060. scene.multiMaterials.splice(index, 1);
  70061. }
  70062. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70063. };
  70064. return MultiMaterial;
  70065. }(BABYLON.Material));
  70066. BABYLON.MultiMaterial = MultiMaterial;
  70067. })(BABYLON || (BABYLON = {}));
  70068. //# sourceMappingURL=babylon.multiMaterial.js.map
  70069. var BABYLON;
  70070. (function (BABYLON) {
  70071. var FreeCameraTouchInput = /** @class */ (function () {
  70072. function FreeCameraTouchInput() {
  70073. this._offsetX = null;
  70074. this._offsetY = null;
  70075. this._pointerPressed = new Array();
  70076. this.touchAngularSensibility = 200000.0;
  70077. this.touchMoveSensibility = 250.0;
  70078. }
  70079. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70080. var _this = this;
  70081. var previousPosition = null;
  70082. if (this._pointerInput === undefined) {
  70083. this._onLostFocus = function (evt) {
  70084. _this._offsetX = null;
  70085. _this._offsetY = null;
  70086. };
  70087. this._pointerInput = function (p, s) {
  70088. var evt = p.event;
  70089. if (evt.pointerType === "mouse") {
  70090. return;
  70091. }
  70092. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70093. if (!noPreventDefault) {
  70094. evt.preventDefault();
  70095. }
  70096. _this._pointerPressed.push(evt.pointerId);
  70097. if (_this._pointerPressed.length !== 1) {
  70098. return;
  70099. }
  70100. previousPosition = {
  70101. x: evt.clientX,
  70102. y: evt.clientY
  70103. };
  70104. }
  70105. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70106. if (!noPreventDefault) {
  70107. evt.preventDefault();
  70108. }
  70109. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70110. if (index === -1) {
  70111. return;
  70112. }
  70113. _this._pointerPressed.splice(index, 1);
  70114. if (index != 0) {
  70115. return;
  70116. }
  70117. previousPosition = null;
  70118. _this._offsetX = null;
  70119. _this._offsetY = null;
  70120. }
  70121. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70122. if (!noPreventDefault) {
  70123. evt.preventDefault();
  70124. }
  70125. if (!previousPosition) {
  70126. return;
  70127. }
  70128. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70129. if (index != 0) {
  70130. return;
  70131. }
  70132. _this._offsetX = evt.clientX - previousPosition.x;
  70133. _this._offsetY = -(evt.clientY - previousPosition.y);
  70134. }
  70135. };
  70136. }
  70137. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70138. if (this._onLostFocus) {
  70139. element.addEventListener("blur", this._onLostFocus);
  70140. }
  70141. };
  70142. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70143. if (this._pointerInput && element) {
  70144. if (this._observer) {
  70145. this.camera.getScene().onPointerObservable.remove(this._observer);
  70146. this._observer = null;
  70147. }
  70148. if (this._onLostFocus) {
  70149. element.removeEventListener("blur", this._onLostFocus);
  70150. this._onLostFocus = null;
  70151. }
  70152. this._pointerPressed = [];
  70153. this._offsetX = null;
  70154. this._offsetY = null;
  70155. }
  70156. };
  70157. FreeCameraTouchInput.prototype.checkInputs = function () {
  70158. if (this._offsetX && this._offsetY) {
  70159. var camera = this.camera;
  70160. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70161. if (this._pointerPressed.length > 1) {
  70162. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70163. }
  70164. else {
  70165. var speed = camera._computeLocalCameraSpeed();
  70166. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70167. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70168. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70169. }
  70170. }
  70171. };
  70172. FreeCameraTouchInput.prototype.getClassName = function () {
  70173. return "FreeCameraTouchInput";
  70174. };
  70175. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70176. return "touch";
  70177. };
  70178. __decorate([
  70179. BABYLON.serialize()
  70180. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70181. __decorate([
  70182. BABYLON.serialize()
  70183. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70184. return FreeCameraTouchInput;
  70185. }());
  70186. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70187. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70188. })(BABYLON || (BABYLON = {}));
  70189. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70190. var BABYLON;
  70191. (function (BABYLON) {
  70192. // We're mainly based on the logic defined into the FreeCamera code
  70193. var TouchCamera = /** @class */ (function (_super) {
  70194. __extends(TouchCamera, _super);
  70195. //-- end properties for backward compatibility for inputs
  70196. function TouchCamera(name, position, scene) {
  70197. var _this = _super.call(this, name, position, scene) || this;
  70198. _this.inputs.addTouch();
  70199. _this._setupInputs();
  70200. return _this;
  70201. }
  70202. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70203. //-- Begin properties for backward compatibility for inputs
  70204. get: function () {
  70205. var touch = this.inputs.attached["touch"];
  70206. if (touch)
  70207. return touch.touchAngularSensibility;
  70208. return 0;
  70209. },
  70210. set: function (value) {
  70211. var touch = this.inputs.attached["touch"];
  70212. if (touch)
  70213. touch.touchAngularSensibility = value;
  70214. },
  70215. enumerable: true,
  70216. configurable: true
  70217. });
  70218. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70219. get: function () {
  70220. var touch = this.inputs.attached["touch"];
  70221. if (touch)
  70222. return touch.touchMoveSensibility;
  70223. return 0;
  70224. },
  70225. set: function (value) {
  70226. var touch = this.inputs.attached["touch"];
  70227. if (touch)
  70228. touch.touchMoveSensibility = value;
  70229. },
  70230. enumerable: true,
  70231. configurable: true
  70232. });
  70233. TouchCamera.prototype.getClassName = function () {
  70234. return "TouchCamera";
  70235. };
  70236. TouchCamera.prototype._setupInputs = function () {
  70237. var mouse = this.inputs.attached["mouse"];
  70238. if (mouse) {
  70239. mouse.touchEnabled = false;
  70240. }
  70241. };
  70242. return TouchCamera;
  70243. }(BABYLON.FreeCamera));
  70244. BABYLON.TouchCamera = TouchCamera;
  70245. })(BABYLON || (BABYLON = {}));
  70246. //# sourceMappingURL=babylon.touchCamera.js.map
  70247. var BABYLON;
  70248. (function (BABYLON) {
  70249. var ProceduralTexture = /** @class */ (function (_super) {
  70250. __extends(ProceduralTexture, _super);
  70251. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70252. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70253. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70254. if (isCube === void 0) { isCube = false; }
  70255. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70256. _this.isCube = isCube;
  70257. _this.isEnabled = true;
  70258. _this._currentRefreshId = -1;
  70259. _this._refreshRate = 1;
  70260. _this._vertexBuffers = {};
  70261. _this._uniforms = new Array();
  70262. _this._samplers = new Array();
  70263. _this._textures = {};
  70264. _this._floats = {};
  70265. _this._floatsArrays = {};
  70266. _this._colors3 = {};
  70267. _this._colors4 = {};
  70268. _this._vectors2 = {};
  70269. _this._vectors3 = {};
  70270. _this._matrices = {};
  70271. _this._fallbackTextureUsed = false;
  70272. scene.proceduralTextures.push(_this);
  70273. _this._engine = scene.getEngine();
  70274. _this.name = name;
  70275. _this.isRenderTarget = true;
  70276. _this._size = size;
  70277. _this._generateMipMaps = generateMipMaps;
  70278. _this.setFragment(fragment);
  70279. _this._fallbackTexture = fallbackTexture;
  70280. if (isCube) {
  70281. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70282. _this.setFloat("face", 0);
  70283. }
  70284. else {
  70285. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70286. }
  70287. // VBO
  70288. var vertices = [];
  70289. vertices.push(1, 1);
  70290. vertices.push(-1, 1);
  70291. vertices.push(-1, -1);
  70292. vertices.push(1, -1);
  70293. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70294. _this._createIndexBuffer();
  70295. return _this;
  70296. }
  70297. ProceduralTexture.prototype._createIndexBuffer = function () {
  70298. var engine = this._engine;
  70299. // Indices
  70300. var indices = [];
  70301. indices.push(0);
  70302. indices.push(1);
  70303. indices.push(2);
  70304. indices.push(0);
  70305. indices.push(2);
  70306. indices.push(3);
  70307. this._indexBuffer = engine.createIndexBuffer(indices);
  70308. };
  70309. ProceduralTexture.prototype._rebuild = function () {
  70310. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70311. if (vb) {
  70312. vb._rebuild();
  70313. }
  70314. this._createIndexBuffer();
  70315. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70316. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70317. }
  70318. };
  70319. ProceduralTexture.prototype.reset = function () {
  70320. if (this._effect === undefined) {
  70321. return;
  70322. }
  70323. var engine = this._engine;
  70324. engine._releaseEffect(this._effect);
  70325. };
  70326. ProceduralTexture.prototype.isReady = function () {
  70327. var _this = this;
  70328. var engine = this._engine;
  70329. var shaders;
  70330. if (!this._fragment) {
  70331. return false;
  70332. }
  70333. if (this._fallbackTextureUsed) {
  70334. return true;
  70335. }
  70336. if (this._fragment.fragmentElement !== undefined) {
  70337. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70338. }
  70339. else {
  70340. shaders = { vertex: "procedural", fragment: this._fragment };
  70341. }
  70342. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70343. _this.releaseInternalTexture();
  70344. if (_this._fallbackTexture) {
  70345. _this._texture = _this._fallbackTexture._texture;
  70346. if (_this._texture) {
  70347. _this._texture.incrementReferences();
  70348. }
  70349. }
  70350. _this._fallbackTextureUsed = true;
  70351. });
  70352. return this._effect.isReady();
  70353. };
  70354. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70355. this._currentRefreshId = -1;
  70356. };
  70357. ProceduralTexture.prototype.setFragment = function (fragment) {
  70358. this._fragment = fragment;
  70359. };
  70360. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70361. get: function () {
  70362. return this._refreshRate;
  70363. },
  70364. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70365. set: function (value) {
  70366. this._refreshRate = value;
  70367. this.resetRefreshCounter();
  70368. },
  70369. enumerable: true,
  70370. configurable: true
  70371. });
  70372. ProceduralTexture.prototype._shouldRender = function () {
  70373. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70374. return false;
  70375. }
  70376. if (this._fallbackTextureUsed) {
  70377. return false;
  70378. }
  70379. if (this._currentRefreshId === -1) { // At least render once
  70380. this._currentRefreshId = 1;
  70381. return true;
  70382. }
  70383. if (this.refreshRate === this._currentRefreshId) {
  70384. this._currentRefreshId = 1;
  70385. return true;
  70386. }
  70387. this._currentRefreshId++;
  70388. return false;
  70389. };
  70390. ProceduralTexture.prototype.getRenderSize = function () {
  70391. return this._size;
  70392. };
  70393. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70394. if (this._fallbackTextureUsed) {
  70395. return;
  70396. }
  70397. this.releaseInternalTexture();
  70398. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70399. };
  70400. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70401. if (this._uniforms.indexOf(uniformName) === -1) {
  70402. this._uniforms.push(uniformName);
  70403. }
  70404. };
  70405. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70406. if (this._samplers.indexOf(name) === -1) {
  70407. this._samplers.push(name);
  70408. }
  70409. this._textures[name] = texture;
  70410. return this;
  70411. };
  70412. ProceduralTexture.prototype.setFloat = function (name, value) {
  70413. this._checkUniform(name);
  70414. this._floats[name] = value;
  70415. return this;
  70416. };
  70417. ProceduralTexture.prototype.setFloats = function (name, value) {
  70418. this._checkUniform(name);
  70419. this._floatsArrays[name] = value;
  70420. return this;
  70421. };
  70422. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70423. this._checkUniform(name);
  70424. this._colors3[name] = value;
  70425. return this;
  70426. };
  70427. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70428. this._checkUniform(name);
  70429. this._colors4[name] = value;
  70430. return this;
  70431. };
  70432. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70433. this._checkUniform(name);
  70434. this._vectors2[name] = value;
  70435. return this;
  70436. };
  70437. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70438. this._checkUniform(name);
  70439. this._vectors3[name] = value;
  70440. return this;
  70441. };
  70442. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70443. this._checkUniform(name);
  70444. this._matrices[name] = value;
  70445. return this;
  70446. };
  70447. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70448. var scene = this.getScene();
  70449. if (!scene) {
  70450. return;
  70451. }
  70452. var engine = this._engine;
  70453. // Render
  70454. engine.enableEffect(this._effect);
  70455. engine.setState(false);
  70456. // Texture
  70457. for (var name in this._textures) {
  70458. this._effect.setTexture(name, this._textures[name]);
  70459. }
  70460. // Float
  70461. for (name in this._floats) {
  70462. this._effect.setFloat(name, this._floats[name]);
  70463. }
  70464. // Floats
  70465. for (name in this._floatsArrays) {
  70466. this._effect.setArray(name, this._floatsArrays[name]);
  70467. }
  70468. // Color3
  70469. for (name in this._colors3) {
  70470. this._effect.setColor3(name, this._colors3[name]);
  70471. }
  70472. // Color4
  70473. for (name in this._colors4) {
  70474. var color = this._colors4[name];
  70475. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70476. }
  70477. // Vector2
  70478. for (name in this._vectors2) {
  70479. this._effect.setVector2(name, this._vectors2[name]);
  70480. }
  70481. // Vector3
  70482. for (name in this._vectors3) {
  70483. this._effect.setVector3(name, this._vectors3[name]);
  70484. }
  70485. // Matrix
  70486. for (name in this._matrices) {
  70487. this._effect.setMatrix(name, this._matrices[name]);
  70488. }
  70489. if (!this._texture) {
  70490. return;
  70491. }
  70492. if (this.isCube) {
  70493. for (var face = 0; face < 6; face++) {
  70494. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70495. // VBOs
  70496. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70497. this._effect.setFloat("face", face);
  70498. // Clear
  70499. engine.clear(scene.clearColor, true, true, true);
  70500. // Draw order
  70501. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70502. // Mipmaps
  70503. if (face === 5) {
  70504. engine.generateMipMapsForCubemap(this._texture);
  70505. }
  70506. }
  70507. }
  70508. else {
  70509. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70510. // VBOs
  70511. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70512. // Clear
  70513. engine.clear(scene.clearColor, true, true, true);
  70514. // Draw order
  70515. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70516. }
  70517. // Unbind
  70518. engine.unBindFramebuffer(this._texture, this.isCube);
  70519. if (this.onGenerated) {
  70520. this.onGenerated();
  70521. }
  70522. };
  70523. ProceduralTexture.prototype.clone = function () {
  70524. var textureSize = this.getSize();
  70525. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70526. // Base texture
  70527. newTexture.hasAlpha = this.hasAlpha;
  70528. newTexture.level = this.level;
  70529. // RenderTarget Texture
  70530. newTexture.coordinatesMode = this.coordinatesMode;
  70531. return newTexture;
  70532. };
  70533. ProceduralTexture.prototype.dispose = function () {
  70534. var scene = this.getScene();
  70535. if (!scene) {
  70536. return;
  70537. }
  70538. var index = scene.proceduralTextures.indexOf(this);
  70539. if (index >= 0) {
  70540. scene.proceduralTextures.splice(index, 1);
  70541. }
  70542. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70543. if (vertexBuffer) {
  70544. vertexBuffer.dispose();
  70545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70546. }
  70547. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70548. this._indexBuffer = null;
  70549. }
  70550. _super.prototype.dispose.call(this);
  70551. };
  70552. return ProceduralTexture;
  70553. }(BABYLON.Texture));
  70554. BABYLON.ProceduralTexture = ProceduralTexture;
  70555. })(BABYLON || (BABYLON = {}));
  70556. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70557. var BABYLON;
  70558. (function (BABYLON) {
  70559. var CustomProceduralTexture = /** @class */ (function (_super) {
  70560. __extends(CustomProceduralTexture, _super);
  70561. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70562. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70563. _this._animate = true;
  70564. _this._time = 0;
  70565. _this._texturePath = texturePath;
  70566. //Try to load json
  70567. _this.loadJson(texturePath);
  70568. _this.refreshRate = 1;
  70569. return _this;
  70570. }
  70571. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70572. var _this = this;
  70573. var noConfigFile = function () {
  70574. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70575. try {
  70576. _this.setFragment(_this._texturePath);
  70577. }
  70578. catch (ex) {
  70579. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70580. }
  70581. };
  70582. var configFileUrl = jsonUrl + "/config.json";
  70583. var xhr = new XMLHttpRequest();
  70584. xhr.open("GET", configFileUrl, true);
  70585. xhr.addEventListener("load", function () {
  70586. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70587. try {
  70588. _this._config = JSON.parse(xhr.response);
  70589. _this.updateShaderUniforms();
  70590. _this.updateTextures();
  70591. _this.setFragment(_this._texturePath + "/custom");
  70592. _this._animate = _this._config.animate;
  70593. _this.refreshRate = _this._config.refreshrate;
  70594. }
  70595. catch (ex) {
  70596. noConfigFile();
  70597. }
  70598. }
  70599. else {
  70600. noConfigFile();
  70601. }
  70602. }, false);
  70603. xhr.addEventListener("error", function () {
  70604. noConfigFile();
  70605. }, false);
  70606. try {
  70607. xhr.send();
  70608. }
  70609. catch (ex) {
  70610. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70611. }
  70612. };
  70613. CustomProceduralTexture.prototype.isReady = function () {
  70614. if (!_super.prototype.isReady.call(this)) {
  70615. return false;
  70616. }
  70617. for (var name in this._textures) {
  70618. var texture = this._textures[name];
  70619. if (!texture.isReady()) {
  70620. return false;
  70621. }
  70622. }
  70623. return true;
  70624. };
  70625. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70626. var scene = this.getScene();
  70627. if (this._animate && scene) {
  70628. this._time += scene.getAnimationRatio() * 0.03;
  70629. this.updateShaderUniforms();
  70630. }
  70631. _super.prototype.render.call(this, useCameraPostProcess);
  70632. };
  70633. CustomProceduralTexture.prototype.updateTextures = function () {
  70634. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70635. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70636. }
  70637. };
  70638. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70639. if (this._config) {
  70640. for (var j = 0; j < this._config.uniforms.length; j++) {
  70641. var uniform = this._config.uniforms[j];
  70642. switch (uniform.type) {
  70643. case "float":
  70644. this.setFloat(uniform.name, uniform.value);
  70645. break;
  70646. case "color3":
  70647. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70648. break;
  70649. case "color4":
  70650. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70651. break;
  70652. case "vector2":
  70653. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70654. break;
  70655. case "vector3":
  70656. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70657. break;
  70658. }
  70659. }
  70660. }
  70661. this.setFloat("time", this._time);
  70662. };
  70663. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70664. get: function () {
  70665. return this._animate;
  70666. },
  70667. set: function (value) {
  70668. this._animate = value;
  70669. },
  70670. enumerable: true,
  70671. configurable: true
  70672. });
  70673. return CustomProceduralTexture;
  70674. }(BABYLON.ProceduralTexture));
  70675. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70676. })(BABYLON || (BABYLON = {}));
  70677. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70678. var BABYLON;
  70679. (function (BABYLON) {
  70680. var FreeCameraGamepadInput = /** @class */ (function () {
  70681. function FreeCameraGamepadInput() {
  70682. this.gamepadAngularSensibility = 200;
  70683. this.gamepadMoveSensibility = 40;
  70684. // private members
  70685. this._cameraTransform = BABYLON.Matrix.Identity();
  70686. this._deltaTransform = BABYLON.Vector3.Zero();
  70687. this._vector3 = BABYLON.Vector3.Zero();
  70688. this._vector2 = BABYLON.Vector2.Zero();
  70689. }
  70690. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70691. var _this = this;
  70692. var manager = this.camera.getScene().gamepadManager;
  70693. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70694. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70695. // prioritize XBOX gamepads.
  70696. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70697. _this.gamepad = gamepad;
  70698. }
  70699. }
  70700. });
  70701. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70702. if (_this.gamepad === gamepad) {
  70703. _this.gamepad = null;
  70704. }
  70705. });
  70706. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70707. };
  70708. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70709. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70710. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70711. this.gamepad = null;
  70712. };
  70713. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70714. if (this.gamepad && this.gamepad.leftStick) {
  70715. var camera = this.camera;
  70716. var LSValues = this.gamepad.leftStick;
  70717. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70718. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70719. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70720. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70721. var RSValues = this.gamepad.rightStick;
  70722. if (RSValues) {
  70723. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70724. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70725. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70726. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70727. }
  70728. else {
  70729. RSValues = { x: 0, y: 0 };
  70730. }
  70731. if (!camera.rotationQuaternion) {
  70732. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70733. }
  70734. else {
  70735. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70736. }
  70737. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70738. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70739. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70740. camera.cameraDirection.addInPlace(this._deltaTransform);
  70741. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70742. camera.cameraRotation.addInPlace(this._vector2);
  70743. }
  70744. };
  70745. FreeCameraGamepadInput.prototype.getClassName = function () {
  70746. return "FreeCameraGamepadInput";
  70747. };
  70748. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70749. return "gamepad";
  70750. };
  70751. __decorate([
  70752. BABYLON.serialize()
  70753. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70754. __decorate([
  70755. BABYLON.serialize()
  70756. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70757. return FreeCameraGamepadInput;
  70758. }());
  70759. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70760. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70761. })(BABYLON || (BABYLON = {}));
  70762. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70763. var BABYLON;
  70764. (function (BABYLON) {
  70765. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70766. function ArcRotateCameraGamepadInput() {
  70767. this.gamepadRotationSensibility = 80;
  70768. this.gamepadMoveSensibility = 40;
  70769. }
  70770. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70771. var _this = this;
  70772. var manager = this.camera.getScene().gamepadManager;
  70773. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70774. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70775. // prioritize XBOX gamepads.
  70776. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70777. _this.gamepad = gamepad;
  70778. }
  70779. }
  70780. });
  70781. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70782. if (_this.gamepad === gamepad) {
  70783. _this.gamepad = null;
  70784. }
  70785. });
  70786. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70787. };
  70788. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70789. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70790. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70791. this.gamepad = null;
  70792. };
  70793. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70794. if (this.gamepad) {
  70795. var camera = this.camera;
  70796. var RSValues = this.gamepad.rightStick;
  70797. if (RSValues) {
  70798. if (RSValues.x != 0) {
  70799. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70800. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70801. camera.inertialAlphaOffset += normalizedRX;
  70802. }
  70803. }
  70804. if (RSValues.y != 0) {
  70805. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70806. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70807. camera.inertialBetaOffset += normalizedRY;
  70808. }
  70809. }
  70810. }
  70811. var LSValues = this.gamepad.leftStick;
  70812. if (LSValues && LSValues.y != 0) {
  70813. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70814. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70815. this.camera.inertialRadiusOffset -= normalizedLY;
  70816. }
  70817. }
  70818. }
  70819. };
  70820. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70821. return "ArcRotateCameraGamepadInput";
  70822. };
  70823. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70824. return "gamepad";
  70825. };
  70826. __decorate([
  70827. BABYLON.serialize()
  70828. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70829. __decorate([
  70830. BABYLON.serialize()
  70831. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70832. return ArcRotateCameraGamepadInput;
  70833. }());
  70834. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70835. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70836. })(BABYLON || (BABYLON = {}));
  70837. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70838. var BABYLON;
  70839. (function (BABYLON) {
  70840. var GamepadManager = /** @class */ (function () {
  70841. function GamepadManager(_scene) {
  70842. var _this = this;
  70843. this._scene = _scene;
  70844. this._babylonGamepads = [];
  70845. this._oneGamepadConnected = false;
  70846. this._isMonitoring = false;
  70847. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70848. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70849. this._gamepadEventSupported = false;
  70850. }
  70851. else {
  70852. this._gamepadEventSupported = 'GamepadEvent' in window;
  70853. this._gamepadSupport = (navigator.getGamepads ||
  70854. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70855. }
  70856. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70857. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70858. for (var i in _this._babylonGamepads) {
  70859. var gamepad = _this._babylonGamepads[i];
  70860. if (gamepad && gamepad._isConnected) {
  70861. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70862. }
  70863. }
  70864. });
  70865. this._onGamepadConnectedEvent = function (evt) {
  70866. var gamepad = evt.gamepad;
  70867. if (gamepad.index in _this._babylonGamepads) {
  70868. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70869. return;
  70870. }
  70871. }
  70872. var newGamepad;
  70873. if (_this._babylonGamepads[gamepad.index]) {
  70874. newGamepad = _this._babylonGamepads[gamepad.index];
  70875. newGamepad.browserGamepad = gamepad;
  70876. newGamepad._isConnected = true;
  70877. }
  70878. else {
  70879. newGamepad = _this._addNewGamepad(gamepad);
  70880. }
  70881. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70882. _this._startMonitoringGamepads();
  70883. };
  70884. this._onGamepadDisconnectedEvent = function (evt) {
  70885. var gamepad = evt.gamepad;
  70886. // Remove the gamepad from the list of gamepads to monitor.
  70887. for (var i in _this._babylonGamepads) {
  70888. if (_this._babylonGamepads[i].index === gamepad.index) {
  70889. var disconnectedGamepad = _this._babylonGamepads[i];
  70890. disconnectedGamepad._isConnected = false;
  70891. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70892. break;
  70893. }
  70894. }
  70895. };
  70896. if (this._gamepadSupport) {
  70897. //first add already-connected gamepads
  70898. this._updateGamepadObjects();
  70899. if (this._babylonGamepads.length) {
  70900. this._startMonitoringGamepads();
  70901. }
  70902. // Checking if the gamepad connected event is supported (like in Firefox)
  70903. if (this._gamepadEventSupported) {
  70904. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70905. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70906. }
  70907. else {
  70908. this._startMonitoringGamepads();
  70909. }
  70910. }
  70911. }
  70912. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70913. get: function () {
  70914. return this._babylonGamepads;
  70915. },
  70916. enumerable: true,
  70917. configurable: true
  70918. });
  70919. GamepadManager.prototype.getGamepadByType = function (type) {
  70920. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70921. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70922. var gamepad = _a[_i];
  70923. if (gamepad && gamepad.type === type) {
  70924. return gamepad;
  70925. }
  70926. }
  70927. return null;
  70928. };
  70929. GamepadManager.prototype.dispose = function () {
  70930. if (this._gamepadEventSupported) {
  70931. if (this._onGamepadConnectedEvent) {
  70932. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70933. }
  70934. if (this._onGamepadDisconnectedEvent) {
  70935. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70936. }
  70937. this._onGamepadConnectedEvent = null;
  70938. this._onGamepadDisconnectedEvent = null;
  70939. }
  70940. this._babylonGamepads.forEach(function (gamepad) {
  70941. gamepad.dispose();
  70942. });
  70943. this.onGamepadConnectedObservable.clear();
  70944. this.onGamepadDisconnectedObservable.clear();
  70945. this._oneGamepadConnected = false;
  70946. this._stopMonitoringGamepads();
  70947. this._babylonGamepads = [];
  70948. };
  70949. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70950. if (!this._oneGamepadConnected) {
  70951. this._oneGamepadConnected = true;
  70952. }
  70953. var newGamepad;
  70954. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70955. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70956. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70957. }
  70958. // if pose is supported, use the (WebVR) pose enabled controller
  70959. else if (gamepad.pose) {
  70960. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70961. }
  70962. else {
  70963. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70964. }
  70965. this._babylonGamepads[newGamepad.index] = newGamepad;
  70966. return newGamepad;
  70967. };
  70968. GamepadManager.prototype._startMonitoringGamepads = function () {
  70969. if (!this._isMonitoring) {
  70970. this._isMonitoring = true;
  70971. //back-comp
  70972. if (!this._scene) {
  70973. this._checkGamepadsStatus();
  70974. }
  70975. }
  70976. };
  70977. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70978. this._isMonitoring = false;
  70979. };
  70980. GamepadManager.prototype._checkGamepadsStatus = function () {
  70981. var _this = this;
  70982. // Hack to be compatible Chrome
  70983. this._updateGamepadObjects();
  70984. for (var i in this._babylonGamepads) {
  70985. var gamepad = this._babylonGamepads[i];
  70986. if (!gamepad || !gamepad.isConnected) {
  70987. continue;
  70988. }
  70989. gamepad.update();
  70990. }
  70991. if (this._isMonitoring && !this._scene) {
  70992. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70993. }
  70994. };
  70995. // This function is called only on Chrome, which does not properly support
  70996. // connection/disconnection events and forces you to recopy again the gamepad object
  70997. GamepadManager.prototype._updateGamepadObjects = function () {
  70998. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70999. for (var i = 0; i < gamepads.length; i++) {
  71000. var gamepad = gamepads[i];
  71001. if (gamepad) {
  71002. if (!this._babylonGamepads[gamepad.index]) {
  71003. var newGamepad = this._addNewGamepad(gamepad);
  71004. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71005. }
  71006. else {
  71007. // Forced to copy again this object for Chrome for unknown reason
  71008. this._babylonGamepads[i].browserGamepad = gamepad;
  71009. if (!this._babylonGamepads[i].isConnected) {
  71010. this._babylonGamepads[i]._isConnected = true;
  71011. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71012. }
  71013. }
  71014. }
  71015. }
  71016. };
  71017. return GamepadManager;
  71018. }());
  71019. BABYLON.GamepadManager = GamepadManager;
  71020. })(BABYLON || (BABYLON = {}));
  71021. //# sourceMappingURL=babylon.gamepadManager.js.map
  71022. var BABYLON;
  71023. (function (BABYLON) {
  71024. var StickValues = /** @class */ (function () {
  71025. function StickValues(x, y) {
  71026. this.x = x;
  71027. this.y = y;
  71028. }
  71029. return StickValues;
  71030. }());
  71031. BABYLON.StickValues = StickValues;
  71032. var Gamepad = /** @class */ (function () {
  71033. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71034. if (leftStickX === void 0) { leftStickX = 0; }
  71035. if (leftStickY === void 0) { leftStickY = 1; }
  71036. if (rightStickX === void 0) { rightStickX = 2; }
  71037. if (rightStickY === void 0) { rightStickY = 3; }
  71038. this.id = id;
  71039. this.index = index;
  71040. this.browserGamepad = browserGamepad;
  71041. this._isConnected = true;
  71042. this._invertLeftStickY = false;
  71043. this.type = Gamepad.GAMEPAD;
  71044. this._leftStickAxisX = leftStickX;
  71045. this._leftStickAxisY = leftStickY;
  71046. this._rightStickAxisX = rightStickX;
  71047. this._rightStickAxisY = rightStickY;
  71048. if (this.browserGamepad.axes.length >= 2) {
  71049. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71050. }
  71051. if (this.browserGamepad.axes.length >= 4) {
  71052. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71053. }
  71054. }
  71055. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71056. get: function () {
  71057. return this._isConnected;
  71058. },
  71059. enumerable: true,
  71060. configurable: true
  71061. });
  71062. Gamepad.prototype.onleftstickchanged = function (callback) {
  71063. this._onleftstickchanged = callback;
  71064. };
  71065. Gamepad.prototype.onrightstickchanged = function (callback) {
  71066. this._onrightstickchanged = callback;
  71067. };
  71068. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71069. get: function () {
  71070. return this._leftStick;
  71071. },
  71072. set: function (newValues) {
  71073. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71074. this._onleftstickchanged(newValues);
  71075. }
  71076. this._leftStick = newValues;
  71077. },
  71078. enumerable: true,
  71079. configurable: true
  71080. });
  71081. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71082. get: function () {
  71083. return this._rightStick;
  71084. },
  71085. set: function (newValues) {
  71086. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71087. this._onrightstickchanged(newValues);
  71088. }
  71089. this._rightStick = newValues;
  71090. },
  71091. enumerable: true,
  71092. configurable: true
  71093. });
  71094. Gamepad.prototype.update = function () {
  71095. if (this._leftStick) {
  71096. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71097. if (this._invertLeftStickY) {
  71098. this.leftStick.y *= -1;
  71099. }
  71100. }
  71101. if (this._rightStick) {
  71102. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71103. }
  71104. };
  71105. Gamepad.prototype.dispose = function () {
  71106. };
  71107. Gamepad.GAMEPAD = 0;
  71108. Gamepad.GENERIC = 1;
  71109. Gamepad.XBOX = 2;
  71110. Gamepad.POSE_ENABLED = 3;
  71111. return Gamepad;
  71112. }());
  71113. BABYLON.Gamepad = Gamepad;
  71114. var GenericPad = /** @class */ (function (_super) {
  71115. __extends(GenericPad, _super);
  71116. function GenericPad(id, index, browserGamepad) {
  71117. var _this = _super.call(this, id, index, browserGamepad) || this;
  71118. _this.onButtonDownObservable = new BABYLON.Observable();
  71119. _this.onButtonUpObservable = new BABYLON.Observable();
  71120. _this.type = Gamepad.GENERIC;
  71121. _this._buttons = new Array(browserGamepad.buttons.length);
  71122. return _this;
  71123. }
  71124. GenericPad.prototype.onbuttondown = function (callback) {
  71125. this._onbuttondown = callback;
  71126. };
  71127. GenericPad.prototype.onbuttonup = function (callback) {
  71128. this._onbuttonup = callback;
  71129. };
  71130. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71131. if (newValue !== currentValue) {
  71132. if (newValue === 1) {
  71133. if (this._onbuttondown) {
  71134. this._onbuttondown(buttonIndex);
  71135. }
  71136. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71137. }
  71138. if (newValue === 0) {
  71139. if (this._onbuttonup) {
  71140. this._onbuttonup(buttonIndex);
  71141. }
  71142. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71143. }
  71144. }
  71145. return newValue;
  71146. };
  71147. GenericPad.prototype.update = function () {
  71148. _super.prototype.update.call(this);
  71149. for (var index = 0; index < this._buttons.length; index++) {
  71150. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71151. }
  71152. };
  71153. GenericPad.prototype.dispose = function () {
  71154. _super.prototype.dispose.call(this);
  71155. this.onButtonDownObservable.clear();
  71156. this.onButtonUpObservable.clear();
  71157. };
  71158. return GenericPad;
  71159. }(Gamepad));
  71160. BABYLON.GenericPad = GenericPad;
  71161. })(BABYLON || (BABYLON = {}));
  71162. //# sourceMappingURL=babylon.gamepad.js.map
  71163. var BABYLON;
  71164. (function (BABYLON) {
  71165. /**
  71166. * Defines supported buttons for XBox360 compatible gamepads
  71167. */
  71168. var Xbox360Button;
  71169. (function (Xbox360Button) {
  71170. /** A */
  71171. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71172. /** B */
  71173. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71174. /** X */
  71175. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71176. /** Y */
  71177. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71178. /** Start */
  71179. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71180. /** Back */
  71181. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71182. /** Left button */
  71183. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71184. /** Right button */
  71185. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71186. /** Left stick */
  71187. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71188. /** Right stick */
  71189. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71190. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71191. /** Defines values for XBox360 DPad */
  71192. var Xbox360Dpad;
  71193. (function (Xbox360Dpad) {
  71194. /** Up */
  71195. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71196. /** Down */
  71197. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71198. /** Left */
  71199. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71200. /** Right */
  71201. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71202. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71203. /**
  71204. * Defines a XBox360 gamepad
  71205. */
  71206. var Xbox360Pad = /** @class */ (function (_super) {
  71207. __extends(Xbox360Pad, _super);
  71208. /**
  71209. * Creates a new XBox360 gamepad object
  71210. * @param id defines the id of this gamepad
  71211. * @param index defines its index
  71212. * @param gamepad defines the internal HTML gamepad object
  71213. * @param xboxOne defines if it is a XBox One gamepad
  71214. */
  71215. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71216. if (xboxOne === void 0) { xboxOne = false; }
  71217. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71218. _this._leftTrigger = 0;
  71219. _this._rightTrigger = 0;
  71220. /** Observable raised when a button is pressed */
  71221. _this.onButtonDownObservable = new BABYLON.Observable();
  71222. /** Observable raised when a button is released */
  71223. _this.onButtonUpObservable = new BABYLON.Observable();
  71224. /** Observable raised when a pad is pressed */
  71225. _this.onPadDownObservable = new BABYLON.Observable();
  71226. /** Observable raised when a pad is released */
  71227. _this.onPadUpObservable = new BABYLON.Observable();
  71228. _this._buttonA = 0;
  71229. _this._buttonB = 0;
  71230. _this._buttonX = 0;
  71231. _this._buttonY = 0;
  71232. _this._buttonBack = 0;
  71233. _this._buttonStart = 0;
  71234. _this._buttonLB = 0;
  71235. _this._buttonRB = 0;
  71236. _this._buttonLeftStick = 0;
  71237. _this._buttonRightStick = 0;
  71238. _this._dPadUp = 0;
  71239. _this._dPadDown = 0;
  71240. _this._dPadLeft = 0;
  71241. _this._dPadRight = 0;
  71242. _this._isXboxOnePad = false;
  71243. _this.type = BABYLON.Gamepad.XBOX;
  71244. _this._isXboxOnePad = xboxOne;
  71245. return _this;
  71246. }
  71247. /**
  71248. * Defines the callback to call when left trigger is pressed
  71249. * @param callback defines the callback to use
  71250. */
  71251. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71252. this._onlefttriggerchanged = callback;
  71253. };
  71254. /**
  71255. * Defines the callback to call when right trigger is pressed
  71256. * @param callback defines the callback to use
  71257. */
  71258. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71259. this._onrighttriggerchanged = callback;
  71260. };
  71261. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71262. /**
  71263. * Gets or sets left trigger value
  71264. */
  71265. get: function () {
  71266. return this._leftTrigger;
  71267. },
  71268. set: function (newValue) {
  71269. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71270. this._onlefttriggerchanged(newValue);
  71271. }
  71272. this._leftTrigger = newValue;
  71273. },
  71274. enumerable: true,
  71275. configurable: true
  71276. });
  71277. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71278. /**
  71279. * Gets or sets right trigger value
  71280. */
  71281. get: function () {
  71282. return this._rightTrigger;
  71283. },
  71284. set: function (newValue) {
  71285. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71286. this._onrighttriggerchanged(newValue);
  71287. }
  71288. this._rightTrigger = newValue;
  71289. },
  71290. enumerable: true,
  71291. configurable: true
  71292. });
  71293. /**
  71294. * Defines the callback to call when a button is pressed
  71295. * @param callback defines the callback to use
  71296. */
  71297. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71298. this._onbuttondown = callback;
  71299. };
  71300. /**
  71301. * Defines the callback to call when a button is released
  71302. * @param callback defines the callback to use
  71303. */
  71304. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71305. this._onbuttonup = callback;
  71306. };
  71307. /**
  71308. * Defines the callback to call when a pad is pressed
  71309. * @param callback defines the callback to use
  71310. */
  71311. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71312. this._ondpaddown = callback;
  71313. };
  71314. /**
  71315. * Defines the callback to call when a pad is released
  71316. * @param callback defines the callback to use
  71317. */
  71318. Xbox360Pad.prototype.ondpadup = function (callback) {
  71319. this._ondpadup = callback;
  71320. };
  71321. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71322. if (newValue !== currentValue) {
  71323. if (newValue === 1) {
  71324. if (this._onbuttondown) {
  71325. this._onbuttondown(buttonType);
  71326. }
  71327. this.onButtonDownObservable.notifyObservers(buttonType);
  71328. }
  71329. if (newValue === 0) {
  71330. if (this._onbuttonup) {
  71331. this._onbuttonup(buttonType);
  71332. }
  71333. this.onButtonUpObservable.notifyObservers(buttonType);
  71334. }
  71335. }
  71336. return newValue;
  71337. };
  71338. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71339. if (newValue !== currentValue) {
  71340. if (newValue === 1) {
  71341. if (this._ondpaddown) {
  71342. this._ondpaddown(buttonType);
  71343. }
  71344. this.onPadDownObservable.notifyObservers(buttonType);
  71345. }
  71346. if (newValue === 0) {
  71347. if (this._ondpadup) {
  71348. this._ondpadup(buttonType);
  71349. }
  71350. this.onPadUpObservable.notifyObservers(buttonType);
  71351. }
  71352. }
  71353. return newValue;
  71354. };
  71355. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71356. /** Gets or sets value of A button */
  71357. get: function () {
  71358. return this._buttonA;
  71359. },
  71360. set: function (value) {
  71361. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71362. },
  71363. enumerable: true,
  71364. configurable: true
  71365. });
  71366. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71367. /** Gets or sets value of B button */
  71368. get: function () {
  71369. return this._buttonB;
  71370. },
  71371. set: function (value) {
  71372. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71373. },
  71374. enumerable: true,
  71375. configurable: true
  71376. });
  71377. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71378. /** Gets or sets value of X button */
  71379. get: function () {
  71380. return this._buttonX;
  71381. },
  71382. set: function (value) {
  71383. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71384. },
  71385. enumerable: true,
  71386. configurable: true
  71387. });
  71388. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71389. /** Gets or sets value of Y button */
  71390. get: function () {
  71391. return this._buttonY;
  71392. },
  71393. set: function (value) {
  71394. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71400. /** Gets or sets value of Start button */
  71401. get: function () {
  71402. return this._buttonStart;
  71403. },
  71404. set: function (value) {
  71405. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71406. },
  71407. enumerable: true,
  71408. configurable: true
  71409. });
  71410. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71411. /** Gets or sets value of Back button */
  71412. get: function () {
  71413. return this._buttonBack;
  71414. },
  71415. set: function (value) {
  71416. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71417. },
  71418. enumerable: true,
  71419. configurable: true
  71420. });
  71421. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71422. /** Gets or sets value of Left button */
  71423. get: function () {
  71424. return this._buttonLB;
  71425. },
  71426. set: function (value) {
  71427. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71428. },
  71429. enumerable: true,
  71430. configurable: true
  71431. });
  71432. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71433. /** Gets or sets value of Right button */
  71434. get: function () {
  71435. return this._buttonRB;
  71436. },
  71437. set: function (value) {
  71438. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71439. },
  71440. enumerable: true,
  71441. configurable: true
  71442. });
  71443. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71444. /** Gets or sets value of left stick */
  71445. get: function () {
  71446. return this._buttonLeftStick;
  71447. },
  71448. set: function (value) {
  71449. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71450. },
  71451. enumerable: true,
  71452. configurable: true
  71453. });
  71454. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71455. /** Gets or sets value of right stick */
  71456. get: function () {
  71457. return this._buttonRightStick;
  71458. },
  71459. set: function (value) {
  71460. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71461. },
  71462. enumerable: true,
  71463. configurable: true
  71464. });
  71465. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71466. /** Gets or sets value of DPad up */
  71467. get: function () {
  71468. return this._dPadUp;
  71469. },
  71470. set: function (value) {
  71471. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71472. },
  71473. enumerable: true,
  71474. configurable: true
  71475. });
  71476. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71477. /** Gets or sets value of DPad down */
  71478. get: function () {
  71479. return this._dPadDown;
  71480. },
  71481. set: function (value) {
  71482. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71483. },
  71484. enumerable: true,
  71485. configurable: true
  71486. });
  71487. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71488. /** Gets or sets value of DPad left */
  71489. get: function () {
  71490. return this._dPadLeft;
  71491. },
  71492. set: function (value) {
  71493. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71494. },
  71495. enumerable: true,
  71496. configurable: true
  71497. });
  71498. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71499. /** Gets or sets value of DPad right */
  71500. get: function () {
  71501. return this._dPadRight;
  71502. },
  71503. set: function (value) {
  71504. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71505. },
  71506. enumerable: true,
  71507. configurable: true
  71508. });
  71509. /**
  71510. * Force the gamepad to synchronize with device values
  71511. */
  71512. Xbox360Pad.prototype.update = function () {
  71513. _super.prototype.update.call(this);
  71514. if (this._isXboxOnePad) {
  71515. this.buttonA = this.browserGamepad.buttons[0].value;
  71516. this.buttonB = this.browserGamepad.buttons[1].value;
  71517. this.buttonX = this.browserGamepad.buttons[2].value;
  71518. this.buttonY = this.browserGamepad.buttons[3].value;
  71519. this.buttonLB = this.browserGamepad.buttons[4].value;
  71520. this.buttonRB = this.browserGamepad.buttons[5].value;
  71521. this.leftTrigger = this.browserGamepad.axes[2];
  71522. this.rightTrigger = this.browserGamepad.axes[5];
  71523. this.buttonBack = this.browserGamepad.buttons[9].value;
  71524. this.buttonStart = this.browserGamepad.buttons[8].value;
  71525. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71526. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71527. this.dPadUp = this.browserGamepad.buttons[11].value;
  71528. this.dPadDown = this.browserGamepad.buttons[12].value;
  71529. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71530. this.dPadRight = this.browserGamepad.buttons[14].value;
  71531. }
  71532. else {
  71533. this.buttonA = this.browserGamepad.buttons[0].value;
  71534. this.buttonB = this.browserGamepad.buttons[1].value;
  71535. this.buttonX = this.browserGamepad.buttons[2].value;
  71536. this.buttonY = this.browserGamepad.buttons[3].value;
  71537. this.buttonLB = this.browserGamepad.buttons[4].value;
  71538. this.buttonRB = this.browserGamepad.buttons[5].value;
  71539. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71540. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71541. this.buttonBack = this.browserGamepad.buttons[8].value;
  71542. this.buttonStart = this.browserGamepad.buttons[9].value;
  71543. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71544. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71545. this.dPadUp = this.browserGamepad.buttons[12].value;
  71546. this.dPadDown = this.browserGamepad.buttons[13].value;
  71547. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71548. this.dPadRight = this.browserGamepad.buttons[15].value;
  71549. }
  71550. };
  71551. Xbox360Pad.prototype.dispose = function () {
  71552. _super.prototype.dispose.call(this);
  71553. this.onButtonDownObservable.clear();
  71554. this.onButtonUpObservable.clear();
  71555. this.onPadDownObservable.clear();
  71556. this.onPadUpObservable.clear();
  71557. };
  71558. return Xbox360Pad;
  71559. }(BABYLON.Gamepad));
  71560. BABYLON.Xbox360Pad = Xbox360Pad;
  71561. })(BABYLON || (BABYLON = {}));
  71562. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71563. var BABYLON;
  71564. (function (BABYLON) {
  71565. /**
  71566. * Defines the types of pose enabled controllers that are supported
  71567. */
  71568. var PoseEnabledControllerType;
  71569. (function (PoseEnabledControllerType) {
  71570. /**
  71571. * HTC Vive
  71572. */
  71573. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71574. /**
  71575. * Oculus Rift
  71576. */
  71577. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71578. /**
  71579. * Windows mixed reality
  71580. */
  71581. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71582. /**
  71583. * Samsung gear VR
  71584. */
  71585. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71586. /**
  71587. * Google Daydream
  71588. */
  71589. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71590. /**
  71591. * Generic
  71592. */
  71593. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71594. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71595. /**
  71596. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71597. */
  71598. var PoseEnabledControllerHelper = /** @class */ (function () {
  71599. function PoseEnabledControllerHelper() {
  71600. }
  71601. /**
  71602. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71603. * @param vrGamepad the gamepad to initialized
  71604. * @returns a vr controller of the type the gamepad identified as
  71605. */
  71606. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71607. // Oculus Touch
  71608. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71609. return new BABYLON.OculusTouchController(vrGamepad);
  71610. }
  71611. // Windows Mixed Reality controllers
  71612. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71613. return new BABYLON.WindowsMotionController(vrGamepad);
  71614. }
  71615. // HTC Vive
  71616. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71617. return new BABYLON.ViveController(vrGamepad);
  71618. }
  71619. // Samsung/Oculus Gear VR or Oculus Go
  71620. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71621. return new BABYLON.GearVRController(vrGamepad);
  71622. }
  71623. // Google Daydream
  71624. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71625. return new BABYLON.DaydreamController(vrGamepad);
  71626. }
  71627. // Generic
  71628. else {
  71629. return new BABYLON.GenericController(vrGamepad);
  71630. }
  71631. };
  71632. return PoseEnabledControllerHelper;
  71633. }());
  71634. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71635. /**
  71636. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71637. */
  71638. var PoseEnabledController = /** @class */ (function (_super) {
  71639. __extends(PoseEnabledController, _super);
  71640. /**
  71641. * Creates a new PoseEnabledController from a gamepad
  71642. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71643. */
  71644. function PoseEnabledController(browserGamepad) {
  71645. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71646. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71647. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71648. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71649. /**
  71650. * The device position in babylon space
  71651. */
  71652. _this.devicePosition = BABYLON.Vector3.Zero();
  71653. /**
  71654. * The device rotation in babylon space
  71655. */
  71656. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71657. /**
  71658. * The scale factor of the device in babylon space
  71659. */
  71660. _this.deviceScaleFactor = 1;
  71661. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71662. /**
  71663. * Internal, matrix used to convert room space to babylon space
  71664. */
  71665. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71666. /**
  71667. * Node to be used when casting a ray from the controller
  71668. */
  71669. _this._pointingPoseNode = null;
  71670. _this._workingMatrix = BABYLON.Matrix.Identity();
  71671. /**
  71672. * @hidden
  71673. */
  71674. _this._meshAttachedObservable = new BABYLON.Observable();
  71675. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71676. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71677. _this.position = BABYLON.Vector3.Zero();
  71678. _this.rotationQuaternion = new BABYLON.Quaternion();
  71679. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71680. _this._calculatedRotation = new BABYLON.Quaternion();
  71681. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71682. return _this;
  71683. }
  71684. /**
  71685. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71686. */
  71687. PoseEnabledController.prototype.update = function () {
  71688. _super.prototype.update.call(this);
  71689. var pose = this.browserGamepad.pose;
  71690. this.updateFromDevice(pose);
  71691. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71692. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71693. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71694. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71695. if (this._mesh) {
  71696. this._mesh.position.copyFrom(this.devicePosition);
  71697. if (this._mesh.rotationQuaternion) {
  71698. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71699. }
  71700. }
  71701. };
  71702. /**
  71703. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71704. * @param poseData raw pose fromthe device
  71705. */
  71706. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71707. if (poseData) {
  71708. this.rawPose = poseData;
  71709. if (poseData.position) {
  71710. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71711. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71712. this._deviceRoomPosition.z *= -1;
  71713. }
  71714. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71715. this._calculatedPosition.addInPlace(this.position);
  71716. }
  71717. var pose = this.rawPose;
  71718. if (poseData.orientation && pose.orientation) {
  71719. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71720. if (this._mesh) {
  71721. if (this._mesh.getScene().useRightHandedSystem) {
  71722. this._deviceRoomRotationQuaternion.z *= -1;
  71723. this._deviceRoomRotationQuaternion.w *= -1;
  71724. }
  71725. else {
  71726. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71727. }
  71728. }
  71729. // if the camera is set, rotate to the camera's rotation
  71730. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71731. }
  71732. }
  71733. };
  71734. /**
  71735. * Attaches a mesh to the controller
  71736. * @param mesh the mesh to be attached
  71737. */
  71738. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71739. if (this._mesh) {
  71740. this._mesh.parent = null;
  71741. }
  71742. this._mesh = mesh;
  71743. if (this._poseControlledCamera) {
  71744. this._mesh.parent = this._poseControlledCamera;
  71745. }
  71746. if (!this._mesh.rotationQuaternion) {
  71747. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71748. }
  71749. this._meshAttachedObservable.notifyObservers(mesh);
  71750. };
  71751. /**
  71752. * Attaches the controllers mesh to a camera
  71753. * @param camera the camera the mesh should be attached to
  71754. */
  71755. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71756. this._poseControlledCamera = camera;
  71757. if (this._mesh) {
  71758. this._mesh.parent = this._poseControlledCamera;
  71759. }
  71760. };
  71761. /**
  71762. * Disposes of the controller
  71763. */
  71764. PoseEnabledController.prototype.dispose = function () {
  71765. if (this._mesh) {
  71766. this._mesh.dispose();
  71767. }
  71768. this._mesh = null;
  71769. _super.prototype.dispose.call(this);
  71770. };
  71771. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71772. /**
  71773. * The mesh that is attached to the controller
  71774. */
  71775. get: function () {
  71776. return this._mesh;
  71777. },
  71778. enumerable: true,
  71779. configurable: true
  71780. });
  71781. /**
  71782. * Gets the ray of the controller in the direction the controller is pointing
  71783. * @param length the length the resulting ray should be
  71784. * @returns a ray in the direction the controller is pointing
  71785. */
  71786. PoseEnabledController.prototype.getForwardRay = function (length) {
  71787. if (length === void 0) { length = 100; }
  71788. if (!this.mesh) {
  71789. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71790. }
  71791. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71792. var origin = m.getTranslation();
  71793. var forward = new BABYLON.Vector3(0, 0, -1);
  71794. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71795. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71796. return new BABYLON.Ray(origin, direction, length);
  71797. };
  71798. /**
  71799. * Name of the child mesh that can be used to cast a ray from the controller
  71800. */
  71801. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71802. return PoseEnabledController;
  71803. }(BABYLON.Gamepad));
  71804. BABYLON.PoseEnabledController = PoseEnabledController;
  71805. })(BABYLON || (BABYLON = {}));
  71806. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71807. var BABYLON;
  71808. (function (BABYLON) {
  71809. /**
  71810. * Defines the WebVRController object that represents controllers tracked in 3D space
  71811. */
  71812. var WebVRController = /** @class */ (function (_super) {
  71813. __extends(WebVRController, _super);
  71814. /**
  71815. * Creates a new WebVRController from a gamepad
  71816. * @param vrGamepad the gamepad that the WebVRController should be created from
  71817. */
  71818. function WebVRController(vrGamepad) {
  71819. var _this = _super.call(this, vrGamepad) || this;
  71820. // Observables
  71821. /**
  71822. * Fired when the trigger state has changed
  71823. */
  71824. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71825. /**
  71826. * Fired when the main button state has changed
  71827. */
  71828. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71829. /**
  71830. * Fired when the secondary button state has changed
  71831. */
  71832. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71833. /**
  71834. * Fired when the pad state has changed
  71835. */
  71836. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71837. /**
  71838. * Fired when controllers stick values have changed
  71839. */
  71840. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71841. /**
  71842. * X and Y axis corrisponding to the controllers joystick
  71843. */
  71844. _this.pad = { x: 0, y: 0 };
  71845. // avoid GC, store state in a tmp object
  71846. _this._changes = {
  71847. pressChanged: false,
  71848. touchChanged: false,
  71849. valueChanged: false,
  71850. changed: false
  71851. };
  71852. _this._buttons = new Array(vrGamepad.buttons.length);
  71853. _this.hand = vrGamepad.hand;
  71854. return _this;
  71855. }
  71856. /**
  71857. * Fired when a controller button's state has changed
  71858. * @param callback the callback containing the button that was modified
  71859. */
  71860. WebVRController.prototype.onButtonStateChange = function (callback) {
  71861. this._onButtonStateChange = callback;
  71862. };
  71863. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71864. /**
  71865. * The default controller model for the controller
  71866. */
  71867. get: function () {
  71868. return this._defaultModel;
  71869. },
  71870. enumerable: true,
  71871. configurable: true
  71872. });
  71873. /**
  71874. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71875. */
  71876. WebVRController.prototype.update = function () {
  71877. _super.prototype.update.call(this);
  71878. for (var index = 0; index < this._buttons.length; index++) {
  71879. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71880. }
  71881. ;
  71882. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71883. this.pad.x = this.leftStick.x;
  71884. this.pad.y = this.leftStick.y;
  71885. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71886. }
  71887. };
  71888. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71889. if (!newState) {
  71890. newState = {
  71891. pressed: false,
  71892. touched: false,
  71893. value: 0
  71894. };
  71895. }
  71896. if (!currentState) {
  71897. this._buttons[buttonIndex] = {
  71898. pressed: newState.pressed,
  71899. touched: newState.touched,
  71900. value: newState.value
  71901. };
  71902. return;
  71903. }
  71904. this._checkChanges(newState, currentState);
  71905. if (this._changes.changed) {
  71906. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71907. this._handleButtonChange(buttonIndex, newState, this._changes);
  71908. }
  71909. this._buttons[buttonIndex].pressed = newState.pressed;
  71910. this._buttons[buttonIndex].touched = newState.touched;
  71911. // oculus triggers are never 0, thou not touched.
  71912. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71913. };
  71914. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71915. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71916. this._changes.touchChanged = newState.touched !== currentState.touched;
  71917. this._changes.valueChanged = newState.value !== currentState.value;
  71918. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71919. return this._changes;
  71920. };
  71921. /**
  71922. * Disposes of th webVRCOntroller
  71923. */
  71924. WebVRController.prototype.dispose = function () {
  71925. _super.prototype.dispose.call(this);
  71926. this.onTriggerStateChangedObservable.clear();
  71927. this.onMainButtonStateChangedObservable.clear();
  71928. this.onSecondaryButtonStateChangedObservable.clear();
  71929. this.onPadStateChangedObservable.clear();
  71930. this.onPadValuesChangedObservable.clear();
  71931. };
  71932. return WebVRController;
  71933. }(BABYLON.PoseEnabledController));
  71934. BABYLON.WebVRController = WebVRController;
  71935. })(BABYLON || (BABYLON = {}));
  71936. //# sourceMappingURL=babylon.webVRController.js.map
  71937. var BABYLON;
  71938. (function (BABYLON) {
  71939. /**
  71940. * Oculus Touch Controller
  71941. */
  71942. var OculusTouchController = /** @class */ (function (_super) {
  71943. __extends(OculusTouchController, _super);
  71944. /**
  71945. * Creates a new OculusTouchController from a gamepad
  71946. * @param vrGamepad the gamepad that the controller should be created from
  71947. */
  71948. function OculusTouchController(vrGamepad) {
  71949. var _this = _super.call(this, vrGamepad) || this;
  71950. /**
  71951. * Fired when the secondary trigger on this controller is modified
  71952. */
  71953. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71954. /**
  71955. * Fired when the thumb rest on this controller is modified
  71956. */
  71957. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71958. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71959. return _this;
  71960. }
  71961. /**
  71962. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71963. * @param scene scene in which to add meshes
  71964. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71965. */
  71966. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71967. var _this = this;
  71968. var meshName;
  71969. // Hand
  71970. if (this.hand === 'left') {
  71971. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71972. }
  71973. else { // Right is the default if no hand is specified
  71974. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71975. }
  71976. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71977. /*
  71978. Parent Mesh name: oculus_touch_left
  71979. - body
  71980. - trigger
  71981. - thumbstick
  71982. - grip
  71983. - button_y
  71984. - button_x
  71985. - button_enter
  71986. */
  71987. _this._defaultModel = newMeshes[1];
  71988. _this.attachToMesh(_this._defaultModel);
  71989. if (meshLoaded) {
  71990. meshLoaded(_this._defaultModel);
  71991. }
  71992. });
  71993. };
  71994. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71995. /**
  71996. * Fired when the A button on this controller is modified
  71997. */
  71998. get: function () {
  71999. if (this.hand === 'right') {
  72000. return this.onMainButtonStateChangedObservable;
  72001. }
  72002. else {
  72003. throw new Error('No A button on left hand');
  72004. }
  72005. },
  72006. enumerable: true,
  72007. configurable: true
  72008. });
  72009. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72010. /**
  72011. * Fired when the B button on this controller is modified
  72012. */
  72013. get: function () {
  72014. if (this.hand === 'right') {
  72015. return this.onSecondaryButtonStateChangedObservable;
  72016. }
  72017. else {
  72018. throw new Error('No B button on left hand');
  72019. }
  72020. },
  72021. enumerable: true,
  72022. configurable: true
  72023. });
  72024. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72025. /**
  72026. * Fired when the X button on this controller is modified
  72027. */
  72028. get: function () {
  72029. if (this.hand === 'left') {
  72030. return this.onMainButtonStateChangedObservable;
  72031. }
  72032. else {
  72033. throw new Error('No X button on right hand');
  72034. }
  72035. },
  72036. enumerable: true,
  72037. configurable: true
  72038. });
  72039. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72040. /**
  72041. * Fired when the Y button on this controller is modified
  72042. */
  72043. get: function () {
  72044. if (this.hand === 'left') {
  72045. return this.onSecondaryButtonStateChangedObservable;
  72046. }
  72047. else {
  72048. throw new Error('No Y button on right hand');
  72049. }
  72050. },
  72051. enumerable: true,
  72052. configurable: true
  72053. });
  72054. /**
  72055. * Called once for each button that changed state since the last frame
  72056. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72057. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72058. * 2) secondary trigger (same)
  72059. * 3) A (right) X (left), touch, pressed = value
  72060. * 4) B / Y
  72061. * 5) thumb rest
  72062. * @param buttonIdx Which button index changed
  72063. * @param state New state of the button
  72064. * @param changes Which properties on the state changed since last frame
  72065. */
  72066. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72067. var notifyObject = state; //{ state: state, changes: changes };
  72068. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72069. switch (buttonIdx) {
  72070. case 0:
  72071. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72072. return;
  72073. case 1: // index trigger
  72074. if (this._defaultModel) {
  72075. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72076. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72077. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72078. }
  72079. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72080. return;
  72081. case 2: // secondary trigger
  72082. if (this._defaultModel) {
  72083. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72084. }
  72085. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72086. return;
  72087. case 3:
  72088. if (this._defaultModel) {
  72089. if (notifyObject.pressed) {
  72090. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72091. }
  72092. else {
  72093. (this._defaultModel.getChildren()[1]).position.y = 0;
  72094. }
  72095. }
  72096. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72097. return;
  72098. case 4:
  72099. if (this._defaultModel) {
  72100. if (notifyObject.pressed) {
  72101. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72102. }
  72103. else {
  72104. (this._defaultModel.getChildren()[2]).position.y = 0;
  72105. }
  72106. }
  72107. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72108. return;
  72109. case 5:
  72110. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72111. return;
  72112. }
  72113. };
  72114. /**
  72115. * Base Url for the controller model.
  72116. */
  72117. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72118. /**
  72119. * File name for the left controller model.
  72120. */
  72121. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72122. /**
  72123. * File name for the right controller model.
  72124. */
  72125. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72126. return OculusTouchController;
  72127. }(BABYLON.WebVRController));
  72128. BABYLON.OculusTouchController = OculusTouchController;
  72129. })(BABYLON || (BABYLON = {}));
  72130. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72131. var BABYLON;
  72132. (function (BABYLON) {
  72133. /**
  72134. * Vive Controller
  72135. */
  72136. var ViveController = /** @class */ (function (_super) {
  72137. __extends(ViveController, _super);
  72138. /**
  72139. * Creates a new ViveController from a gamepad
  72140. * @param vrGamepad the gamepad that the controller should be created from
  72141. */
  72142. function ViveController(vrGamepad) {
  72143. var _this = _super.call(this, vrGamepad) || this;
  72144. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72145. _this._invertLeftStickY = true;
  72146. return _this;
  72147. }
  72148. /**
  72149. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72150. * @param scene scene in which to add meshes
  72151. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72152. */
  72153. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72154. var _this = this;
  72155. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72156. /*
  72157. Parent Mesh name: ViveWand
  72158. - body
  72159. - r_gripper
  72160. - l_gripper
  72161. - menu_button
  72162. - system_button
  72163. - trackpad
  72164. - trigger
  72165. - LED
  72166. */
  72167. _this._defaultModel = newMeshes[1];
  72168. _this.attachToMesh(_this._defaultModel);
  72169. if (meshLoaded) {
  72170. meshLoaded(_this._defaultModel);
  72171. }
  72172. });
  72173. };
  72174. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72175. /**
  72176. * Fired when the left button on this controller is modified
  72177. */
  72178. get: function () {
  72179. return this.onMainButtonStateChangedObservable;
  72180. },
  72181. enumerable: true,
  72182. configurable: true
  72183. });
  72184. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72185. /**
  72186. * Fired when the right button on this controller is modified
  72187. */
  72188. get: function () {
  72189. return this.onMainButtonStateChangedObservable;
  72190. },
  72191. enumerable: true,
  72192. configurable: true
  72193. });
  72194. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72195. /**
  72196. * Fired when the menu button on this controller is modified
  72197. */
  72198. get: function () {
  72199. return this.onSecondaryButtonStateChangedObservable;
  72200. },
  72201. enumerable: true,
  72202. configurable: true
  72203. });
  72204. /**
  72205. * Called once for each button that changed state since the last frame
  72206. * Vive mapping:
  72207. * 0: touchpad
  72208. * 1: trigger
  72209. * 2: left AND right buttons
  72210. * 3: menu button
  72211. * @param buttonIdx Which button index changed
  72212. * @param state New state of the button
  72213. * @param changes Which properties on the state changed since last frame
  72214. */
  72215. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72216. var notifyObject = state; //{ state: state, changes: changes };
  72217. switch (buttonIdx) {
  72218. case 0:
  72219. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72220. return;
  72221. case 1: // index trigger
  72222. if (this._defaultModel) {
  72223. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72224. }
  72225. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72226. return;
  72227. case 2: // left AND right button
  72228. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72229. return;
  72230. case 3:
  72231. if (this._defaultModel) {
  72232. if (notifyObject.pressed) {
  72233. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72234. }
  72235. else {
  72236. (this._defaultModel.getChildren()[2]).position.y = 0;
  72237. }
  72238. }
  72239. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72240. return;
  72241. }
  72242. };
  72243. /**
  72244. * Base Url for the controller model.
  72245. */
  72246. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72247. /**
  72248. * File name for the controller model.
  72249. */
  72250. ViveController.MODEL_FILENAME = 'wand.babylon';
  72251. return ViveController;
  72252. }(BABYLON.WebVRController));
  72253. BABYLON.ViveController = ViveController;
  72254. })(BABYLON || (BABYLON = {}));
  72255. //# sourceMappingURL=babylon.viveController.js.map
  72256. var BABYLON;
  72257. (function (BABYLON) {
  72258. /**
  72259. * Generic Controller
  72260. */
  72261. var GenericController = /** @class */ (function (_super) {
  72262. __extends(GenericController, _super);
  72263. /**
  72264. * Creates a new GenericController from a gamepad
  72265. * @param vrGamepad the gamepad that the controller should be created from
  72266. */
  72267. function GenericController(vrGamepad) {
  72268. return _super.call(this, vrGamepad) || this;
  72269. }
  72270. /**
  72271. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72272. * @param scene scene in which to add meshes
  72273. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72274. */
  72275. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72276. var _this = this;
  72277. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72278. _this._defaultModel = newMeshes[1];
  72279. _this.attachToMesh(_this._defaultModel);
  72280. if (meshLoaded) {
  72281. meshLoaded(_this._defaultModel);
  72282. }
  72283. });
  72284. };
  72285. /**
  72286. * Called once for each button that changed state since the last frame
  72287. * @param buttonIdx Which button index changed
  72288. * @param state New state of the button
  72289. * @param changes Which properties on the state changed since last frame
  72290. */
  72291. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72292. console.log("Button id: " + buttonIdx + "state: ");
  72293. console.dir(state);
  72294. };
  72295. /**
  72296. * Base Url for the controller model.
  72297. */
  72298. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72299. /**
  72300. * File name for the controller model.
  72301. */
  72302. GenericController.MODEL_FILENAME = 'generic.babylon';
  72303. return GenericController;
  72304. }(BABYLON.WebVRController));
  72305. BABYLON.GenericController = GenericController;
  72306. })(BABYLON || (BABYLON = {}));
  72307. //# sourceMappingURL=babylon.genericController.js.map
  72308. var BABYLON;
  72309. (function (BABYLON) {
  72310. /**
  72311. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72312. */
  72313. var LoadedMeshInfo = /** @class */ (function () {
  72314. function LoadedMeshInfo() {
  72315. /**
  72316. * Map of the button meshes contained in the controller
  72317. */
  72318. this.buttonMeshes = {};
  72319. /**
  72320. * Map of the axis meshes contained in the controller
  72321. */
  72322. this.axisMeshes = {};
  72323. }
  72324. return LoadedMeshInfo;
  72325. }());
  72326. /**
  72327. * Defines the WindowsMotionController object that the state of the windows motion controller
  72328. */
  72329. var WindowsMotionController = /** @class */ (function (_super) {
  72330. __extends(WindowsMotionController, _super);
  72331. /**
  72332. * Creates a new WindowsMotionController from a gamepad
  72333. * @param vrGamepad the gamepad that the controller should be created from
  72334. */
  72335. function WindowsMotionController(vrGamepad) {
  72336. var _this = _super.call(this, vrGamepad) || this;
  72337. _this._mapping = {
  72338. // Semantic button names
  72339. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72340. // A mapping of the button name to glTF model node name
  72341. // that should be transformed by button value.
  72342. buttonMeshNames: {
  72343. 'trigger': 'SELECT',
  72344. 'menu': 'MENU',
  72345. 'grip': 'GRASP',
  72346. 'thumbstick': 'THUMBSTICK_PRESS',
  72347. 'trackpad': 'TOUCHPAD_PRESS'
  72348. },
  72349. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72350. buttonObservableNames: {
  72351. 'trigger': 'onTriggerStateChangedObservable',
  72352. 'menu': 'onSecondaryButtonStateChangedObservable',
  72353. 'grip': 'onMainButtonStateChangedObservable',
  72354. 'thumbstick': 'onPadStateChangedObservable',
  72355. 'trackpad': 'onTrackpadChangedObservable'
  72356. },
  72357. // A mapping of the axis name to glTF model node name
  72358. // that should be transformed by axis value.
  72359. // This array mirrors the browserGamepad.axes array, such that
  72360. // the mesh corresponding to axis 0 is in this array index 0.
  72361. axisMeshNames: [
  72362. 'THUMBSTICK_X',
  72363. 'THUMBSTICK_Y',
  72364. 'TOUCHPAD_TOUCH_X',
  72365. 'TOUCHPAD_TOUCH_Y'
  72366. ],
  72367. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72368. };
  72369. /**
  72370. * Fired when the trackpad on this controller is clicked
  72371. */
  72372. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72373. /**
  72374. * Fired when the trackpad on this controller is modified
  72375. */
  72376. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72377. /**
  72378. * The current x and y values of this controller's trackpad
  72379. */
  72380. _this.trackpad = { x: 0, y: 0 };
  72381. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72382. _this._loadedMeshInfo = null;
  72383. return _this;
  72384. }
  72385. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72386. /**
  72387. * Fired when the trigger on this controller is modified
  72388. */
  72389. get: function () {
  72390. return this.onTriggerStateChangedObservable;
  72391. },
  72392. enumerable: true,
  72393. configurable: true
  72394. });
  72395. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72396. /**
  72397. * Fired when the menu button on this controller is modified
  72398. */
  72399. get: function () {
  72400. return this.onSecondaryButtonStateChangedObservable;
  72401. },
  72402. enumerable: true,
  72403. configurable: true
  72404. });
  72405. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72406. /**
  72407. * Fired when the grip button on this controller is modified
  72408. */
  72409. get: function () {
  72410. return this.onMainButtonStateChangedObservable;
  72411. },
  72412. enumerable: true,
  72413. configurable: true
  72414. });
  72415. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72416. /**
  72417. * Fired when the thumbstick button on this controller is modified
  72418. */
  72419. get: function () {
  72420. return this.onPadStateChangedObservable;
  72421. },
  72422. enumerable: true,
  72423. configurable: true
  72424. });
  72425. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72426. /**
  72427. * Fired when the touchpad button on this controller is modified
  72428. */
  72429. get: function () {
  72430. return this.onTrackpadChangedObservable;
  72431. },
  72432. enumerable: true,
  72433. configurable: true
  72434. });
  72435. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72436. /**
  72437. * Fired when the touchpad values on this controller are modified
  72438. */
  72439. get: function () {
  72440. return this.onTrackpadValuesChangedObservable;
  72441. },
  72442. enumerable: true,
  72443. configurable: true
  72444. });
  72445. /**
  72446. * Called once per frame by the engine.
  72447. */
  72448. WindowsMotionController.prototype.update = function () {
  72449. _super.prototype.update.call(this);
  72450. if (this.browserGamepad.axes) {
  72451. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  72452. this.trackpad.x = this.browserGamepad["axes"][2];
  72453. this.trackpad.y = this.browserGamepad["axes"][3];
  72454. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72455. }
  72456. // Only need to animate axes if there is a loaded mesh
  72457. if (this._loadedMeshInfo) {
  72458. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72459. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72460. }
  72461. }
  72462. }
  72463. };
  72464. /**
  72465. * Called once for each button that changed state since the last frame
  72466. * @param buttonIdx Which button index changed
  72467. * @param state New state of the button
  72468. * @param changes Which properties on the state changed since last frame
  72469. */
  72470. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72471. var buttonName = this._mapping.buttons[buttonIdx];
  72472. if (!buttonName) {
  72473. return;
  72474. }
  72475. // Only emit events for buttons that we know how to map from index to name
  72476. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72477. if (observable) {
  72478. observable.notifyObservers(state);
  72479. }
  72480. this._lerpButtonTransform(buttonName, state.value);
  72481. };
  72482. /**
  72483. * Moves the buttons on the controller mesh based on their current state
  72484. * @param buttonName the name of the button to move
  72485. * @param buttonValue the value of the button which determines the buttons new position
  72486. */
  72487. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72488. // If there is no loaded mesh, there is nothing to transform.
  72489. if (!this._loadedMeshInfo) {
  72490. return;
  72491. }
  72492. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72493. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72494. return;
  72495. }
  72496. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72497. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72498. };
  72499. /**
  72500. * Moves the axis on the controller mesh based on its current state
  72501. * @param axis the index of the axis
  72502. * @param axisValue the value of the axis which determines the meshes new position
  72503. * @hidden
  72504. */
  72505. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72506. if (!this._loadedMeshInfo) {
  72507. return;
  72508. }
  72509. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72510. if (!meshInfo) {
  72511. return;
  72512. }
  72513. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72514. return;
  72515. }
  72516. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72517. var lerpValue = axisValue * 0.5 + 0.5;
  72518. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72519. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72520. };
  72521. /**
  72522. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72523. * @param scene scene in which to add meshes
  72524. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72525. */
  72526. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72527. var _this = this;
  72528. if (forceDefault === void 0) { forceDefault = false; }
  72529. var path;
  72530. var filename;
  72531. // Checking if GLB loader is present
  72532. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72533. // Determine the device specific folder based on the ID suffix
  72534. var device = 'default';
  72535. if (this.id && !forceDefault) {
  72536. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72537. device = ((match && match[0]) || device);
  72538. }
  72539. // Hand
  72540. if (this.hand === 'left') {
  72541. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72542. }
  72543. else { // Right is the default if no hand is specified
  72544. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72545. }
  72546. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72547. }
  72548. else {
  72549. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72550. path = BABYLON.GenericController.MODEL_BASE_URL;
  72551. filename = BABYLON.GenericController.MODEL_FILENAME;
  72552. }
  72553. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72554. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72555. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72556. if (!_this._loadedMeshInfo) {
  72557. return;
  72558. }
  72559. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72560. _this.attachToMesh(_this._defaultModel);
  72561. if (meshLoaded) {
  72562. meshLoaded(_this._defaultModel);
  72563. }
  72564. }, null, function (scene, message) {
  72565. BABYLON.Tools.Log(message);
  72566. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72567. if (!forceDefault) {
  72568. _this.initControllerMesh(scene, meshLoaded, true);
  72569. }
  72570. });
  72571. };
  72572. /**
  72573. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72574. * can be transformed by button presses and axes values, based on this._mapping.
  72575. *
  72576. * @param scene scene in which the meshes exist
  72577. * @param meshes list of meshes that make up the controller model to process
  72578. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72579. */
  72580. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72581. var loadedMeshInfo = null;
  72582. // Create a new mesh to contain the glTF hierarchy
  72583. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72584. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72585. var childMesh = null;
  72586. for (var i = 0; i < meshes.length; i++) {
  72587. var mesh = meshes[i];
  72588. if (!mesh.parent) {
  72589. // Exclude controller meshes from picking results
  72590. mesh.isPickable = false;
  72591. // Handle root node, attach to the new parentMesh
  72592. childMesh = mesh;
  72593. break;
  72594. }
  72595. }
  72596. if (childMesh) {
  72597. childMesh.setParent(parentMesh);
  72598. // Create our mesh info. Note that this method will always return non-null.
  72599. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72600. }
  72601. else {
  72602. BABYLON.Tools.Warn('Could not find root node in model file.');
  72603. }
  72604. return loadedMeshInfo;
  72605. };
  72606. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72607. var loadedMeshInfo = new LoadedMeshInfo();
  72608. var i;
  72609. loadedMeshInfo.rootNode = rootNode;
  72610. // Reset the caches
  72611. loadedMeshInfo.buttonMeshes = {};
  72612. loadedMeshInfo.axisMeshes = {};
  72613. // Button Meshes
  72614. for (i = 0; i < this._mapping.buttons.length; i++) {
  72615. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72616. if (!buttonMeshName) {
  72617. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72618. continue;
  72619. }
  72620. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72621. if (!buttonMesh) {
  72622. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72623. continue;
  72624. }
  72625. var buttonMeshInfo = {
  72626. index: i,
  72627. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72628. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72629. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72630. };
  72631. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72632. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72633. }
  72634. else {
  72635. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72636. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72637. '(VALUE: ' + !!buttonMeshInfo.value +
  72638. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72639. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72640. ')');
  72641. }
  72642. }
  72643. // Axis Meshes
  72644. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72645. var axisMeshName = this._mapping.axisMeshNames[i];
  72646. if (!axisMeshName) {
  72647. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72648. continue;
  72649. }
  72650. var axisMesh = getChildByName(rootNode, axisMeshName);
  72651. if (!axisMesh) {
  72652. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72653. continue;
  72654. }
  72655. var axisMeshInfo = {
  72656. index: i,
  72657. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72658. min: getImmediateChildByName(axisMesh, 'MIN'),
  72659. max: getImmediateChildByName(axisMesh, 'MAX')
  72660. };
  72661. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72662. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72663. }
  72664. else {
  72665. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72666. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72667. '(VALUE: ' + !!axisMeshInfo.value +
  72668. ', MIN: ' + !!axisMeshInfo.min +
  72669. ', MAX:' + !!axisMeshInfo.max +
  72670. ')');
  72671. }
  72672. }
  72673. // Pointing Ray
  72674. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72675. if (!loadedMeshInfo.pointingPoseNode) {
  72676. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72677. }
  72678. return loadedMeshInfo;
  72679. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72680. function getChildByName(node, name) {
  72681. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72682. }
  72683. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72684. function getImmediateChildByName(node, name) {
  72685. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72686. }
  72687. };
  72688. /**
  72689. * Gets the ray of the controller in the direction the controller is pointing
  72690. * @param length the length the resulting ray should be
  72691. * @returns a ray in the direction the controller is pointing
  72692. */
  72693. WindowsMotionController.prototype.getForwardRay = function (length) {
  72694. if (length === void 0) { length = 100; }
  72695. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72696. return _super.prototype.getForwardRay.call(this, length);
  72697. }
  72698. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72699. var origin = m.getTranslation();
  72700. var forward = new BABYLON.Vector3(0, 0, -1);
  72701. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72702. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72703. return new BABYLON.Ray(origin, direction, length);
  72704. };
  72705. /**
  72706. * Disposes of the controller
  72707. */
  72708. WindowsMotionController.prototype.dispose = function () {
  72709. _super.prototype.dispose.call(this);
  72710. this.onTrackpadChangedObservable.clear();
  72711. };
  72712. /**
  72713. * The base url used to load the left and right controller models
  72714. */
  72715. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72716. /**
  72717. * The name of the left controller model file
  72718. */
  72719. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72720. /**
  72721. * The name of the right controller model file
  72722. */
  72723. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72724. /**
  72725. * The controller name prefix for this controller type
  72726. */
  72727. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72728. /**
  72729. * The controller id pattern for this controller type
  72730. */
  72731. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72732. return WindowsMotionController;
  72733. }(BABYLON.WebVRController));
  72734. BABYLON.WindowsMotionController = WindowsMotionController;
  72735. })(BABYLON || (BABYLON = {}));
  72736. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72737. var BABYLON;
  72738. (function (BABYLON) {
  72739. /**
  72740. * Gear VR Controller
  72741. */
  72742. var GearVRController = /** @class */ (function (_super) {
  72743. __extends(GearVRController, _super);
  72744. /**
  72745. * Creates a new GearVRController from a gamepad
  72746. * @param vrGamepad the gamepad that the controller should be created from
  72747. */
  72748. function GearVRController(vrGamepad) {
  72749. var _this = _super.call(this, vrGamepad) || this;
  72750. _this._buttonIndexToObservableNameMap = [
  72751. 'onTrackpadChangedObservable',
  72752. 'onTriggerStateChangedObservable' // Trigger
  72753. ];
  72754. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72755. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72756. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72757. return _this;
  72758. }
  72759. /**
  72760. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72761. * @param scene scene in which to add meshes
  72762. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72763. */
  72764. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72765. var _this = this;
  72766. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72767. _this._defaultModel = newMeshes[1];
  72768. _this.attachToMesh(_this._defaultModel);
  72769. if (meshLoaded) {
  72770. meshLoaded(_this._defaultModel);
  72771. }
  72772. });
  72773. };
  72774. /**
  72775. * Called once for each button that changed state since the last frame
  72776. * @param buttonIdx Which button index changed
  72777. * @param state New state of the button
  72778. * @param changes Which properties on the state changed since last frame
  72779. */
  72780. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72781. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72782. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72783. // Only emit events for buttons that we know how to map from index to observable
  72784. var observable = this[observableName];
  72785. if (observable) {
  72786. observable.notifyObservers(state);
  72787. }
  72788. }
  72789. };
  72790. /**
  72791. * Base Url for the controller model.
  72792. */
  72793. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72794. /**
  72795. * File name for the controller model.
  72796. */
  72797. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72798. /**
  72799. * Gamepad Id prefix used to identify this controller.
  72800. */
  72801. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72802. return GearVRController;
  72803. }(BABYLON.WebVRController));
  72804. BABYLON.GearVRController = GearVRController;
  72805. })(BABYLON || (BABYLON = {}));
  72806. //# sourceMappingURL=babylon.gearVRController.js.map
  72807. var BABYLON;
  72808. (function (BABYLON) {
  72809. /**
  72810. * Google Daydream controller
  72811. */
  72812. var DaydreamController = /** @class */ (function (_super) {
  72813. __extends(DaydreamController, _super);
  72814. /**
  72815. * Creates a new DaydreamController from a gamepad
  72816. * @param vrGamepad the gamepad that the controller should be created from
  72817. */
  72818. function DaydreamController(vrGamepad) {
  72819. var _this = _super.call(this, vrGamepad) || this;
  72820. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72821. return _this;
  72822. }
  72823. /**
  72824. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72825. * @param scene scene in which to add meshes
  72826. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72827. */
  72828. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72829. var _this = this;
  72830. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72831. _this._defaultModel = newMeshes[1];
  72832. _this.attachToMesh(_this._defaultModel);
  72833. if (meshLoaded) {
  72834. meshLoaded(_this._defaultModel);
  72835. }
  72836. });
  72837. };
  72838. /**
  72839. * Called once for each button that changed state since the last frame
  72840. * @param buttonIdx Which button index changed
  72841. * @param state New state of the button
  72842. * @param changes Which properties on the state changed since last frame
  72843. */
  72844. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72845. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72846. if (buttonIdx === 0) {
  72847. var observable = this.onTriggerStateChangedObservable;
  72848. if (observable) {
  72849. observable.notifyObservers(state);
  72850. }
  72851. }
  72852. else {
  72853. // If the app or home buttons are ever made available
  72854. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72855. }
  72856. };
  72857. /**
  72858. * Base Url for the controller model.
  72859. */
  72860. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72861. /**
  72862. * File name for the controller model.
  72863. */
  72864. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72865. /**
  72866. * Gamepad Id prefix used to identify Daydream Controller.
  72867. */
  72868. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72869. return DaydreamController;
  72870. }(BABYLON.WebVRController));
  72871. BABYLON.DaydreamController = DaydreamController;
  72872. })(BABYLON || (BABYLON = {}));
  72873. //# sourceMappingURL=babylon.daydreamController.js.map
  72874. var BABYLON;
  72875. (function (BABYLON) {
  72876. var FollowCamera = /** @class */ (function (_super) {
  72877. __extends(FollowCamera, _super);
  72878. function FollowCamera(name, position, scene, lockedTarget) {
  72879. if (lockedTarget === void 0) { lockedTarget = null; }
  72880. var _this = _super.call(this, name, position, scene) || this;
  72881. _this.radius = 12;
  72882. _this.rotationOffset = 0;
  72883. _this.heightOffset = 4;
  72884. _this.cameraAcceleration = 0.05;
  72885. _this.maxCameraSpeed = 20;
  72886. _this.lockedTarget = lockedTarget;
  72887. return _this;
  72888. }
  72889. FollowCamera.prototype.getRadians = function (degrees) {
  72890. return degrees * Math.PI / 180;
  72891. };
  72892. FollowCamera.prototype.follow = function (cameraTarget) {
  72893. if (!cameraTarget)
  72894. return;
  72895. var yRotation;
  72896. if (cameraTarget.rotationQuaternion) {
  72897. var rotMatrix = new BABYLON.Matrix();
  72898. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72899. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72900. }
  72901. else {
  72902. yRotation = cameraTarget.rotation.y;
  72903. }
  72904. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72905. var targetPosition = cameraTarget.getAbsolutePosition();
  72906. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72907. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72908. var dx = targetX - this.position.x;
  72909. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72910. var dz = (targetZ) - this.position.z;
  72911. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72912. var vy = dy * this.cameraAcceleration;
  72913. var vz = dz * this.cameraAcceleration * 2;
  72914. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72915. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72916. }
  72917. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72918. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72919. }
  72920. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72921. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72922. }
  72923. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72924. this.setTarget(targetPosition);
  72925. };
  72926. FollowCamera.prototype._checkInputs = function () {
  72927. _super.prototype._checkInputs.call(this);
  72928. if (this.lockedTarget) {
  72929. this.follow(this.lockedTarget);
  72930. }
  72931. };
  72932. FollowCamera.prototype.getClassName = function () {
  72933. return "FollowCamera";
  72934. };
  72935. __decorate([
  72936. BABYLON.serialize()
  72937. ], FollowCamera.prototype, "radius", void 0);
  72938. __decorate([
  72939. BABYLON.serialize()
  72940. ], FollowCamera.prototype, "rotationOffset", void 0);
  72941. __decorate([
  72942. BABYLON.serialize()
  72943. ], FollowCamera.prototype, "heightOffset", void 0);
  72944. __decorate([
  72945. BABYLON.serialize()
  72946. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72947. __decorate([
  72948. BABYLON.serialize()
  72949. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72950. __decorate([
  72951. BABYLON.serializeAsMeshReference("lockedTargetId")
  72952. ], FollowCamera.prototype, "lockedTarget", void 0);
  72953. return FollowCamera;
  72954. }(BABYLON.TargetCamera));
  72955. BABYLON.FollowCamera = FollowCamera;
  72956. var ArcFollowCamera = /** @class */ (function (_super) {
  72957. __extends(ArcFollowCamera, _super);
  72958. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72959. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72960. _this.alpha = alpha;
  72961. _this.beta = beta;
  72962. _this.radius = radius;
  72963. _this.target = target;
  72964. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72965. _this.follow();
  72966. return _this;
  72967. }
  72968. ArcFollowCamera.prototype.follow = function () {
  72969. if (!this.target) {
  72970. return;
  72971. }
  72972. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72973. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72974. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72975. var targetPosition = this.target.getAbsolutePosition();
  72976. this.position = targetPosition.add(this._cartesianCoordinates);
  72977. this.setTarget(targetPosition);
  72978. };
  72979. ArcFollowCamera.prototype._checkInputs = function () {
  72980. _super.prototype._checkInputs.call(this);
  72981. this.follow();
  72982. };
  72983. ArcFollowCamera.prototype.getClassName = function () {
  72984. return "ArcFollowCamera";
  72985. };
  72986. return ArcFollowCamera;
  72987. }(BABYLON.TargetCamera));
  72988. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72989. })(BABYLON || (BABYLON = {}));
  72990. //# sourceMappingURL=babylon.followCamera.js.map
  72991. var BABYLON;
  72992. (function (BABYLON) {
  72993. // We're mainly based on the logic defined into the FreeCamera code
  72994. var UniversalCamera = /** @class */ (function (_super) {
  72995. __extends(UniversalCamera, _super);
  72996. //-- end properties for backward compatibility for inputs
  72997. function UniversalCamera(name, position, scene) {
  72998. var _this = _super.call(this, name, position, scene) || this;
  72999. _this.inputs.addGamepad();
  73000. return _this;
  73001. }
  73002. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73003. //-- Begin properties for backward compatibility for inputs
  73004. get: function () {
  73005. var gamepad = this.inputs.attached["gamepad"];
  73006. if (gamepad)
  73007. return gamepad.gamepadAngularSensibility;
  73008. return 0;
  73009. },
  73010. set: function (value) {
  73011. var gamepad = this.inputs.attached["gamepad"];
  73012. if (gamepad)
  73013. gamepad.gamepadAngularSensibility = value;
  73014. },
  73015. enumerable: true,
  73016. configurable: true
  73017. });
  73018. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73019. get: function () {
  73020. var gamepad = this.inputs.attached["gamepad"];
  73021. if (gamepad)
  73022. return gamepad.gamepadMoveSensibility;
  73023. return 0;
  73024. },
  73025. set: function (value) {
  73026. var gamepad = this.inputs.attached["gamepad"];
  73027. if (gamepad)
  73028. gamepad.gamepadMoveSensibility = value;
  73029. },
  73030. enumerable: true,
  73031. configurable: true
  73032. });
  73033. UniversalCamera.prototype.getClassName = function () {
  73034. return "UniversalCamera";
  73035. };
  73036. return UniversalCamera;
  73037. }(BABYLON.TouchCamera));
  73038. BABYLON.UniversalCamera = UniversalCamera;
  73039. })(BABYLON || (BABYLON = {}));
  73040. //# sourceMappingURL=babylon.universalCamera.js.map
  73041. var BABYLON;
  73042. (function (BABYLON) {
  73043. // We're mainly based on the logic defined into the FreeCamera code
  73044. var GamepadCamera = /** @class */ (function (_super) {
  73045. __extends(GamepadCamera, _super);
  73046. //-- end properties for backward compatibility for inputs
  73047. function GamepadCamera(name, position, scene) {
  73048. return _super.call(this, name, position, scene) || this;
  73049. }
  73050. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73051. //-- Begin properties for backward compatibility for inputs
  73052. get: function () {
  73053. var gamepad = this.inputs.attached["gamepad"];
  73054. if (gamepad)
  73055. return gamepad.gamepadAngularSensibility;
  73056. return 0;
  73057. },
  73058. set: function (value) {
  73059. var gamepad = this.inputs.attached["gamepad"];
  73060. if (gamepad)
  73061. gamepad.gamepadAngularSensibility = value;
  73062. },
  73063. enumerable: true,
  73064. configurable: true
  73065. });
  73066. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73067. get: function () {
  73068. var gamepad = this.inputs.attached["gamepad"];
  73069. if (gamepad)
  73070. return gamepad.gamepadMoveSensibility;
  73071. return 0;
  73072. },
  73073. set: function (value) {
  73074. var gamepad = this.inputs.attached["gamepad"];
  73075. if (gamepad)
  73076. gamepad.gamepadMoveSensibility = value;
  73077. },
  73078. enumerable: true,
  73079. configurable: true
  73080. });
  73081. GamepadCamera.prototype.getClassName = function () {
  73082. return "GamepadCamera";
  73083. };
  73084. return GamepadCamera;
  73085. }(BABYLON.UniversalCamera));
  73086. BABYLON.GamepadCamera = GamepadCamera;
  73087. })(BABYLON || (BABYLON = {}));
  73088. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73089. var BABYLON;
  73090. (function (BABYLON) {
  73091. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73092. function PostProcessRenderPipelineManager() {
  73093. this._renderPipelines = {};
  73094. }
  73095. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73096. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73097. };
  73098. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73099. if (unique === void 0) { unique = false; }
  73100. var renderPipeline = this._renderPipelines[renderPipelineName];
  73101. if (!renderPipeline) {
  73102. return;
  73103. }
  73104. renderPipeline._attachCameras(cameras, unique);
  73105. };
  73106. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73107. var renderPipeline = this._renderPipelines[renderPipelineName];
  73108. if (!renderPipeline) {
  73109. return;
  73110. }
  73111. renderPipeline._detachCameras(cameras);
  73112. };
  73113. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73114. var renderPipeline = this._renderPipelines[renderPipelineName];
  73115. if (!renderPipeline) {
  73116. return;
  73117. }
  73118. renderPipeline._enableEffect(renderEffectName, cameras);
  73119. };
  73120. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73121. var renderPipeline = this._renderPipelines[renderPipelineName];
  73122. if (!renderPipeline) {
  73123. return;
  73124. }
  73125. renderPipeline._disableEffect(renderEffectName, cameras);
  73126. };
  73127. PostProcessRenderPipelineManager.prototype.update = function () {
  73128. for (var renderPipelineName in this._renderPipelines) {
  73129. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73130. var pipeline = this._renderPipelines[renderPipelineName];
  73131. if (!pipeline.isSupported) {
  73132. pipeline.dispose();
  73133. delete this._renderPipelines[renderPipelineName];
  73134. }
  73135. else {
  73136. pipeline._update();
  73137. }
  73138. }
  73139. }
  73140. };
  73141. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73142. for (var renderPipelineName in this._renderPipelines) {
  73143. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73144. var pipeline = this._renderPipelines[renderPipelineName];
  73145. pipeline._rebuild();
  73146. }
  73147. }
  73148. };
  73149. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73150. for (var renderPipelineName in this._renderPipelines) {
  73151. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73152. var pipeline = this._renderPipelines[renderPipelineName];
  73153. pipeline.dispose();
  73154. }
  73155. }
  73156. };
  73157. return PostProcessRenderPipelineManager;
  73158. }());
  73159. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73160. })(BABYLON || (BABYLON = {}));
  73161. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73162. var BABYLON;
  73163. (function (BABYLON) {
  73164. /**
  73165. * This represents a set of one or more post processes in Babylon.
  73166. * A post process can be used to apply a shader to a texture after it is rendered.
  73167. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73168. */
  73169. var PostProcessRenderEffect = /** @class */ (function () {
  73170. /**
  73171. * Instantiates a post process render effect.
  73172. * A post process can be used to apply a shader to a texture after it is rendered.
  73173. * @param engine The engine the effect is tied to
  73174. * @param name The name of the effect
  73175. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73176. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73177. */
  73178. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73179. this._name = name;
  73180. this._singleInstance = singleInstance || true;
  73181. this._getPostProcesses = getPostProcesses;
  73182. this._cameras = {};
  73183. this._indicesForCamera = {};
  73184. this._postProcesses = {};
  73185. }
  73186. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73187. /**
  73188. * Checks if all the post processes in the effect are supported.
  73189. */
  73190. get: function () {
  73191. for (var index in this._postProcesses) {
  73192. if (this._postProcesses.hasOwnProperty(index)) {
  73193. var pps = this._postProcesses[index];
  73194. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73195. if (!pps[ppIndex].isSupported) {
  73196. return false;
  73197. }
  73198. }
  73199. }
  73200. }
  73201. return true;
  73202. },
  73203. enumerable: true,
  73204. configurable: true
  73205. });
  73206. /**
  73207. * Updates the current state of the effect
  73208. */
  73209. PostProcessRenderEffect.prototype._update = function () {
  73210. };
  73211. /**
  73212. * Attaches the effect on cameras
  73213. * @param cameras The camera to attach to.
  73214. */
  73215. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73216. var _this = this;
  73217. var cameraKey;
  73218. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73219. if (!cams) {
  73220. return;
  73221. }
  73222. for (var i = 0; i < cams.length; i++) {
  73223. var camera = cams[i];
  73224. var cameraName = camera.name;
  73225. if (this._singleInstance) {
  73226. cameraKey = 0;
  73227. }
  73228. else {
  73229. cameraKey = cameraName;
  73230. }
  73231. if (!this._postProcesses[cameraKey]) {
  73232. var postProcess = this._getPostProcesses();
  73233. if (postProcess) {
  73234. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73235. }
  73236. }
  73237. if (!this._indicesForCamera[cameraName]) {
  73238. this._indicesForCamera[cameraName] = [];
  73239. }
  73240. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73241. var index = camera.attachPostProcess(postProcess);
  73242. _this._indicesForCamera[cameraName].push(index);
  73243. });
  73244. if (!this._cameras[cameraName]) {
  73245. this._cameras[cameraName] = camera;
  73246. }
  73247. }
  73248. };
  73249. /**
  73250. * Detatches the effect on cameras
  73251. * @param cameras The camera to detatch from.
  73252. */
  73253. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73254. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73255. if (!cams) {
  73256. return;
  73257. }
  73258. for (var i = 0; i < cams.length; i++) {
  73259. var camera = cams[i];
  73260. var cameraName = camera.name;
  73261. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73262. camera.detachPostProcess(postProcess);
  73263. });
  73264. if (this._cameras[cameraName]) {
  73265. //this._indicesForCamera.splice(index, 1);
  73266. this._cameras[cameraName] = null;
  73267. }
  73268. }
  73269. };
  73270. /**
  73271. * Enables the effect on given cameras
  73272. * @param cameras The camera to enable.
  73273. */
  73274. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73275. var _this = this;
  73276. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73277. if (!cams) {
  73278. return;
  73279. }
  73280. for (var i = 0; i < cams.length; i++) {
  73281. var camera = cams[i];
  73282. var cameraName = camera.name;
  73283. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73284. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73285. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73286. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73287. });
  73288. }
  73289. }
  73290. }
  73291. };
  73292. /**
  73293. * Disables the effect on the given cameras
  73294. * @param cameras The camera to disable.
  73295. */
  73296. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73297. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73298. if (!cams) {
  73299. return;
  73300. }
  73301. for (var i = 0; i < cams.length; i++) {
  73302. var camera = cams[i];
  73303. var cameraName = camera.name;
  73304. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73305. camera.detachPostProcess(postProcess);
  73306. });
  73307. }
  73308. };
  73309. /**
  73310. * Gets a list of the post processes contained in the effect.
  73311. * @param camera The camera to get the post processes on.
  73312. * @returns The list of the post processes in the effect.
  73313. */
  73314. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73315. if (this._singleInstance) {
  73316. return this._postProcesses[0];
  73317. }
  73318. else {
  73319. if (!camera) {
  73320. return null;
  73321. }
  73322. return this._postProcesses[camera.name];
  73323. }
  73324. };
  73325. return PostProcessRenderEffect;
  73326. }());
  73327. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73328. })(BABYLON || (BABYLON = {}));
  73329. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73330. var BABYLON;
  73331. (function (BABYLON) {
  73332. var PostProcessRenderPipeline = /** @class */ (function () {
  73333. function PostProcessRenderPipeline(engine, name) {
  73334. this.engine = engine;
  73335. this._name = name;
  73336. this._renderEffects = {};
  73337. this._renderEffectsForIsolatedPass = new Array();
  73338. this._cameras = [];
  73339. }
  73340. PostProcessRenderPipeline.prototype.getClassName = function () {
  73341. return "PostProcessRenderPipeline";
  73342. };
  73343. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73344. get: function () {
  73345. for (var renderEffectName in this._renderEffects) {
  73346. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73347. if (!this._renderEffects[renderEffectName].isSupported) {
  73348. return false;
  73349. }
  73350. }
  73351. }
  73352. return true;
  73353. },
  73354. enumerable: true,
  73355. configurable: true
  73356. });
  73357. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73358. this._renderEffects[renderEffect._name] = renderEffect;
  73359. };
  73360. // private
  73361. PostProcessRenderPipeline.prototype._rebuild = function () {
  73362. };
  73363. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73364. var renderEffects = this._renderEffects[renderEffectName];
  73365. if (!renderEffects) {
  73366. return;
  73367. }
  73368. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73369. };
  73370. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73371. var renderEffects = this._renderEffects[renderEffectName];
  73372. if (!renderEffects) {
  73373. return;
  73374. }
  73375. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73376. };
  73377. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73378. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73379. if (!cams) {
  73380. return;
  73381. }
  73382. var indicesToDelete = [];
  73383. var i;
  73384. for (i = 0; i < cams.length; i++) {
  73385. var camera = cams[i];
  73386. var cameraName = camera.name;
  73387. if (this._cameras.indexOf(camera) === -1) {
  73388. this._cameras[cameraName] = camera;
  73389. }
  73390. else if (unique) {
  73391. indicesToDelete.push(i);
  73392. }
  73393. }
  73394. for (i = 0; i < indicesToDelete.length; i++) {
  73395. cameras.splice(indicesToDelete[i], 1);
  73396. }
  73397. for (var renderEffectName in this._renderEffects) {
  73398. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73399. this._renderEffects[renderEffectName]._attachCameras(cams);
  73400. }
  73401. }
  73402. };
  73403. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73404. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73405. if (!cams) {
  73406. return;
  73407. }
  73408. for (var renderEffectName in this._renderEffects) {
  73409. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73410. this._renderEffects[renderEffectName]._detachCameras(cams);
  73411. }
  73412. }
  73413. for (var i = 0; i < cams.length; i++) {
  73414. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73415. }
  73416. };
  73417. PostProcessRenderPipeline.prototype._update = function () {
  73418. for (var renderEffectName in this._renderEffects) {
  73419. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73420. this._renderEffects[renderEffectName]._update();
  73421. }
  73422. }
  73423. for (var i = 0; i < this._cameras.length; i++) {
  73424. var cameraName = this._cameras[i].name;
  73425. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73426. this._renderEffectsForIsolatedPass[cameraName]._update();
  73427. }
  73428. }
  73429. };
  73430. PostProcessRenderPipeline.prototype._reset = function () {
  73431. this._renderEffects = {};
  73432. this._renderEffectsForIsolatedPass = new Array();
  73433. };
  73434. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73435. // 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)
  73436. var effectKeys = Object.keys(this._renderEffects);
  73437. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73438. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73439. if (postProcesses) {
  73440. postProcesses[0].samples = sampleCount;
  73441. return true;
  73442. }
  73443. }
  73444. return false;
  73445. };
  73446. PostProcessRenderPipeline.prototype.dispose = function () {
  73447. // Must be implemented by children
  73448. };
  73449. __decorate([
  73450. BABYLON.serialize()
  73451. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73452. return PostProcessRenderPipeline;
  73453. }());
  73454. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73455. })(BABYLON || (BABYLON = {}));
  73456. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73457. var BABYLON;
  73458. (function (BABYLON) {
  73459. /**
  73460. * This represents a depth renderer in Babylon.
  73461. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73462. */
  73463. var DepthRenderer = /** @class */ (function () {
  73464. /**
  73465. * Instantiates a depth renderer
  73466. * @param scene The scene the renderer belongs to
  73467. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73468. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73469. */
  73470. function DepthRenderer(scene, type, camera) {
  73471. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73472. if (camera === void 0) { camera = null; }
  73473. var _this = this;
  73474. this._scene = scene;
  73475. this._camera = camera;
  73476. var engine = scene.getEngine();
  73477. // Render target
  73478. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73479. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73480. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73481. this._depthMap.refreshRate = 1;
  73482. this._depthMap.renderParticles = false;
  73483. this._depthMap.renderList = null;
  73484. // Camera to get depth map from to support multiple concurrent cameras
  73485. this._depthMap.activeCamera = this._camera;
  73486. this._depthMap.ignoreCameraViewport = true;
  73487. this._depthMap.useCameraPostProcesses = false;
  73488. // set default depth value to 1.0 (far away)
  73489. this._depthMap.onClearObservable.add(function (engine) {
  73490. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73491. });
  73492. // Custom render function
  73493. var renderSubMesh = function (subMesh) {
  73494. var mesh = subMesh.getRenderingMesh();
  73495. var scene = _this._scene;
  73496. var engine = scene.getEngine();
  73497. var material = subMesh.getMaterial();
  73498. if (!material) {
  73499. return;
  73500. }
  73501. // Culling and reverse (right handed system)
  73502. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73503. // Managing instances
  73504. var batch = mesh._getInstancesRenderList(subMesh._id);
  73505. if (batch.mustReturn) {
  73506. return;
  73507. }
  73508. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73509. var camera = _this._camera || scene.activeCamera;
  73510. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73511. engine.enableEffect(_this._effect);
  73512. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73513. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73514. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73515. // Alpha test
  73516. if (material && material.needAlphaTesting()) {
  73517. var alphaTexture = material.getAlphaTestTexture();
  73518. if (alphaTexture) {
  73519. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73520. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73521. }
  73522. }
  73523. // Bones
  73524. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73525. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73526. }
  73527. // Draw
  73528. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73529. }
  73530. };
  73531. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73532. var index;
  73533. if (depthOnlySubMeshes.length) {
  73534. engine.setColorWrite(false);
  73535. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73536. renderSubMesh(depthOnlySubMeshes.data[index]);
  73537. }
  73538. engine.setColorWrite(true);
  73539. }
  73540. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73541. renderSubMesh(opaqueSubMeshes.data[index]);
  73542. }
  73543. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73544. renderSubMesh(alphaTestSubMeshes.data[index]);
  73545. }
  73546. };
  73547. }
  73548. /**
  73549. * Creates the depth rendering effect and checks if the effect is ready.
  73550. * @param subMesh The submesh to be used to render the depth map of
  73551. * @param useInstances If multiple world instances should be used
  73552. * @returns if the depth renderer is ready to render the depth map
  73553. */
  73554. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73555. var material = subMesh.getMaterial();
  73556. if (material.disableDepthWrite) {
  73557. return false;
  73558. }
  73559. var defines = [];
  73560. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73561. var mesh = subMesh.getMesh();
  73562. // Alpha test
  73563. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73564. defines.push("#define ALPHATEST");
  73565. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73566. attribs.push(BABYLON.VertexBuffer.UVKind);
  73567. defines.push("#define UV1");
  73568. }
  73569. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73570. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73571. defines.push("#define UV2");
  73572. }
  73573. }
  73574. // Bones
  73575. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73576. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73577. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73578. if (mesh.numBoneInfluencers > 4) {
  73579. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73580. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73581. }
  73582. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73583. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73584. }
  73585. else {
  73586. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73587. }
  73588. // Instances
  73589. if (useInstances) {
  73590. defines.push("#define INSTANCES");
  73591. attribs.push("world0");
  73592. attribs.push("world1");
  73593. attribs.push("world2");
  73594. attribs.push("world3");
  73595. }
  73596. // Get correct effect
  73597. var join = defines.join("\n");
  73598. if (this._cachedDefines !== join) {
  73599. this._cachedDefines = join;
  73600. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73601. }
  73602. return this._effect.isReady();
  73603. };
  73604. /**
  73605. * Gets the texture which the depth map will be written to.
  73606. * @returns The depth map texture
  73607. */
  73608. DepthRenderer.prototype.getDepthMap = function () {
  73609. return this._depthMap;
  73610. };
  73611. /**
  73612. * Disposes of the depth renderer.
  73613. */
  73614. DepthRenderer.prototype.dispose = function () {
  73615. this._depthMap.dispose();
  73616. };
  73617. return DepthRenderer;
  73618. }());
  73619. BABYLON.DepthRenderer = DepthRenderer;
  73620. })(BABYLON || (BABYLON = {}));
  73621. //# sourceMappingURL=babylon.depthRenderer.js.map
  73622. var BABYLON;
  73623. (function (BABYLON) {
  73624. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73625. __extends(SSAORenderingPipeline, _super);
  73626. /**
  73627. * @constructor
  73628. * @param {string} name - The rendering pipeline name
  73629. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73630. * @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 }
  73631. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73632. */
  73633. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73634. var _this = _super.call(this, scene.getEngine(), name) || this;
  73635. // Members
  73636. /**
  73637. * The PassPostProcess id in the pipeline that contains the original scene color
  73638. */
  73639. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73640. /**
  73641. * The SSAO PostProcess id in the pipeline
  73642. */
  73643. _this.SSAORenderEffect = "SSAORenderEffect";
  73644. /**
  73645. * The horizontal blur PostProcess id in the pipeline
  73646. */
  73647. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73648. /**
  73649. * The vertical blur PostProcess id in the pipeline
  73650. */
  73651. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73652. /**
  73653. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73654. */
  73655. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73656. /**
  73657. * The output strength of the SSAO post-process. Default value is 1.0.
  73658. */
  73659. _this.totalStrength = 1.0;
  73660. /**
  73661. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73662. */
  73663. _this.radius = 0.0001;
  73664. /**
  73665. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73666. * Must not be equal to fallOff and superior to fallOff.
  73667. * Default value is 0.975
  73668. */
  73669. _this.area = 0.0075;
  73670. /**
  73671. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73672. * Must not be equal to area and inferior to area.
  73673. * Default value is 0.0
  73674. */
  73675. _this.fallOff = 0.000001;
  73676. /**
  73677. * The base color of the SSAO post-process
  73678. * The final result is "base + ssao" between [0, 1]
  73679. */
  73680. _this.base = 0.5;
  73681. _this._firstUpdate = true;
  73682. _this._scene = scene;
  73683. // Set up assets
  73684. _this._createRandomTexture();
  73685. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73686. var ssaoRatio = ratio.ssaoRatio || ratio;
  73687. var combineRatio = ratio.combineRatio || ratio;
  73688. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73689. _this._createSSAOPostProcess(ssaoRatio);
  73690. _this._createBlurPostProcess(ssaoRatio);
  73691. _this._createSSAOCombinePostProcess(combineRatio);
  73692. // Set up pipeline
  73693. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73694. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73695. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73696. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73697. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73698. // Finish
  73699. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73700. if (cameras)
  73701. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73702. return _this;
  73703. }
  73704. // Public Methods
  73705. /**
  73706. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73707. */
  73708. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73709. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73710. for (var i = 0; i < this._scene.cameras.length; i++) {
  73711. var camera = this._scene.cameras[i];
  73712. this._originalColorPostProcess.dispose(camera);
  73713. this._ssaoPostProcess.dispose(camera);
  73714. this._blurHPostProcess.dispose(camera);
  73715. this._blurVPostProcess.dispose(camera);
  73716. this._ssaoCombinePostProcess.dispose(camera);
  73717. }
  73718. this._randomTexture.dispose();
  73719. if (disableDepthRender)
  73720. this._scene.disableDepthRenderer();
  73721. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73722. _super.prototype.dispose.call(this);
  73723. };
  73724. // Private Methods
  73725. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73726. var _this = this;
  73727. var size = 16;
  73728. 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);
  73729. 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);
  73730. this._blurHPostProcess.onActivateObservable.add(function () {
  73731. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73732. _this._blurHPostProcess.kernel = size * dw;
  73733. });
  73734. this._blurVPostProcess.onActivateObservable.add(function () {
  73735. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73736. _this._blurVPostProcess.kernel = size * dw;
  73737. });
  73738. };
  73739. SSAORenderingPipeline.prototype._rebuild = function () {
  73740. this._firstUpdate = true;
  73741. _super.prototype._rebuild.call(this);
  73742. };
  73743. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73744. var _this = this;
  73745. var numSamples = 16;
  73746. var sampleSphere = [
  73747. 0.5381, 0.1856, -0.4319,
  73748. 0.1379, 0.2486, 0.4430,
  73749. 0.3371, 0.5679, -0.0057,
  73750. -0.6999, -0.0451, -0.0019,
  73751. 0.0689, -0.1598, -0.8547,
  73752. 0.0560, 0.0069, -0.1843,
  73753. -0.0146, 0.1402, 0.0762,
  73754. 0.0100, -0.1924, -0.0344,
  73755. -0.3577, -0.5301, -0.4358,
  73756. -0.3169, 0.1063, 0.0158,
  73757. 0.0103, -0.5869, 0.0046,
  73758. -0.0897, -0.4940, 0.3287,
  73759. 0.7119, -0.0154, -0.0918,
  73760. -0.0533, 0.0596, -0.5411,
  73761. 0.0352, -0.0631, 0.5460,
  73762. -0.4776, 0.2847, -0.0271
  73763. ];
  73764. var samplesFactor = 1.0 / numSamples;
  73765. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73766. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73767. "area", "fallOff", "base", "range", "viewport"
  73768. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73769. this._ssaoPostProcess.onApply = function (effect) {
  73770. if (_this._firstUpdate) {
  73771. effect.setArray3("sampleSphere", sampleSphere);
  73772. effect.setFloat("samplesFactor", samplesFactor);
  73773. effect.setFloat("randTextureTiles", 4.0);
  73774. }
  73775. effect.setFloat("totalStrength", _this.totalStrength);
  73776. effect.setFloat("radius", _this.radius);
  73777. effect.setFloat("area", _this.area);
  73778. effect.setFloat("fallOff", _this.fallOff);
  73779. effect.setFloat("base", _this.base);
  73780. effect.setTexture("textureSampler", _this._depthTexture);
  73781. effect.setTexture("randomSampler", _this._randomTexture);
  73782. };
  73783. };
  73784. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73785. var _this = this;
  73786. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73787. this._ssaoCombinePostProcess.onApply = function (effect) {
  73788. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73789. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73790. };
  73791. };
  73792. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73793. var size = 512;
  73794. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73795. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73796. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73797. var context = this._randomTexture.getContext();
  73798. var rand = function (min, max) {
  73799. return Math.random() * (max - min) + min;
  73800. };
  73801. var randVector = BABYLON.Vector3.Zero();
  73802. for (var x = 0; x < size; x++) {
  73803. for (var y = 0; y < size; y++) {
  73804. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73805. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73806. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73807. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73808. context.fillRect(x, y, 1, 1);
  73809. }
  73810. }
  73811. this._randomTexture.update(false);
  73812. };
  73813. __decorate([
  73814. BABYLON.serialize()
  73815. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73816. __decorate([
  73817. BABYLON.serialize()
  73818. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73819. __decorate([
  73820. BABYLON.serialize()
  73821. ], SSAORenderingPipeline.prototype, "area", void 0);
  73822. __decorate([
  73823. BABYLON.serialize()
  73824. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73825. __decorate([
  73826. BABYLON.serialize()
  73827. ], SSAORenderingPipeline.prototype, "base", void 0);
  73828. return SSAORenderingPipeline;
  73829. }(BABYLON.PostProcessRenderPipeline));
  73830. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73831. })(BABYLON || (BABYLON = {}));
  73832. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73833. var BABYLON;
  73834. (function (BABYLON) {
  73835. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73836. __extends(SSAO2RenderingPipeline, _super);
  73837. /**
  73838. * @constructor
  73839. * @param {string} name - The rendering pipeline name
  73840. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73841. * @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 }
  73842. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73843. */
  73844. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73845. var _this = _super.call(this, scene.getEngine(), name) || this;
  73846. // Members
  73847. /**
  73848. * The PassPostProcess id in the pipeline that contains the original scene color
  73849. */
  73850. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73851. /**
  73852. * The SSAO PostProcess id in the pipeline
  73853. */
  73854. _this.SSAORenderEffect = "SSAORenderEffect";
  73855. /**
  73856. * The horizontal blur PostProcess id in the pipeline
  73857. */
  73858. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73859. /**
  73860. * The vertical blur PostProcess id in the pipeline
  73861. */
  73862. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73863. /**
  73864. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73865. */
  73866. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73867. /**
  73868. * The output strength of the SSAO post-process. Default value is 1.0.
  73869. */
  73870. _this.totalStrength = 1.0;
  73871. /**
  73872. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73873. */
  73874. _this.maxZ = 100.0;
  73875. /**
  73876. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73877. */
  73878. _this.minZAspect = 0.2;
  73879. /**
  73880. * Number of samples used for the SSAO calculations. Default value is 8
  73881. */
  73882. _this._samples = 8;
  73883. /**
  73884. * Are we using bilateral blur ?
  73885. */
  73886. _this._expensiveBlur = true;
  73887. /**
  73888. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73889. */
  73890. _this.radius = 2.0;
  73891. /**
  73892. * The base color of the SSAO post-process
  73893. * The final result is "base + ssao" between [0, 1]
  73894. */
  73895. _this.base = 0.1;
  73896. _this._firstUpdate = true;
  73897. _this._scene = scene;
  73898. _this._ratio = ratio;
  73899. if (!_this.isSupported) {
  73900. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73901. return _this;
  73902. }
  73903. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73904. var blurRatio = _this._ratio.blurRatio || ratio;
  73905. // Set up assets
  73906. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73907. _this._createRandomTexture();
  73908. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73909. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73910. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73911. _this._createSSAOPostProcess(1.0);
  73912. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73913. _this._createSSAOCombinePostProcess(blurRatio);
  73914. // Set up pipeline
  73915. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73916. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73917. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73918. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73919. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73920. // Finish
  73921. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73922. if (cameras)
  73923. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73924. return _this;
  73925. }
  73926. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73927. get: function () {
  73928. return this._samples;
  73929. },
  73930. set: function (n) {
  73931. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73932. this._samples = n;
  73933. this._sampleSphere = this._generateHemisphere();
  73934. this._firstUpdate = true;
  73935. },
  73936. enumerable: true,
  73937. configurable: true
  73938. });
  73939. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73940. get: function () {
  73941. return this._expensiveBlur;
  73942. },
  73943. set: function (b) {
  73944. 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"]);
  73945. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73946. this._expensiveBlur = b;
  73947. this._firstUpdate = true;
  73948. },
  73949. enumerable: true,
  73950. configurable: true
  73951. });
  73952. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73953. /**
  73954. * Support test.
  73955. */
  73956. get: function () {
  73957. var engine = BABYLON.Engine.LastCreatedEngine;
  73958. if (!engine) {
  73959. return false;
  73960. }
  73961. return engine.getCaps().drawBuffersExtension;
  73962. },
  73963. enumerable: true,
  73964. configurable: true
  73965. });
  73966. // Public Methods
  73967. /**
  73968. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73969. */
  73970. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73971. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73972. for (var i = 0; i < this._scene.cameras.length; i++) {
  73973. var camera = this._scene.cameras[i];
  73974. this._originalColorPostProcess.dispose(camera);
  73975. this._ssaoPostProcess.dispose(camera);
  73976. this._blurHPostProcess.dispose(camera);
  73977. this._blurVPostProcess.dispose(camera);
  73978. this._ssaoCombinePostProcess.dispose(camera);
  73979. }
  73980. this._randomTexture.dispose();
  73981. if (disableGeometryBufferRenderer)
  73982. this._scene.disableGeometryBufferRenderer();
  73983. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73984. _super.prototype.dispose.call(this);
  73985. };
  73986. // Private Methods
  73987. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73988. var _this = this;
  73989. this._samplerOffsets = [];
  73990. var expensive = this.expensiveBlur;
  73991. for (var i = -8; i < 8; i++) {
  73992. this._samplerOffsets.push(i * 2 + 0.5);
  73993. }
  73994. 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");
  73995. this._blurHPostProcess.onApply = function (effect) {
  73996. if (!_this._scene.activeCamera) {
  73997. return;
  73998. }
  73999. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74000. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74001. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74002. effect.setFloat("radius", _this.radius);
  74003. effect.setTexture("depthSampler", _this._depthTexture);
  74004. if (_this._firstUpdate) {
  74005. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74006. }
  74007. };
  74008. 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");
  74009. this._blurVPostProcess.onApply = function (effect) {
  74010. if (!_this._scene.activeCamera) {
  74011. return;
  74012. }
  74013. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74014. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74015. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74016. effect.setFloat("radius", _this.radius);
  74017. effect.setTexture("depthSampler", _this._depthTexture);
  74018. if (_this._firstUpdate) {
  74019. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74020. _this._firstUpdate = false;
  74021. }
  74022. };
  74023. };
  74024. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74025. this._firstUpdate = true;
  74026. _super.prototype._rebuild.call(this);
  74027. };
  74028. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74029. var numSamples = this.samples;
  74030. var result = [];
  74031. var vector, scale;
  74032. var rand = function (min, max) {
  74033. return Math.random() * (max - min) + min;
  74034. };
  74035. var i = 0;
  74036. while (i < numSamples) {
  74037. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74038. vector.normalize();
  74039. scale = i / numSamples;
  74040. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74041. vector.scaleInPlace(scale);
  74042. result.push(vector.x, vector.y, vector.z);
  74043. i++;
  74044. }
  74045. return result;
  74046. };
  74047. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74048. var _this = this;
  74049. var numSamples = this.samples;
  74050. this._sampleSphere = this._generateHemisphere();
  74051. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74052. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74053. "base", "range", "projection", "near", "far", "texelSize",
  74054. "xViewport", "yViewport", "maxZ", "minZAspect"
  74055. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74056. this._ssaoPostProcess.onApply = function (effect) {
  74057. if (_this._firstUpdate) {
  74058. effect.setArray3("sampleSphere", _this._sampleSphere);
  74059. effect.setFloat("randTextureTiles", 4.0);
  74060. }
  74061. if (!_this._scene.activeCamera) {
  74062. return;
  74063. }
  74064. effect.setFloat("samplesFactor", 1 / _this.samples);
  74065. effect.setFloat("totalStrength", _this.totalStrength);
  74066. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74067. effect.setFloat("radius", _this.radius);
  74068. effect.setFloat("maxZ", _this.maxZ);
  74069. effect.setFloat("minZAspect", _this.minZAspect);
  74070. effect.setFloat("base", _this.base);
  74071. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74072. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74073. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74074. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74075. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74076. effect.setTexture("textureSampler", _this._depthTexture);
  74077. effect.setTexture("normalSampler", _this._normalTexture);
  74078. effect.setTexture("randomSampler", _this._randomTexture);
  74079. };
  74080. };
  74081. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74082. var _this = this;
  74083. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74084. this._ssaoCombinePostProcess.onApply = function (effect) {
  74085. var viewport = _this._scene.activeCamera.viewport;
  74086. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74087. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74088. };
  74089. };
  74090. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74091. var size = 512;
  74092. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74093. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74094. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74095. var context = this._randomTexture.getContext();
  74096. var rand = function (min, max) {
  74097. return Math.random() * (max - min) + min;
  74098. };
  74099. var randVector = BABYLON.Vector3.Zero();
  74100. for (var x = 0; x < size; x++) {
  74101. for (var y = 0; y < size; y++) {
  74102. randVector.x = rand(0.0, 1.0);
  74103. randVector.y = rand(0.0, 1.0);
  74104. randVector.z = 0.0;
  74105. randVector.normalize();
  74106. randVector.scaleInPlace(255);
  74107. randVector.x = Math.floor(randVector.x);
  74108. randVector.y = Math.floor(randVector.y);
  74109. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74110. context.fillRect(x, y, 1, 1);
  74111. }
  74112. }
  74113. this._randomTexture.update(false);
  74114. };
  74115. /**
  74116. * Serialize the rendering pipeline (Used when exporting)
  74117. * @returns the serialized object
  74118. */
  74119. SSAO2RenderingPipeline.prototype.serialize = function () {
  74120. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74121. serializationObject.customType = "SSAO2RenderingPipeline";
  74122. return serializationObject;
  74123. };
  74124. /**
  74125. * Parse the serialized pipeline
  74126. * @param source Source pipeline.
  74127. * @param scene The scene to load the pipeline to.
  74128. * @param rootUrl The URL of the serialized pipeline.
  74129. * @returns An instantiated pipeline from the serialized object.
  74130. */
  74131. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74132. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74133. };
  74134. __decorate([
  74135. BABYLON.serialize()
  74136. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74137. __decorate([
  74138. BABYLON.serialize()
  74139. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74140. __decorate([
  74141. BABYLON.serialize()
  74142. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74143. __decorate([
  74144. BABYLON.serialize("samples")
  74145. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74146. __decorate([
  74147. BABYLON.serialize()
  74148. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74149. __decorate([
  74150. BABYLON.serialize("expensiveBlur")
  74151. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74152. __decorate([
  74153. BABYLON.serialize()
  74154. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74155. __decorate([
  74156. BABYLON.serialize()
  74157. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74158. return SSAO2RenderingPipeline;
  74159. }(BABYLON.PostProcessRenderPipeline));
  74160. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74161. })(BABYLON || (BABYLON = {}));
  74162. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74163. // BABYLON.JS Chromatic Aberration GLSL Shader
  74164. // Author: Olivier Guyot
  74165. // Separates very slightly R, G and B colors on the edges of the screen
  74166. // Inspired by Francois Tarlier & Martins Upitis
  74167. var BABYLON;
  74168. (function (BABYLON) {
  74169. var LensRenderingPipeline = /** @class */ (function (_super) {
  74170. __extends(LensRenderingPipeline, _super);
  74171. /**
  74172. * @constructor
  74173. *
  74174. * Effect parameters are as follow:
  74175. * {
  74176. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74177. * edge_blur: number; // from 0 to x (1 for realism)
  74178. * distortion: number; // from 0 to x (1 for realism)
  74179. * grain_amount: number; // from 0 to 1
  74180. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74181. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74182. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74183. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74184. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74185. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74186. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74187. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74188. * }
  74189. * Note: if an effect parameter is unset, effect is disabled
  74190. *
  74191. * @param {string} name - The rendering pipeline name
  74192. * @param {object} parameters - An object containing all parameters (see above)
  74193. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74194. * @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)
  74195. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74196. */
  74197. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74198. if (ratio === void 0) { ratio = 1.0; }
  74199. var _this = _super.call(this, scene.getEngine(), name) || this;
  74200. // Lens effects can be of the following:
  74201. // - chromatic aberration (slight shift of RGB colors)
  74202. // - blur on the edge of the lens
  74203. // - lens distortion
  74204. // - depth-of-field blur & highlights enhancing
  74205. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74206. // - grain effect (noise or custom texture)
  74207. // Two additional texture samplers are needed:
  74208. // - depth map (for depth-of-field)
  74209. // - grain texture
  74210. /**
  74211. * The chromatic aberration PostProcess id in the pipeline
  74212. */
  74213. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74214. /**
  74215. * The highlights enhancing PostProcess id in the pipeline
  74216. */
  74217. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74218. /**
  74219. * The depth-of-field PostProcess id in the pipeline
  74220. */
  74221. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74222. _this._scene = scene;
  74223. // Fetch texture samplers
  74224. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74225. if (parameters.grain_texture) {
  74226. _this._grainTexture = parameters.grain_texture;
  74227. }
  74228. else {
  74229. _this._createGrainTexture();
  74230. }
  74231. // save parameters
  74232. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74233. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74234. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74235. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74236. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74237. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74238. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74239. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74240. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74241. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74242. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74243. // Create effects
  74244. _this._createChromaticAberrationPostProcess(ratio);
  74245. _this._createHighlightsPostProcess(ratio);
  74246. _this._createDepthOfFieldPostProcess(ratio / 4);
  74247. // Set up pipeline
  74248. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74249. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74250. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74251. if (_this._highlightsGain === -1) {
  74252. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74253. }
  74254. // Finish
  74255. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74256. if (cameras) {
  74257. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74258. }
  74259. return _this;
  74260. }
  74261. // public methods (self explanatory)
  74262. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74263. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74264. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74265. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74266. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74267. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74268. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74269. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74270. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74271. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74272. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74273. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74274. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74275. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74276. };
  74277. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74278. this._highlightsPostProcess.updateEffect();
  74279. };
  74280. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74281. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74282. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74283. this._highlightsGain = amount;
  74284. };
  74285. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74286. if (this._highlightsGain === -1) {
  74287. this._highlightsGain = 1.0;
  74288. }
  74289. this._highlightsThreshold = amount;
  74290. };
  74291. LensRenderingPipeline.prototype.disableHighlights = function () {
  74292. this._highlightsGain = -1;
  74293. };
  74294. /**
  74295. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74296. */
  74297. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74298. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74299. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74300. this._chromaticAberrationPostProcess = null;
  74301. this._highlightsPostProcess = null;
  74302. this._depthOfFieldPostProcess = null;
  74303. this._grainTexture.dispose();
  74304. if (disableDepthRender)
  74305. this._scene.disableDepthRenderer();
  74306. };
  74307. // colors shifting and distortion
  74308. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74309. var _this = this;
  74310. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74311. [], // samplers
  74312. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74313. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74314. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74315. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74316. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74317. effect.setFloat('radialIntensity', 1);
  74318. effect.setFloat2('direction', 17, 17);
  74319. effect.setFloat2('centerPosition', 0.5, 0.5);
  74320. };
  74321. };
  74322. // highlights enhancing
  74323. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74324. var _this = this;
  74325. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74326. [], // samplers
  74327. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74328. this._highlightsPostProcess.onApply = function (effect) {
  74329. effect.setFloat('gain', _this._highlightsGain);
  74330. effect.setFloat('threshold', _this._highlightsThreshold);
  74331. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74332. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74333. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74334. };
  74335. };
  74336. // colors shifting and distortion
  74337. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74338. var _this = this;
  74339. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74340. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74341. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74342. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74343. this._depthOfFieldPostProcess.onApply = function (effect) {
  74344. effect.setTexture("depthSampler", _this._depthTexture);
  74345. effect.setTexture("grainSampler", _this._grainTexture);
  74346. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74347. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74348. effect.setFloat('grain_amount', _this._grainAmount);
  74349. effect.setBool('blur_noise', _this._blurNoise);
  74350. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74351. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74352. effect.setFloat('distortion', _this._distortion);
  74353. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74354. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74355. effect.setFloat('aperture', _this._dofAperture);
  74356. effect.setFloat('darken', _this._dofDarken);
  74357. effect.setFloat('edge_blur', _this._edgeBlur);
  74358. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74359. if (_this._scene.activeCamera) {
  74360. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74361. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74362. }
  74363. };
  74364. };
  74365. // creates a black and white random noise texture, 512x512
  74366. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74367. var size = 512;
  74368. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74369. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74370. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74371. var context = this._grainTexture.getContext();
  74372. var rand = function (min, max) {
  74373. return Math.random() * (max - min) + min;
  74374. };
  74375. var value;
  74376. for (var x = 0; x < size; x++) {
  74377. for (var y = 0; y < size; y++) {
  74378. value = Math.floor(rand(0.42, 0.58) * 255);
  74379. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74380. context.fillRect(x, y, 1, 1);
  74381. }
  74382. }
  74383. this._grainTexture.update(false);
  74384. };
  74385. return LensRenderingPipeline;
  74386. }(BABYLON.PostProcessRenderPipeline));
  74387. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74388. })(BABYLON || (BABYLON = {}));
  74389. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74390. var BABYLON;
  74391. (function (BABYLON) {
  74392. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74393. __extends(StandardRenderingPipeline, _super);
  74394. /**
  74395. * @constructor
  74396. * @param {string} name - The rendering pipeline name
  74397. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74398. * @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)
  74399. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74400. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74401. */
  74402. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74403. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74404. var _this = _super.call(this, scene.getEngine(), name) || this;
  74405. _this.downSampleX4PostProcess = null;
  74406. _this.brightPassPostProcess = null;
  74407. _this.blurHPostProcesses = [];
  74408. _this.blurVPostProcesses = [];
  74409. _this.textureAdderPostProcess = null;
  74410. _this.volumetricLightPostProcess = null;
  74411. _this.volumetricLightSmoothXPostProcess = null;
  74412. _this.volumetricLightSmoothYPostProcess = null;
  74413. _this.volumetricLightMergePostProces = null;
  74414. _this.volumetricLightFinalPostProcess = null;
  74415. _this.luminancePostProcess = null;
  74416. _this.luminanceDownSamplePostProcesses = [];
  74417. _this.hdrPostProcess = null;
  74418. _this.textureAdderFinalPostProcess = null;
  74419. _this.lensFlareFinalPostProcess = null;
  74420. _this.hdrFinalPostProcess = null;
  74421. _this.lensFlarePostProcess = null;
  74422. _this.lensFlareComposePostProcess = null;
  74423. _this.motionBlurPostProcess = null;
  74424. _this.depthOfFieldPostProcess = null;
  74425. // Values
  74426. _this.brightThreshold = 1.0;
  74427. _this.blurWidth = 512.0;
  74428. _this.horizontalBlur = false;
  74429. _this.exposure = 1.0;
  74430. _this.lensTexture = null;
  74431. _this.volumetricLightCoefficient = 0.2;
  74432. _this.volumetricLightPower = 4.0;
  74433. _this.volumetricLightBlurScale = 64.0;
  74434. _this.sourceLight = null;
  74435. _this.hdrMinimumLuminance = 1.0;
  74436. _this.hdrDecreaseRate = 0.5;
  74437. _this.hdrIncreaseRate = 0.5;
  74438. _this.lensColorTexture = null;
  74439. _this.lensFlareStrength = 20.0;
  74440. _this.lensFlareGhostDispersal = 1.4;
  74441. _this.lensFlareHaloWidth = 0.7;
  74442. _this.lensFlareDistortionStrength = 16.0;
  74443. _this.lensStarTexture = null;
  74444. _this.lensFlareDirtTexture = null;
  74445. _this.depthOfFieldDistance = 10.0;
  74446. _this.depthOfFieldBlurWidth = 64.0;
  74447. _this.motionStrength = 1.0;
  74448. // IAnimatable
  74449. _this.animations = [];
  74450. _this._currentDepthOfFieldSource = null;
  74451. _this._hdrCurrentLuminance = 1.0;
  74452. // Getters and setters
  74453. _this._bloomEnabled = true;
  74454. _this._depthOfFieldEnabled = false;
  74455. _this._vlsEnabled = false;
  74456. _this._lensFlareEnabled = false;
  74457. _this._hdrEnabled = false;
  74458. _this._motionBlurEnabled = false;
  74459. _this._motionBlurSamples = 64.0;
  74460. _this._volumetricLightStepsCount = 50.0;
  74461. _this._cameras = cameras || [];
  74462. // Initialize
  74463. _this._scene = scene;
  74464. _this._basePostProcess = originalPostProcess;
  74465. _this._ratio = ratio;
  74466. // Misc
  74467. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74468. // Finish
  74469. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74470. _this._buildPipeline();
  74471. return _this;
  74472. }
  74473. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74474. get: function () {
  74475. return this._bloomEnabled;
  74476. },
  74477. set: function (enabled) {
  74478. if (this._bloomEnabled === enabled) {
  74479. return;
  74480. }
  74481. this._bloomEnabled = enabled;
  74482. this._buildPipeline();
  74483. },
  74484. enumerable: true,
  74485. configurable: true
  74486. });
  74487. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74488. get: function () {
  74489. return this._depthOfFieldEnabled;
  74490. },
  74491. set: function (enabled) {
  74492. if (this._depthOfFieldEnabled === enabled) {
  74493. return;
  74494. }
  74495. this._depthOfFieldEnabled = enabled;
  74496. this._buildPipeline();
  74497. },
  74498. enumerable: true,
  74499. configurable: true
  74500. });
  74501. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74502. get: function () {
  74503. return this._lensFlareEnabled;
  74504. },
  74505. set: function (enabled) {
  74506. if (this._lensFlareEnabled === enabled) {
  74507. return;
  74508. }
  74509. this._lensFlareEnabled = enabled;
  74510. this._buildPipeline();
  74511. },
  74512. enumerable: true,
  74513. configurable: true
  74514. });
  74515. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74516. get: function () {
  74517. return this._hdrEnabled;
  74518. },
  74519. set: function (enabled) {
  74520. if (this._hdrEnabled === enabled) {
  74521. return;
  74522. }
  74523. this._hdrEnabled = enabled;
  74524. this._buildPipeline();
  74525. },
  74526. enumerable: true,
  74527. configurable: true
  74528. });
  74529. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74530. get: function () {
  74531. return this._vlsEnabled;
  74532. },
  74533. set: function (enabled) {
  74534. if (this._vlsEnabled === enabled) {
  74535. return;
  74536. }
  74537. if (enabled) {
  74538. var geometry = this._scene.enableGeometryBufferRenderer();
  74539. if (!geometry) {
  74540. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74541. return;
  74542. }
  74543. }
  74544. this._vlsEnabled = enabled;
  74545. this._buildPipeline();
  74546. },
  74547. enumerable: true,
  74548. configurable: true
  74549. });
  74550. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74551. get: function () {
  74552. return this._motionBlurEnabled;
  74553. },
  74554. set: function (enabled) {
  74555. if (this._motionBlurEnabled === enabled) {
  74556. return;
  74557. }
  74558. this._motionBlurEnabled = enabled;
  74559. this._buildPipeline();
  74560. },
  74561. enumerable: true,
  74562. configurable: true
  74563. });
  74564. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74565. get: function () {
  74566. return this._volumetricLightStepsCount;
  74567. },
  74568. set: function (count) {
  74569. if (this.volumetricLightPostProcess) {
  74570. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74571. }
  74572. this._volumetricLightStepsCount = count;
  74573. },
  74574. enumerable: true,
  74575. configurable: true
  74576. });
  74577. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74578. get: function () {
  74579. return this._motionBlurSamples;
  74580. },
  74581. set: function (samples) {
  74582. if (this.motionBlurPostProcess) {
  74583. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74584. }
  74585. this._motionBlurSamples = samples;
  74586. },
  74587. enumerable: true,
  74588. configurable: true
  74589. });
  74590. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74591. var _this = this;
  74592. var ratio = this._ratio;
  74593. var scene = this._scene;
  74594. this._disposePostProcesses();
  74595. this._reset();
  74596. // Create pass post-process
  74597. if (!this._basePostProcess) {
  74598. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74599. this.originalPostProcess.onApply = function (effect) {
  74600. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74601. };
  74602. }
  74603. else {
  74604. this.originalPostProcess = this._basePostProcess;
  74605. }
  74606. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74607. this._currentDepthOfFieldSource = this.originalPostProcess;
  74608. if (this._bloomEnabled) {
  74609. // Create down sample X4 post-process
  74610. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74611. // Create bright pass post-process
  74612. this._createBrightPassPostProcess(scene, ratio / 2);
  74613. // Create gaussian blur post-processes (down sampling blurs)
  74614. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74615. // Create texture adder post-process
  74616. this._createTextureAdderPostProcess(scene, ratio);
  74617. // Create depth-of-field source post-process
  74618. 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);
  74619. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74620. }
  74621. if (this._vlsEnabled) {
  74622. // Create volumetric light
  74623. this._createVolumetricLightPostProcess(scene, ratio);
  74624. // Create volumetric light final post-process
  74625. 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);
  74626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74627. }
  74628. if (this._lensFlareEnabled) {
  74629. // Create lens flare post-process
  74630. this._createLensFlarePostProcess(scene, ratio);
  74631. // Create depth-of-field source post-process post lens-flare and disable it now
  74632. 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);
  74633. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74634. }
  74635. if (this._hdrEnabled) {
  74636. // Create luminance
  74637. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74638. // Create HDR
  74639. this._createHdrPostProcess(scene, ratio);
  74640. // Create depth-of-field source post-process post hdr and disable it now
  74641. 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);
  74642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74643. }
  74644. if (this._depthOfFieldEnabled) {
  74645. // Create gaussian blur used by depth-of-field
  74646. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74647. // Create depth-of-field post-process
  74648. this._createDepthOfFieldPostProcess(scene, ratio);
  74649. }
  74650. if (this._motionBlurEnabled) {
  74651. // Create motion blur post-process
  74652. this._createMotionBlurPostProcess(scene, ratio);
  74653. }
  74654. if (this._cameras !== null) {
  74655. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74656. }
  74657. };
  74658. // Down Sample X4 Post-Processs
  74659. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74660. var _this = this;
  74661. var downSampleX4Offsets = new Array(32);
  74662. 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);
  74663. this.downSampleX4PostProcess.onApply = function (effect) {
  74664. var id = 0;
  74665. var width = _this.downSampleX4PostProcess.width;
  74666. var height = _this.downSampleX4PostProcess.height;
  74667. for (var i = -2; i < 2; i++) {
  74668. for (var j = -2; j < 2; j++) {
  74669. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74670. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74671. id += 2;
  74672. }
  74673. }
  74674. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74675. };
  74676. // Add to pipeline
  74677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74678. };
  74679. // Brightpass Post-Process
  74680. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74681. var _this = this;
  74682. var brightOffsets = new Array(8);
  74683. 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);
  74684. this.brightPassPostProcess.onApply = function (effect) {
  74685. var sU = (1.0 / _this.brightPassPostProcess.width);
  74686. var sV = (1.0 / _this.brightPassPostProcess.height);
  74687. brightOffsets[0] = -0.5 * sU;
  74688. brightOffsets[1] = 0.5 * sV;
  74689. brightOffsets[2] = 0.5 * sU;
  74690. brightOffsets[3] = 0.5 * sV;
  74691. brightOffsets[4] = -0.5 * sU;
  74692. brightOffsets[5] = -0.5 * sV;
  74693. brightOffsets[6] = 0.5 * sU;
  74694. brightOffsets[7] = -0.5 * sV;
  74695. effect.setArray2("dsOffsets", brightOffsets);
  74696. effect.setFloat("brightThreshold", _this.brightThreshold);
  74697. };
  74698. // Add to pipeline
  74699. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74700. };
  74701. // Create blur H&V post-processes
  74702. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74703. var _this = this;
  74704. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74705. var engine = scene.getEngine();
  74706. 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);
  74707. 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);
  74708. blurX.onActivateObservable.add(function () {
  74709. var dw = blurX.width / engine.getRenderWidth();
  74710. blurX.kernel = _this[blurWidthKey] * dw;
  74711. });
  74712. blurY.onActivateObservable.add(function () {
  74713. var dw = blurY.height / engine.getRenderHeight();
  74714. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74715. });
  74716. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74717. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74718. this.blurHPostProcesses.push(blurX);
  74719. this.blurVPostProcesses.push(blurY);
  74720. };
  74721. // Create texture adder post-process
  74722. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74723. var _this = this;
  74724. 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);
  74725. this.textureAdderPostProcess.onApply = function (effect) {
  74726. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74727. effect.setTexture("lensSampler", _this.lensTexture);
  74728. effect.setFloat("exposure", _this.exposure);
  74729. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74730. };
  74731. // Add to pipeline
  74732. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74733. };
  74734. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74735. var _this = this;
  74736. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74737. geometryRenderer.enablePosition = true;
  74738. var geometry = geometryRenderer.getGBuffer();
  74739. // Base post-process
  74740. 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));
  74741. var depthValues = BABYLON.Vector2.Zero();
  74742. this.volumetricLightPostProcess.onApply = function (effect) {
  74743. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74744. var generator = _this.sourceLight.getShadowGenerator();
  74745. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74746. effect.setTexture("positionSampler", geometry.textures[2]);
  74747. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74748. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74749. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74750. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74751. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74752. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74753. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74754. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74755. effect.setVector2("depthValues", depthValues);
  74756. }
  74757. };
  74758. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74759. // Smooth
  74760. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74761. // Merge
  74762. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74763. this.volumetricLightMergePostProces.onApply = function (effect) {
  74764. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74765. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74766. };
  74767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74768. };
  74769. // Create luminance
  74770. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74771. var _this = this;
  74772. // Create luminance
  74773. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74774. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74775. var offsets = [];
  74776. this.luminancePostProcess.onApply = function (effect) {
  74777. var sU = (1.0 / _this.luminancePostProcess.width);
  74778. var sV = (1.0 / _this.luminancePostProcess.height);
  74779. offsets[0] = -0.5 * sU;
  74780. offsets[1] = 0.5 * sV;
  74781. offsets[2] = 0.5 * sU;
  74782. offsets[3] = 0.5 * sV;
  74783. offsets[4] = -0.5 * sU;
  74784. offsets[5] = -0.5 * sV;
  74785. offsets[6] = 0.5 * sU;
  74786. offsets[7] = -0.5 * sV;
  74787. effect.setArray2("lumOffsets", offsets);
  74788. };
  74789. // Add to pipeline
  74790. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74791. // Create down sample luminance
  74792. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74793. var size = Math.pow(3, i);
  74794. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74795. if (i === 0) {
  74796. defines += "#define FINAL_DOWN_SAMPLER";
  74797. }
  74798. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74799. this.luminanceDownSamplePostProcesses.push(postProcess);
  74800. }
  74801. // Create callbacks and add effects
  74802. var lastLuminance = this.luminancePostProcess;
  74803. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74804. var downSampleOffsets = new Array(18);
  74805. pp.onApply = function (effect) {
  74806. if (!lastLuminance) {
  74807. return;
  74808. }
  74809. var id = 0;
  74810. for (var x = -1; x < 2; x++) {
  74811. for (var y = -1; y < 2; y++) {
  74812. downSampleOffsets[id] = x / lastLuminance.width;
  74813. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74814. id += 2;
  74815. }
  74816. }
  74817. effect.setArray2("dsOffsets", downSampleOffsets);
  74818. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74819. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74820. lastLuminance = _this.luminancePostProcess;
  74821. }
  74822. else {
  74823. lastLuminance = pp;
  74824. }
  74825. };
  74826. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74827. pp.onAfterRender = function (effect) {
  74828. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74829. 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);
  74830. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74831. };
  74832. }
  74833. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74834. });
  74835. };
  74836. // Create HDR post-process
  74837. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74838. var _this = this;
  74839. 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);
  74840. var outputLiminance = 1;
  74841. var time = 0;
  74842. var lastTime = 0;
  74843. this.hdrPostProcess.onApply = function (effect) {
  74844. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74845. time += scene.getEngine().getDeltaTime();
  74846. if (outputLiminance < 0) {
  74847. outputLiminance = _this._hdrCurrentLuminance;
  74848. }
  74849. else {
  74850. var dt = (lastTime - time) / 1000.0;
  74851. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74852. outputLiminance += _this.hdrDecreaseRate * dt;
  74853. }
  74854. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74855. outputLiminance -= _this.hdrIncreaseRate * dt;
  74856. }
  74857. else {
  74858. outputLiminance = _this._hdrCurrentLuminance;
  74859. }
  74860. }
  74861. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74862. effect.setFloat("averageLuminance", outputLiminance);
  74863. lastTime = time;
  74864. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74865. };
  74866. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74867. };
  74868. // Create lens flare post-process
  74869. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74870. var _this = this;
  74871. 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);
  74872. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74873. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74874. 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);
  74875. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74876. var resolution = new BABYLON.Vector2(0, 0);
  74877. // Lens flare
  74878. this.lensFlarePostProcess.onApply = function (effect) {
  74879. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74880. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74881. effect.setFloat("strength", _this.lensFlareStrength);
  74882. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74883. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74884. // Shift
  74885. resolution.x = _this.lensFlarePostProcess.width;
  74886. resolution.y = _this.lensFlarePostProcess.height;
  74887. effect.setVector2("resolution", resolution);
  74888. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74889. };
  74890. // Compose
  74891. 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);
  74892. 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);
  74893. this.lensFlareComposePostProcess.onApply = function (effect) {
  74894. if (!_this._scene.activeCamera) {
  74895. return;
  74896. }
  74897. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74898. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74899. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74900. // Lens start rotation matrix
  74901. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74902. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74903. 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));
  74904. camRot *= 4.0;
  74905. 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);
  74906. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74907. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74908. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74909. };
  74910. };
  74911. // Create depth-of-field post-process
  74912. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74913. var _this = this;
  74914. 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);
  74915. this.depthOfFieldPostProcess.onApply = function (effect) {
  74916. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74917. effect.setTexture("depthSampler", _this._getDepthTexture());
  74918. effect.setFloat("distance", _this.depthOfFieldDistance);
  74919. };
  74920. // Add to pipeline
  74921. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74922. };
  74923. // Create motion blur post-process
  74924. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74925. var _this = this;
  74926. 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);
  74927. var motionScale = 0;
  74928. var prevViewProjection = BABYLON.Matrix.Identity();
  74929. var invViewProjection = BABYLON.Matrix.Identity();
  74930. var viewProjection = BABYLON.Matrix.Identity();
  74931. var screenSize = BABYLON.Vector2.Zero();
  74932. this.motionBlurPostProcess.onApply = function (effect) {
  74933. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74934. viewProjection.invertToRef(invViewProjection);
  74935. effect.setMatrix("inverseViewProjection", invViewProjection);
  74936. effect.setMatrix("prevViewProjection", prevViewProjection);
  74937. prevViewProjection = viewProjection;
  74938. screenSize.x = _this.motionBlurPostProcess.width;
  74939. screenSize.y = _this.motionBlurPostProcess.height;
  74940. effect.setVector2("screenSize", screenSize);
  74941. motionScale = scene.getEngine().getFps() / 60.0;
  74942. effect.setFloat("motionScale", motionScale);
  74943. effect.setFloat("motionStrength", _this.motionStrength);
  74944. effect.setTexture("depthSampler", _this._getDepthTexture());
  74945. };
  74946. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74947. };
  74948. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74949. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74950. var renderer = this._scene.enableGeometryBufferRenderer();
  74951. return renderer.getGBuffer().textures[0];
  74952. }
  74953. return this._scene.enableDepthRenderer().getDepthMap();
  74954. };
  74955. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74956. for (var i = 0; i < this._cameras.length; i++) {
  74957. var camera = this._cameras[i];
  74958. if (this.originalPostProcess) {
  74959. this.originalPostProcess.dispose(camera);
  74960. }
  74961. if (this.downSampleX4PostProcess) {
  74962. this.downSampleX4PostProcess.dispose(camera);
  74963. }
  74964. if (this.brightPassPostProcess) {
  74965. this.brightPassPostProcess.dispose(camera);
  74966. }
  74967. if (this.textureAdderPostProcess) {
  74968. this.textureAdderPostProcess.dispose(camera);
  74969. }
  74970. if (this.textureAdderFinalPostProcess) {
  74971. this.textureAdderFinalPostProcess.dispose(camera);
  74972. }
  74973. if (this.volumetricLightPostProcess) {
  74974. this.volumetricLightPostProcess.dispose(camera);
  74975. }
  74976. if (this.volumetricLightSmoothXPostProcess) {
  74977. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74978. }
  74979. if (this.volumetricLightSmoothYPostProcess) {
  74980. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74981. }
  74982. if (this.volumetricLightMergePostProces) {
  74983. this.volumetricLightMergePostProces.dispose(camera);
  74984. }
  74985. if (this.volumetricLightFinalPostProcess) {
  74986. this.volumetricLightFinalPostProcess.dispose(camera);
  74987. }
  74988. if (this.lensFlarePostProcess) {
  74989. this.lensFlarePostProcess.dispose(camera);
  74990. }
  74991. if (this.lensFlareComposePostProcess) {
  74992. this.lensFlareComposePostProcess.dispose(camera);
  74993. }
  74994. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74995. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74996. }
  74997. if (this.luminancePostProcess) {
  74998. this.luminancePostProcess.dispose(camera);
  74999. }
  75000. if (this.hdrPostProcess) {
  75001. this.hdrPostProcess.dispose(camera);
  75002. }
  75003. if (this.hdrFinalPostProcess) {
  75004. this.hdrFinalPostProcess.dispose(camera);
  75005. }
  75006. if (this.depthOfFieldPostProcess) {
  75007. this.depthOfFieldPostProcess.dispose(camera);
  75008. }
  75009. if (this.motionBlurPostProcess) {
  75010. this.motionBlurPostProcess.dispose(camera);
  75011. }
  75012. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75013. this.blurHPostProcesses[j].dispose(camera);
  75014. }
  75015. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75016. this.blurVPostProcesses[j].dispose(camera);
  75017. }
  75018. }
  75019. this.originalPostProcess = null;
  75020. this.downSampleX4PostProcess = null;
  75021. this.brightPassPostProcess = null;
  75022. this.textureAdderPostProcess = null;
  75023. this.textureAdderFinalPostProcess = null;
  75024. this.volumetricLightPostProcess = null;
  75025. this.volumetricLightSmoothXPostProcess = null;
  75026. this.volumetricLightSmoothYPostProcess = null;
  75027. this.volumetricLightMergePostProces = null;
  75028. this.volumetricLightFinalPostProcess = null;
  75029. this.lensFlarePostProcess = null;
  75030. this.lensFlareComposePostProcess = null;
  75031. this.luminancePostProcess = null;
  75032. this.hdrPostProcess = null;
  75033. this.hdrFinalPostProcess = null;
  75034. this.depthOfFieldPostProcess = null;
  75035. this.motionBlurPostProcess = null;
  75036. this.luminanceDownSamplePostProcesses = [];
  75037. this.blurHPostProcesses = [];
  75038. this.blurVPostProcesses = [];
  75039. };
  75040. /**
  75041. * Dispose of the pipeline and stop all post processes
  75042. */
  75043. StandardRenderingPipeline.prototype.dispose = function () {
  75044. this._disposePostProcesses();
  75045. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75046. _super.prototype.dispose.call(this);
  75047. };
  75048. /**
  75049. * Serialize the rendering pipeline (Used when exporting)
  75050. * @returns the serialized object
  75051. */
  75052. StandardRenderingPipeline.prototype.serialize = function () {
  75053. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75054. if (this.sourceLight) {
  75055. serializationObject.sourceLightId = this.sourceLight.id;
  75056. }
  75057. serializationObject.customType = "StandardRenderingPipeline";
  75058. return serializationObject;
  75059. };
  75060. /**
  75061. * Parse the serialized pipeline
  75062. * @param source Source pipeline.
  75063. * @param scene The scene to load the pipeline to.
  75064. * @param rootUrl The URL of the serialized pipeline.
  75065. * @returns An instantiated pipeline from the serialized object.
  75066. */
  75067. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75068. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75069. if (source.sourceLightId) {
  75070. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75071. }
  75072. return p;
  75073. };
  75074. // Luminance steps
  75075. StandardRenderingPipeline.LuminanceSteps = 6;
  75076. __decorate([
  75077. BABYLON.serialize()
  75078. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75079. __decorate([
  75080. BABYLON.serialize()
  75081. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75082. __decorate([
  75083. BABYLON.serialize()
  75084. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75085. __decorate([
  75086. BABYLON.serialize()
  75087. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75088. __decorate([
  75089. BABYLON.serializeAsTexture("lensTexture")
  75090. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75091. __decorate([
  75092. BABYLON.serialize()
  75093. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75094. __decorate([
  75095. BABYLON.serialize()
  75096. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75097. __decorate([
  75098. BABYLON.serialize()
  75099. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75100. __decorate([
  75101. BABYLON.serialize()
  75102. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75103. __decorate([
  75104. BABYLON.serialize()
  75105. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75106. __decorate([
  75107. BABYLON.serialize()
  75108. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75109. __decorate([
  75110. BABYLON.serializeAsTexture("lensColorTexture")
  75111. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75112. __decorate([
  75113. BABYLON.serialize()
  75114. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75115. __decorate([
  75116. BABYLON.serialize()
  75117. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75118. __decorate([
  75119. BABYLON.serialize()
  75120. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75121. __decorate([
  75122. BABYLON.serialize()
  75123. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75124. __decorate([
  75125. BABYLON.serializeAsTexture("lensStarTexture")
  75126. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75127. __decorate([
  75128. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75129. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75130. __decorate([
  75131. BABYLON.serialize()
  75132. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75133. __decorate([
  75134. BABYLON.serialize()
  75135. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75136. __decorate([
  75137. BABYLON.serialize()
  75138. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75139. __decorate([
  75140. BABYLON.serialize()
  75141. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75142. __decorate([
  75143. BABYLON.serialize()
  75144. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75145. __decorate([
  75146. BABYLON.serialize()
  75147. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75148. __decorate([
  75149. BABYLON.serialize()
  75150. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75151. __decorate([
  75152. BABYLON.serialize()
  75153. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75154. __decorate([
  75155. BABYLON.serialize()
  75156. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75157. __decorate([
  75158. BABYLON.serialize()
  75159. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75160. __decorate([
  75161. BABYLON.serialize()
  75162. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75163. __decorate([
  75164. BABYLON.serialize()
  75165. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75166. return StandardRenderingPipeline;
  75167. }(BABYLON.PostProcessRenderPipeline));
  75168. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75169. })(BABYLON || (BABYLON = {}));
  75170. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75171. var BABYLON;
  75172. (function (BABYLON) {
  75173. var FxaaPostProcess = /** @class */ (function (_super) {
  75174. __extends(FxaaPostProcess, _super);
  75175. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75176. if (camera === void 0) { camera = null; }
  75177. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75178. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75179. var defines = _this._getDefines();
  75180. _this.updateEffect(defines);
  75181. _this.onApplyObservable.add(function (effect) {
  75182. var texelSize = _this.texelSize;
  75183. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75184. });
  75185. return _this;
  75186. }
  75187. FxaaPostProcess.prototype._getDefines = function () {
  75188. var engine = this.getEngine();
  75189. if (!engine) {
  75190. return null;
  75191. }
  75192. var glInfo = engine.getGlInfo();
  75193. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75194. return "#define MALI 1\n";
  75195. }
  75196. return null;
  75197. };
  75198. return FxaaPostProcess;
  75199. }(BABYLON.PostProcess));
  75200. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75201. })(BABYLON || (BABYLON = {}));
  75202. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75203. var BABYLON;
  75204. (function (BABYLON) {
  75205. /**
  75206. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75207. */
  75208. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75209. __extends(ChromaticAberrationPostProcess, _super);
  75210. /**
  75211. * Creates a new instance ChromaticAberrationPostProcess
  75212. * @param name The name of the effect.
  75213. * @param screenWidth The width of the screen to apply the effect on.
  75214. * @param screenHeight The height of the screen to apply the effect on.
  75215. * @param options The required width/height ratio to downsize to before computing the render pass.
  75216. * @param camera The camera to apply the render pass to.
  75217. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75218. * @param engine The engine which the post process will be applied. (default: current engine)
  75219. * @param reusable If the post process can be reused on the same frame. (default: false)
  75220. * @param textureType Type of textures used when performing the post process. (default: 0)
  75221. * @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)
  75222. */
  75223. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75224. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75225. if (blockCompilation === void 0) { blockCompilation = false; }
  75226. 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;
  75227. /**
  75228. * The amount of seperation of rgb channels (default: 30)
  75229. */
  75230. _this.aberrationAmount = 30;
  75231. /**
  75232. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75233. */
  75234. _this.radialIntensity = 0;
  75235. /**
  75236. * 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))
  75237. */
  75238. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75239. /**
  75240. * 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))
  75241. */
  75242. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75243. _this.onApplyObservable.add(function (effect) {
  75244. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75245. effect.setFloat('screen_width', screenWidth);
  75246. effect.setFloat('screen_height', screenHeight);
  75247. effect.setFloat('radialIntensity', _this.radialIntensity);
  75248. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75249. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75250. });
  75251. return _this;
  75252. }
  75253. return ChromaticAberrationPostProcess;
  75254. }(BABYLON.PostProcess));
  75255. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75256. })(BABYLON || (BABYLON = {}));
  75257. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75258. var BABYLON;
  75259. (function (BABYLON) {
  75260. /**
  75261. * The GrainPostProcess adds noise to the image at mid luminance levels
  75262. */
  75263. var GrainPostProcess = /** @class */ (function (_super) {
  75264. __extends(GrainPostProcess, _super);
  75265. /**
  75266. * Creates a new instance of @see GrainPostProcess
  75267. * @param name The name of the effect.
  75268. * @param options The required width/height ratio to downsize to before computing the render pass.
  75269. * @param camera The camera to apply the render pass to.
  75270. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75271. * @param engine The engine which the post process will be applied. (default: current engine)
  75272. * @param reusable If the post process can be reused on the same frame. (default: false)
  75273. * @param textureType Type of textures used when performing the post process. (default: 0)
  75274. * @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)
  75275. */
  75276. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75277. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75278. if (blockCompilation === void 0) { blockCompilation = false; }
  75279. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75280. /**
  75281. * The intensity of the grain added (default: 30)
  75282. */
  75283. _this.intensity = 30;
  75284. /**
  75285. * If the grain should be randomized on every frame
  75286. */
  75287. _this.animated = false;
  75288. _this.onApplyObservable.add(function (effect) {
  75289. effect.setFloat('intensity', _this.intensity);
  75290. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75291. });
  75292. return _this;
  75293. }
  75294. return GrainPostProcess;
  75295. }(BABYLON.PostProcess));
  75296. BABYLON.GrainPostProcess = GrainPostProcess;
  75297. })(BABYLON || (BABYLON = {}));
  75298. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75299. var BABYLON;
  75300. (function (BABYLON) {
  75301. /**
  75302. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75303. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75304. */
  75305. var SharpenPostProcess = /** @class */ (function (_super) {
  75306. __extends(SharpenPostProcess, _super);
  75307. /**
  75308. * Creates a new instance ConvolutionPostProcess
  75309. * @param name The name of the effect.
  75310. * @param options The required width/height ratio to downsize to before computing the render pass.
  75311. * @param camera The camera to apply the render pass to.
  75312. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75313. * @param engine The engine which the post process will be applied. (default: current engine)
  75314. * @param reusable If the post process can be reused on the same frame. (default: false)
  75315. * @param textureType Type of textures used when performing the post process. (default: 0)
  75316. * @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)
  75317. */
  75318. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75319. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75320. if (blockCompilation === void 0) { blockCompilation = false; }
  75321. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75322. /**
  75323. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75324. */
  75325. _this.colorAmount = 1.0;
  75326. /**
  75327. * How much sharpness should be applied (default: 0.3)
  75328. */
  75329. _this.edgeAmount = 0.3;
  75330. _this.onApply = function (effect) {
  75331. effect.setFloat2("screenSize", _this.width, _this.height);
  75332. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75333. };
  75334. return _this;
  75335. }
  75336. return SharpenPostProcess;
  75337. }(BABYLON.PostProcess));
  75338. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75339. })(BABYLON || (BABYLON = {}));
  75340. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75341. var BABYLON;
  75342. (function (BABYLON) {
  75343. /**
  75344. * The Blur Post Process which blurs an image based on a kernel and direction.
  75345. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75346. */
  75347. var BlurPostProcess = /** @class */ (function (_super) {
  75348. __extends(BlurPostProcess, _super);
  75349. /**
  75350. * Creates a new instance BlurPostProcess
  75351. * @param name The name of the effect.
  75352. * @param direction The direction in which to blur the image.
  75353. * @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.
  75354. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75355. * @param camera The camera to apply the render pass to.
  75356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75357. * @param engine The engine which the post process will be applied. (default: current engine)
  75358. * @param reusable If the post process can be reused on the same frame. (default: false)
  75359. * @param textureType Type of textures used when performing the post process. (default: 0)
  75360. * @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)
  75361. */
  75362. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75363. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75364. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75365. if (defines === void 0) { defines = ""; }
  75366. if (blockCompilation === void 0) { blockCompilation = false; }
  75367. 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;
  75368. _this.direction = direction;
  75369. _this.blockCompilation = blockCompilation;
  75370. _this._packedFloat = false;
  75371. _this._staticDefines = "";
  75372. _this._staticDefines = defines;
  75373. _this.onApplyObservable.add(function (effect) {
  75374. if (_this._outputTexture) {
  75375. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75376. }
  75377. else {
  75378. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75379. }
  75380. });
  75381. _this.kernel = kernel;
  75382. return _this;
  75383. }
  75384. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75385. /**
  75386. * Gets the length in pixels of the blur sample region
  75387. */
  75388. get: function () {
  75389. return this._idealKernel;
  75390. },
  75391. /**
  75392. * Sets the length in pixels of the blur sample region
  75393. */
  75394. set: function (v) {
  75395. if (this._idealKernel === v) {
  75396. return;
  75397. }
  75398. v = Math.max(v, 1);
  75399. this._idealKernel = v;
  75400. this._kernel = this._nearestBestKernel(v);
  75401. if (!this.blockCompilation) {
  75402. this._updateParameters();
  75403. }
  75404. },
  75405. enumerable: true,
  75406. configurable: true
  75407. });
  75408. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75409. /**
  75410. * Gets wether or not the blur is unpacking/repacking floats
  75411. */
  75412. get: function () {
  75413. return this._packedFloat;
  75414. },
  75415. /**
  75416. * Sets wether or not the blur needs to unpack/repack floats
  75417. */
  75418. set: function (v) {
  75419. if (this._packedFloat === v) {
  75420. return;
  75421. }
  75422. this._packedFloat = v;
  75423. if (!this.blockCompilation) {
  75424. this._updateParameters();
  75425. }
  75426. },
  75427. enumerable: true,
  75428. configurable: true
  75429. });
  75430. /**
  75431. * Updates the effect with the current post process compile time values and recompiles the shader.
  75432. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75433. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75434. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75435. * @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
  75436. * @param onCompiled Called when the shader has been compiled.
  75437. * @param onError Called if there is an error when compiling a shader.
  75438. */
  75439. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75440. if (defines === void 0) { defines = null; }
  75441. if (uniforms === void 0) { uniforms = null; }
  75442. if (samplers === void 0) { samplers = null; }
  75443. this._updateParameters(onCompiled, onError);
  75444. };
  75445. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75446. // Generate sampling offsets and weights
  75447. var N = this._kernel;
  75448. var centerIndex = (N - 1) / 2;
  75449. // Generate Gaussian sampling weights over kernel
  75450. var offsets = [];
  75451. var weights = [];
  75452. var totalWeight = 0;
  75453. for (var i = 0; i < N; i++) {
  75454. var u = i / (N - 1);
  75455. var w = this._gaussianWeight(u * 2.0 - 1);
  75456. offsets[i] = (i - centerIndex);
  75457. weights[i] = w;
  75458. totalWeight += w;
  75459. }
  75460. // Normalize weights
  75461. for (var i = 0; i < weights.length; i++) {
  75462. weights[i] /= totalWeight;
  75463. }
  75464. // Optimize: combine samples to take advantage of hardware linear sampling
  75465. // Walk from left to center, combining pairs (symmetrically)
  75466. var linearSamplingWeights = [];
  75467. var linearSamplingOffsets = [];
  75468. var linearSamplingMap = [];
  75469. for (var i = 0; i <= centerIndex; i += 2) {
  75470. var j = Math.min(i + 1, Math.floor(centerIndex));
  75471. var singleCenterSample = i === j;
  75472. if (singleCenterSample) {
  75473. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75474. }
  75475. else {
  75476. var sharedCell = j === centerIndex;
  75477. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75478. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75479. if (offsetLinear === 0) {
  75480. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75481. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75482. }
  75483. else {
  75484. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75485. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75486. }
  75487. }
  75488. }
  75489. for (var i = 0; i < linearSamplingMap.length; i++) {
  75490. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75491. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75492. }
  75493. // Replace with optimized
  75494. offsets = linearSamplingOffsets;
  75495. weights = linearSamplingWeights;
  75496. // Generate shaders
  75497. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75498. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75499. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75500. var defines = "";
  75501. defines += this._staticDefines;
  75502. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75503. if (this._staticDefines.indexOf("DOF") != -1) {
  75504. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75505. varyingCount--;
  75506. }
  75507. for (var i = 0; i < varyingCount; i++) {
  75508. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75509. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75510. }
  75511. var depCount = 0;
  75512. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75513. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75514. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75515. depCount++;
  75516. }
  75517. if (this.packedFloat) {
  75518. defines += "#define PACKEDFLOAT 1";
  75519. }
  75520. this.blockCompilation = false;
  75521. _super.prototype.updateEffect.call(this, defines, null, null, {
  75522. varyingCount: varyingCount,
  75523. depCount: depCount
  75524. }, onCompiled, onError);
  75525. };
  75526. /**
  75527. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75528. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75529. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75530. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75531. * The gaps between physical kernels are compensated for in the weighting of the samples
  75532. * @param idealKernel Ideal blur kernel.
  75533. * @return Nearest best kernel.
  75534. */
  75535. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75536. var v = Math.round(idealKernel);
  75537. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75538. var k = _a[_i];
  75539. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75540. return Math.max(k, 3);
  75541. }
  75542. }
  75543. return Math.max(v, 3);
  75544. };
  75545. /**
  75546. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75547. * @param x The point on the Gaussian distribution to sample.
  75548. * @return the value of the Gaussian function at x.
  75549. */
  75550. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75551. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75552. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75553. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75554. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75555. // truncated at around 1.3% of peak strength.
  75556. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75557. var sigma = (1 / 3);
  75558. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75559. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75560. var weight = (1.0 / denominator) * Math.exp(exponent);
  75561. return weight;
  75562. };
  75563. /**
  75564. * Generates a string that can be used as a floating point number in GLSL.
  75565. * @param x Value to print.
  75566. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75567. * @return GLSL float string.
  75568. */
  75569. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75570. if (decimalFigures === void 0) { decimalFigures = 8; }
  75571. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75572. };
  75573. return BlurPostProcess;
  75574. }(BABYLON.PostProcess));
  75575. BABYLON.BlurPostProcess = BlurPostProcess;
  75576. })(BABYLON || (BABYLON = {}));
  75577. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75578. var BABYLON;
  75579. (function (BABYLON) {
  75580. /**
  75581. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75582. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75583. * based on samples that have a large difference in distance than the center pixel.
  75584. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75585. */
  75586. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75587. __extends(DepthOfFieldBlurPostProcess, _super);
  75588. /**
  75589. * Creates a new instance CircleOfConfusionPostProcess
  75590. * @param name The name of the effect.
  75591. * @param scene The scene the effect belongs to.
  75592. * @param direction The direction the blur should be applied.
  75593. * @param kernel The size of the kernel used to blur.
  75594. * @param options The required width/height ratio to downsize to before computing the render pass.
  75595. * @param camera The camera to apply the render pass to.
  75596. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75597. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75599. * @param engine The engine which the post process will be applied. (default: current engine)
  75600. * @param reusable If the post process can be reused on the same frame. (default: false)
  75601. * @param textureType Type of textures used when performing the post process. (default: 0)
  75602. * @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)
  75603. */
  75604. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75605. if (imageToBlur === void 0) { imageToBlur = null; }
  75606. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75607. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75608. if (blockCompilation === void 0) { blockCompilation = false; }
  75609. 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;
  75610. _this.direction = direction;
  75611. _this.onApplyObservable.add(function (effect) {
  75612. if (imageToBlur != null) {
  75613. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75614. }
  75615. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75616. if (scene.activeCamera) {
  75617. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75618. }
  75619. });
  75620. return _this;
  75621. }
  75622. return DepthOfFieldBlurPostProcess;
  75623. }(BABYLON.BlurPostProcess));
  75624. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75625. })(BABYLON || (BABYLON = {}));
  75626. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75627. var BABYLON;
  75628. (function (BABYLON) {
  75629. /**
  75630. * Options to be set when merging outputs from the default pipeline.
  75631. */
  75632. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75633. function DepthOfFieldMergePostProcessOptions() {
  75634. }
  75635. return DepthOfFieldMergePostProcessOptions;
  75636. }());
  75637. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75638. /**
  75639. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75640. */
  75641. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75642. __extends(DepthOfFieldMergePostProcess, _super);
  75643. /**
  75644. * Creates a new instance of DepthOfFieldMergePostProcess
  75645. * @param name The name of the effect.
  75646. * @param originalFromInput Post process which's input will be used for the merge.
  75647. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75648. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75649. * @param options The required width/height ratio to downsize to before computing the render pass.
  75650. * @param camera The camera to apply the render pass to.
  75651. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75652. * @param engine The engine which the post process will be applied. (default: current engine)
  75653. * @param reusable If the post process can be reused on the same frame. (default: false)
  75654. * @param textureType Type of textures used when performing the post process. (default: 0)
  75655. * @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)
  75656. */
  75657. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75658. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75659. if (blockCompilation === void 0) { blockCompilation = false; }
  75660. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75661. _this.blurSteps = blurSteps;
  75662. _this.onApplyObservable.add(function (effect) {
  75663. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75664. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75665. blurSteps.forEach(function (step, index) {
  75666. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75667. });
  75668. });
  75669. if (!blockCompilation) {
  75670. _this.updateEffect();
  75671. }
  75672. return _this;
  75673. }
  75674. /**
  75675. * Updates the effect with the current post process compile time values and recompiles the shader.
  75676. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75677. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75678. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75679. * @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
  75680. * @param onCompiled Called when the shader has been compiled.
  75681. * @param onError Called if there is an error when compiling a shader.
  75682. */
  75683. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75684. if (defines === void 0) { defines = null; }
  75685. if (uniforms === void 0) { uniforms = null; }
  75686. if (samplers === void 0) { samplers = null; }
  75687. if (!defines) {
  75688. defines = "";
  75689. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75690. }
  75691. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75692. };
  75693. return DepthOfFieldMergePostProcess;
  75694. }(BABYLON.PostProcess));
  75695. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75696. })(BABYLON || (BABYLON = {}));
  75697. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75698. var BABYLON;
  75699. (function (BABYLON) {
  75700. /**
  75701. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75702. */
  75703. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75704. __extends(CircleOfConfusionPostProcess, _super);
  75705. /**
  75706. * Creates a new instance CircleOfConfusionPostProcess
  75707. * @param name The name of the effect.
  75708. * @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.
  75709. * @param options The required width/height ratio to downsize to before computing the render pass.
  75710. * @param camera The camera to apply the render pass to.
  75711. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75712. * @param engine The engine which the post process will be applied. (default: current engine)
  75713. * @param reusable If the post process can be reused on the same frame. (default: false)
  75714. * @param textureType Type of textures used when performing the post process. (default: 0)
  75715. * @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)
  75716. */
  75717. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75718. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75719. if (blockCompilation === void 0) { blockCompilation = false; }
  75720. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75721. /**
  75722. * 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.
  75723. */
  75724. _this.lensSize = 50;
  75725. /**
  75726. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75727. */
  75728. _this.fStop = 1.4;
  75729. /**
  75730. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75731. */
  75732. _this.focusDistance = 2000;
  75733. /**
  75734. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75735. */
  75736. _this.focalLength = 50;
  75737. _this._depthTexture = null;
  75738. _this._depthTexture = depthTexture;
  75739. _this.onApplyObservable.add(function (effect) {
  75740. if (!_this._depthTexture) {
  75741. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75742. return;
  75743. }
  75744. effect.setTexture("depthSampler", _this._depthTexture);
  75745. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75746. var aperture = _this.lensSize / _this.fStop;
  75747. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75748. effect.setFloat('focusDistance', _this.focusDistance);
  75749. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75750. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75751. });
  75752. return _this;
  75753. }
  75754. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75755. /**
  75756. * 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.
  75757. */
  75758. set: function (value) {
  75759. this._depthTexture = value;
  75760. },
  75761. enumerable: true,
  75762. configurable: true
  75763. });
  75764. return CircleOfConfusionPostProcess;
  75765. }(BABYLON.PostProcess));
  75766. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75767. })(BABYLON || (BABYLON = {}));
  75768. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75769. var BABYLON;
  75770. (function (BABYLON) {
  75771. /**
  75772. * Specifies the level of max blur that should be applied when using the depth of field effect
  75773. */
  75774. var DepthOfFieldEffectBlurLevel;
  75775. (function (DepthOfFieldEffectBlurLevel) {
  75776. /**
  75777. * Subtle blur
  75778. */
  75779. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75780. /**
  75781. * Medium blur
  75782. */
  75783. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75784. /**
  75785. * Large blur
  75786. */
  75787. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75788. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75789. ;
  75790. /**
  75791. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75792. */
  75793. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75794. __extends(DepthOfFieldEffect, _super);
  75795. /**
  75796. * Creates a new instance DepthOfFieldEffect
  75797. * @param scene The scene the effect belongs to.
  75798. * @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.
  75799. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75800. * @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)
  75801. */
  75802. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75803. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75804. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75805. if (blockCompilation === void 0) { blockCompilation = false; }
  75806. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75807. return _this._effects;
  75808. }, true) || this;
  75809. /**
  75810. * Internal post processes in depth of field effect
  75811. */
  75812. _this._effects = [];
  75813. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75814. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75815. // 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)
  75816. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75817. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75818. _this._depthOfFieldBlurY = [];
  75819. _this._depthOfFieldBlurX = [];
  75820. var blurCount = 1;
  75821. var kernelSize = 15;
  75822. switch (blurLevel) {
  75823. case DepthOfFieldEffectBlurLevel.High: {
  75824. blurCount = 3;
  75825. kernelSize = 51;
  75826. break;
  75827. }
  75828. case DepthOfFieldEffectBlurLevel.Medium: {
  75829. blurCount = 2;
  75830. kernelSize = 31;
  75831. break;
  75832. }
  75833. default: {
  75834. kernelSize = 15;
  75835. blurCount = 1;
  75836. break;
  75837. }
  75838. }
  75839. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75840. var ratio = 1.0;
  75841. for (var i = 0; i < blurCount; i++) {
  75842. 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);
  75843. blurY.autoClear = false;
  75844. ratio = 0.75 / Math.pow(2, i);
  75845. 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);
  75846. blurX.autoClear = false;
  75847. _this._depthOfFieldBlurY.push(blurY);
  75848. _this._depthOfFieldBlurX.push(blurX);
  75849. }
  75850. // Set all post processes on the effect.
  75851. _this._effects = [_this._circleOfConfusion];
  75852. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75853. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75854. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75855. }
  75856. // Merge blurred images with original image based on circleOfConfusion
  75857. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75858. _this._dofMerge.autoClear = false;
  75859. _this._effects.push(_this._dofMerge);
  75860. return _this;
  75861. }
  75862. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75863. get: function () {
  75864. return this._circleOfConfusion.focalLength;
  75865. },
  75866. /**
  75867. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75868. */
  75869. set: function (value) {
  75870. this._circleOfConfusion.focalLength = value;
  75871. },
  75872. enumerable: true,
  75873. configurable: true
  75874. });
  75875. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75876. get: function () {
  75877. return this._circleOfConfusion.fStop;
  75878. },
  75879. /**
  75880. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75881. */
  75882. set: function (value) {
  75883. this._circleOfConfusion.fStop = value;
  75884. },
  75885. enumerable: true,
  75886. configurable: true
  75887. });
  75888. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75889. get: function () {
  75890. return this._circleOfConfusion.focusDistance;
  75891. },
  75892. /**
  75893. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75894. */
  75895. set: function (value) {
  75896. this._circleOfConfusion.focusDistance = value;
  75897. },
  75898. enumerable: true,
  75899. configurable: true
  75900. });
  75901. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75902. get: function () {
  75903. return this._circleOfConfusion.lensSize;
  75904. },
  75905. /**
  75906. * 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.
  75907. */
  75908. set: function (value) {
  75909. this._circleOfConfusion.lensSize = value;
  75910. },
  75911. enumerable: true,
  75912. configurable: true
  75913. });
  75914. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75915. /**
  75916. * 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.
  75917. */
  75918. set: function (value) {
  75919. this._circleOfConfusion.depthTexture = value;
  75920. },
  75921. enumerable: true,
  75922. configurable: true
  75923. });
  75924. /**
  75925. * Disposes each of the internal effects for a given camera.
  75926. * @param camera The camera to dispose the effect on.
  75927. */
  75928. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75929. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75930. this._effects[effectIndex].dispose(camera);
  75931. }
  75932. };
  75933. /**
  75934. * Internal
  75935. */
  75936. DepthOfFieldEffect.prototype._updateEffects = function () {
  75937. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75938. this._effects[effectIndex].updateEffect();
  75939. }
  75940. };
  75941. /**
  75942. * Internal
  75943. * @returns if all the contained post processes are ready.
  75944. */
  75945. DepthOfFieldEffect.prototype._isReady = function () {
  75946. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75947. if (!this._effects[effectIndex].isReady()) {
  75948. return false;
  75949. }
  75950. }
  75951. return true;
  75952. };
  75953. return DepthOfFieldEffect;
  75954. }(BABYLON.PostProcessRenderEffect));
  75955. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75956. })(BABYLON || (BABYLON = {}));
  75957. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75958. var BABYLON;
  75959. (function (BABYLON) {
  75960. /**
  75961. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75962. */
  75963. var BloomMergePostProcess = /** @class */ (function (_super) {
  75964. __extends(BloomMergePostProcess, _super);
  75965. /**
  75966. * Creates a new instance of @see BloomMergePostProcess
  75967. * @param name The name of the effect.
  75968. * @param originalFromInput Post process which's input will be used for the merge.
  75969. * @param blurred Blurred highlights post process which's output will be used.
  75970. * @param weight Weight of the bloom to be added to the original input.
  75971. * @param options The required width/height ratio to downsize to before computing the render pass.
  75972. * @param camera The camera to apply the render pass to.
  75973. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75974. * @param engine The engine which the post process will be applied. (default: current engine)
  75975. * @param reusable If the post process can be reused on the same frame. (default: false)
  75976. * @param textureType Type of textures used when performing the post process. (default: 0)
  75977. * @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)
  75978. */
  75979. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75980. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75981. if (blockCompilation === void 0) { blockCompilation = false; }
  75982. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75983. _this.weight = weight;
  75984. _this.onApplyObservable.add(function (effect) {
  75985. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75986. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75987. effect.setFloat("bloomWeight", _this.weight);
  75988. });
  75989. if (!blockCompilation) {
  75990. _this.updateEffect();
  75991. }
  75992. return _this;
  75993. }
  75994. return BloomMergePostProcess;
  75995. }(BABYLON.PostProcess));
  75996. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75997. })(BABYLON || (BABYLON = {}));
  75998. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75999. var BABYLON;
  76000. (function (BABYLON) {
  76001. /**
  76002. * 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.
  76003. */
  76004. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76005. __extends(ExtractHighlightsPostProcess, _super);
  76006. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76007. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76008. if (blockCompilation === void 0) { blockCompilation = false; }
  76009. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76010. /**
  76011. * The luminance threshold, pixels below this value will be set to black.
  76012. */
  76013. _this.threshold = 0.9;
  76014. /**
  76015. * Internal
  76016. */
  76017. _this._exposure = 1;
  76018. /**
  76019. * Post process which has the input texture to be used when performing highlight extraction
  76020. */
  76021. _this._inputPostProcess = null;
  76022. _this.onApplyObservable.add(function (effect) {
  76023. if (_this._inputPostProcess) {
  76024. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76025. }
  76026. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76027. effect.setFloat('exposure', _this._exposure);
  76028. });
  76029. return _this;
  76030. }
  76031. return ExtractHighlightsPostProcess;
  76032. }(BABYLON.PostProcess));
  76033. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76034. })(BABYLON || (BABYLON = {}));
  76035. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76036. var BABYLON;
  76037. (function (BABYLON) {
  76038. /**
  76039. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76040. */
  76041. var BloomEffect = /** @class */ (function (_super) {
  76042. __extends(BloomEffect, _super);
  76043. /**
  76044. * Creates a new instance of @see BloomEffect
  76045. * @param scene The scene the effect belongs to.
  76046. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76047. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76048. * @param bloomWeight The the strength of bloom.
  76049. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76050. * @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)
  76051. */
  76052. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76053. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76054. if (blockCompilation === void 0) { blockCompilation = false; }
  76055. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76056. return _this._effects;
  76057. }, true) || this;
  76058. _this.bloomScale = bloomScale;
  76059. /**
  76060. * Internal
  76061. */
  76062. _this._effects = [];
  76063. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76064. _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);
  76065. _this._blurX.alwaysForcePOT = true;
  76066. _this._blurX.autoClear = false;
  76067. _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);
  76068. _this._blurY.alwaysForcePOT = true;
  76069. _this._blurY.autoClear = false;
  76070. _this.kernel = bloomKernel;
  76071. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76072. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76073. _this._merge.autoClear = false;
  76074. _this._effects.push(_this._merge);
  76075. return _this;
  76076. }
  76077. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76078. /**
  76079. * The luminance threshold to find bright areas of the image to bloom.
  76080. */
  76081. get: function () {
  76082. return this._downscale.threshold;
  76083. },
  76084. set: function (value) {
  76085. this._downscale.threshold = value;
  76086. },
  76087. enumerable: true,
  76088. configurable: true
  76089. });
  76090. Object.defineProperty(BloomEffect.prototype, "weight", {
  76091. /**
  76092. * The strength of the bloom.
  76093. */
  76094. get: function () {
  76095. return this._merge.weight;
  76096. },
  76097. set: function (value) {
  76098. this._merge.weight = value;
  76099. },
  76100. enumerable: true,
  76101. configurable: true
  76102. });
  76103. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76104. /**
  76105. * Specifies the size of the bloom blur kernel, relative to the final output size
  76106. */
  76107. get: function () {
  76108. return this._blurX.kernel / this.bloomScale;
  76109. },
  76110. set: function (value) {
  76111. this._blurX.kernel = value * this.bloomScale;
  76112. this._blurY.kernel = value * this.bloomScale;
  76113. },
  76114. enumerable: true,
  76115. configurable: true
  76116. });
  76117. /**
  76118. * Disposes each of the internal effects for a given camera.
  76119. * @param camera The camera to dispose the effect on.
  76120. */
  76121. BloomEffect.prototype.disposeEffects = function (camera) {
  76122. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76123. this._effects[effectIndex].dispose(camera);
  76124. }
  76125. };
  76126. /**
  76127. * Internal
  76128. */
  76129. BloomEffect.prototype._updateEffects = function () {
  76130. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76131. this._effects[effectIndex].updateEffect();
  76132. }
  76133. };
  76134. /**
  76135. * Internal
  76136. * @returns if all the contained post processes are ready.
  76137. */
  76138. BloomEffect.prototype._isReady = function () {
  76139. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76140. if (!this._effects[effectIndex].isReady()) {
  76141. return false;
  76142. }
  76143. }
  76144. return true;
  76145. };
  76146. return BloomEffect;
  76147. }(BABYLON.PostProcessRenderEffect));
  76148. BABYLON.BloomEffect = BloomEffect;
  76149. })(BABYLON || (BABYLON = {}));
  76150. //# sourceMappingURL=babylon.bloomEffect.js.map
  76151. var BABYLON;
  76152. (function (BABYLON) {
  76153. /**
  76154. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76155. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76156. */
  76157. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76158. __extends(DefaultRenderingPipeline, _super);
  76159. /**
  76160. * @constructor
  76161. * @param {string} name - The rendering pipeline name (default: "")
  76162. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76163. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76164. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76165. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76166. */
  76167. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76168. if (name === void 0) { name = ""; }
  76169. if (hdr === void 0) { hdr = true; }
  76170. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76171. if (automaticBuild === void 0) { automaticBuild = true; }
  76172. var _this = _super.call(this, scene.getEngine(), name) || this;
  76173. _this._originalCameras = [];
  76174. /**
  76175. * ID of the sharpen post process,
  76176. */
  76177. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76178. /**
  76179. * ID of the image processing post process;
  76180. */
  76181. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76182. /**
  76183. * ID of the Fast Approximate Anti-Aliasing post process;
  76184. */
  76185. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76186. /**
  76187. * ID of the chromatic aberration post process,
  76188. */
  76189. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76190. /**
  76191. * ID of the grain post process
  76192. */
  76193. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76194. /**
  76195. * Glow post process which adds a glow to emmisive areas of the image
  76196. */
  76197. _this._glowLayer = null;
  76198. /**
  76199. * Animations which can be used to tweak settings over a period of time
  76200. */
  76201. _this.animations = [];
  76202. _this._imageProcessingConfigurationObserver = null;
  76203. // Values
  76204. _this._sharpenEnabled = false;
  76205. _this._bloomEnabled = false;
  76206. _this._depthOfFieldEnabled = false;
  76207. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76208. _this._fxaaEnabled = false;
  76209. _this._imageProcessingEnabled = true;
  76210. _this._bloomScale = 0.5;
  76211. _this._chromaticAberrationEnabled = false;
  76212. _this._grainEnabled = false;
  76213. _this._buildAllowed = true;
  76214. _this._resizeObserver = null;
  76215. _this._hardwareScaleLevel = 1.0;
  76216. _this._bloomKernel = 64;
  76217. /**
  76218. * Specifies the weight of the bloom in the final rendering
  76219. */
  76220. _this._bloomWeight = 0.15;
  76221. /**
  76222. * Specifies the luma threshold for the area that will be blurred by the bloom
  76223. */
  76224. _this._bloomThreshold = 0.9;
  76225. _this._samples = 1;
  76226. _this._hasCleared = false;
  76227. _this._prevPostProcess = null;
  76228. _this._prevPrevPostProcess = null;
  76229. _this._cameras = cameras || scene.cameras;
  76230. _this._originalCameras = _this._cameras.slice();
  76231. _this._buildAllowed = automaticBuild;
  76232. // Initialize
  76233. _this._scene = scene;
  76234. var caps = _this._scene.getEngine().getCaps();
  76235. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76236. // Misc
  76237. if (_this._hdr) {
  76238. if (caps.textureHalfFloatRender) {
  76239. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76240. }
  76241. else if (caps.textureFloatRender) {
  76242. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76243. }
  76244. }
  76245. else {
  76246. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76247. }
  76248. // Attach
  76249. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76250. var engine = _this._scene.getEngine();
  76251. // Create post processes before hand so they can be modified before enabled.
  76252. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76253. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76254. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76255. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76256. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76257. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76258. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76259. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76260. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76261. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76262. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76263. _this.bloomKernel = _this.bloomKernel;
  76264. });
  76265. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76266. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76267. });
  76268. _this._buildPipeline();
  76269. return _this;
  76270. }
  76271. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76272. get: function () {
  76273. return this._sharpenEnabled;
  76274. },
  76275. /**
  76276. * Enable or disable the sharpen process from the pipeline
  76277. */
  76278. set: function (enabled) {
  76279. if (this._sharpenEnabled === enabled) {
  76280. return;
  76281. }
  76282. this._sharpenEnabled = enabled;
  76283. this._buildPipeline();
  76284. },
  76285. enumerable: true,
  76286. configurable: true
  76287. });
  76288. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76289. /**
  76290. * Specifies the size of the bloom blur kernel, relative to the final output size
  76291. */
  76292. get: function () {
  76293. return this._bloomKernel;
  76294. },
  76295. set: function (value) {
  76296. this._bloomKernel = value;
  76297. this.bloom.kernel = value / this._hardwareScaleLevel;
  76298. },
  76299. enumerable: true,
  76300. configurable: true
  76301. });
  76302. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76303. get: function () {
  76304. return this._bloomWeight;
  76305. },
  76306. /**
  76307. * The strength of the bloom.
  76308. */
  76309. set: function (value) {
  76310. if (this._bloomWeight === value) {
  76311. return;
  76312. }
  76313. this.bloom.weight = value;
  76314. this._bloomWeight = value;
  76315. },
  76316. enumerable: true,
  76317. configurable: true
  76318. });
  76319. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76320. get: function () {
  76321. return this._bloomThreshold;
  76322. },
  76323. /**
  76324. * The strength of the bloom.
  76325. */
  76326. set: function (value) {
  76327. if (this._bloomThreshold === value) {
  76328. return;
  76329. }
  76330. this.bloom.threshold = value;
  76331. this._bloomThreshold = value;
  76332. },
  76333. enumerable: true,
  76334. configurable: true
  76335. });
  76336. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76337. get: function () {
  76338. return this._bloomScale;
  76339. },
  76340. /**
  76341. * The scale of the bloom, lower value will provide better performance.
  76342. */
  76343. set: function (value) {
  76344. if (this._bloomScale === value) {
  76345. return;
  76346. }
  76347. this._bloomScale = value;
  76348. // recreate bloom and dispose old as this setting is not dynamic
  76349. this._rebuildBloom();
  76350. this._buildPipeline();
  76351. },
  76352. enumerable: true,
  76353. configurable: true
  76354. });
  76355. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76356. get: function () {
  76357. return this._bloomEnabled;
  76358. },
  76359. /**
  76360. * Enable or disable the bloom from the pipeline
  76361. */
  76362. set: function (enabled) {
  76363. if (this._bloomEnabled === enabled) {
  76364. return;
  76365. }
  76366. this._bloomEnabled = enabled;
  76367. this._buildPipeline();
  76368. },
  76369. enumerable: true,
  76370. configurable: true
  76371. });
  76372. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76373. // recreate bloom and dispose old as this setting is not dynamic
  76374. var oldBloom = this.bloom;
  76375. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76376. this.bloom.threshold = oldBloom.threshold;
  76377. for (var i = 0; i < this._cameras.length; i++) {
  76378. oldBloom.disposeEffects(this._cameras[i]);
  76379. }
  76380. };
  76381. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76382. /**
  76383. * If the depth of field is enabled.
  76384. */
  76385. get: function () {
  76386. return this._depthOfFieldEnabled;
  76387. },
  76388. set: function (enabled) {
  76389. if (this._depthOfFieldEnabled === enabled) {
  76390. return;
  76391. }
  76392. this._depthOfFieldEnabled = enabled;
  76393. this._buildPipeline();
  76394. },
  76395. enumerable: true,
  76396. configurable: true
  76397. });
  76398. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76399. /**
  76400. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76401. */
  76402. get: function () {
  76403. return this._depthOfFieldBlurLevel;
  76404. },
  76405. set: function (value) {
  76406. if (this._depthOfFieldBlurLevel === value) {
  76407. return;
  76408. }
  76409. this._depthOfFieldBlurLevel = value;
  76410. // recreate dof and dispose old as this setting is not dynamic
  76411. var oldDof = this.depthOfField;
  76412. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76413. this.depthOfField.focalLength = oldDof.focalLength;
  76414. this.depthOfField.focusDistance = oldDof.focusDistance;
  76415. this.depthOfField.fStop = oldDof.fStop;
  76416. this.depthOfField.lensSize = oldDof.lensSize;
  76417. for (var i = 0; i < this._cameras.length; i++) {
  76418. oldDof.disposeEffects(this._cameras[i]);
  76419. }
  76420. this._buildPipeline();
  76421. },
  76422. enumerable: true,
  76423. configurable: true
  76424. });
  76425. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76426. get: function () {
  76427. return this._fxaaEnabled;
  76428. },
  76429. /**
  76430. * If the anti aliasing is enabled.
  76431. */
  76432. set: function (enabled) {
  76433. if (this._fxaaEnabled === enabled) {
  76434. return;
  76435. }
  76436. this._fxaaEnabled = enabled;
  76437. this._buildPipeline();
  76438. },
  76439. enumerable: true,
  76440. configurable: true
  76441. });
  76442. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76443. get: function () {
  76444. return this._samples;
  76445. },
  76446. /**
  76447. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76448. */
  76449. set: function (sampleCount) {
  76450. if (this._samples === sampleCount) {
  76451. return;
  76452. }
  76453. this._samples = sampleCount;
  76454. this._buildPipeline();
  76455. },
  76456. enumerable: true,
  76457. configurable: true
  76458. });
  76459. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76460. get: function () {
  76461. return this._imageProcessingEnabled;
  76462. },
  76463. /**
  76464. * If image processing is enabled.
  76465. */
  76466. set: function (enabled) {
  76467. if (this._imageProcessingEnabled === enabled) {
  76468. return;
  76469. }
  76470. this._imageProcessingEnabled = enabled;
  76471. this._buildPipeline();
  76472. },
  76473. enumerable: true,
  76474. configurable: true
  76475. });
  76476. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76477. get: function () {
  76478. return this._glowLayer == null;
  76479. },
  76480. /**
  76481. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76482. */
  76483. set: function (enabled) {
  76484. if (enabled && !this._glowLayer) {
  76485. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76486. }
  76487. else if (!enabled && this._glowLayer) {
  76488. this._glowLayer.dispose();
  76489. this._glowLayer = null;
  76490. }
  76491. },
  76492. enumerable: true,
  76493. configurable: true
  76494. });
  76495. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76496. get: function () {
  76497. return this._chromaticAberrationEnabled;
  76498. },
  76499. /**
  76500. * Enable or disable the chromaticAberration process from the pipeline
  76501. */
  76502. set: function (enabled) {
  76503. if (this._chromaticAberrationEnabled === enabled) {
  76504. return;
  76505. }
  76506. this._chromaticAberrationEnabled = enabled;
  76507. this._buildPipeline();
  76508. },
  76509. enumerable: true,
  76510. configurable: true
  76511. });
  76512. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76513. get: function () {
  76514. return this._grainEnabled;
  76515. },
  76516. /**
  76517. * Enable or disable the grain process from the pipeline
  76518. */
  76519. set: function (enabled) {
  76520. if (this._grainEnabled === enabled) {
  76521. return;
  76522. }
  76523. this._grainEnabled = enabled;
  76524. this._buildPipeline();
  76525. },
  76526. enumerable: true,
  76527. configurable: true
  76528. });
  76529. /**
  76530. * Force the compilation of the entire pipeline.
  76531. */
  76532. DefaultRenderingPipeline.prototype.prepare = function () {
  76533. var previousState = this._buildAllowed;
  76534. this._buildAllowed = true;
  76535. this._buildPipeline();
  76536. this._buildAllowed = previousState;
  76537. };
  76538. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76539. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76540. if (this._hasCleared) {
  76541. postProcess.autoClear = false;
  76542. }
  76543. else {
  76544. postProcess.autoClear = true;
  76545. this._scene.autoClear = false;
  76546. this._hasCleared = true;
  76547. }
  76548. if (!skipTextureSharing) {
  76549. if (this._prevPrevPostProcess) {
  76550. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76551. }
  76552. else {
  76553. postProcess.useOwnOutput();
  76554. }
  76555. if (this._prevPostProcess) {
  76556. this._prevPrevPostProcess = this._prevPostProcess;
  76557. }
  76558. this._prevPostProcess = postProcess;
  76559. }
  76560. };
  76561. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76562. var _this = this;
  76563. if (!this._buildAllowed) {
  76564. return;
  76565. }
  76566. this._scene.autoClear = true;
  76567. var engine = this._scene.getEngine();
  76568. this._disposePostProcesses();
  76569. if (this._cameras !== null) {
  76570. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76571. // get back cameras to be used to reattach pipeline
  76572. this._cameras = this._originalCameras.slice();
  76573. }
  76574. this._reset();
  76575. this._prevPostProcess = null;
  76576. this._prevPrevPostProcess = null;
  76577. this._hasCleared = false;
  76578. if (this.depthOfFieldEnabled) {
  76579. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76580. this.depthOfField.depthTexture = depthTexture;
  76581. if (!this.depthOfField._isReady()) {
  76582. this.depthOfField._updateEffects();
  76583. }
  76584. this.addEffect(this.depthOfField);
  76585. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76586. }
  76587. if (this.bloomEnabled) {
  76588. if (!this.bloom._isReady()) {
  76589. this.bloom._updateEffects();
  76590. }
  76591. this.addEffect(this.bloom);
  76592. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76593. }
  76594. if (this._imageProcessingEnabled) {
  76595. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76596. if (this._hdr) {
  76597. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76598. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76599. }
  76600. else {
  76601. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76602. }
  76603. }
  76604. if (this.sharpenEnabled) {
  76605. if (!this.sharpen.isReady()) {
  76606. this.sharpen.updateEffect();
  76607. }
  76608. this.addEffect(this._sharpenEffect);
  76609. this._setAutoClearAndTextureSharing(this.sharpen);
  76610. }
  76611. if (this.grainEnabled) {
  76612. if (!this.grain.isReady()) {
  76613. this.grain.updateEffect();
  76614. }
  76615. this.addEffect(this._grainEffect);
  76616. this._setAutoClearAndTextureSharing(this.grain);
  76617. }
  76618. if (this.chromaticAberrationEnabled) {
  76619. if (!this.chromaticAberration.isReady()) {
  76620. this.chromaticAberration.updateEffect();
  76621. }
  76622. this.addEffect(this._chromaticAberrationEffect);
  76623. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76624. }
  76625. if (this.fxaaEnabled) {
  76626. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76627. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76628. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76629. }
  76630. if (this._cameras !== null) {
  76631. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76632. }
  76633. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76634. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76635. }
  76636. };
  76637. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76638. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76639. for (var i = 0; i < this._cameras.length; i++) {
  76640. var camera = this._cameras[i];
  76641. if (this.imageProcessing) {
  76642. this.imageProcessing.dispose(camera);
  76643. }
  76644. if (this.fxaa) {
  76645. this.fxaa.dispose(camera);
  76646. }
  76647. // These are created in the constructor and should not be disposed on every pipeline change
  76648. if (disposeNonRecreated) {
  76649. if (this.sharpen) {
  76650. this.sharpen.dispose(camera);
  76651. }
  76652. if (this.depthOfField) {
  76653. this.depthOfField.disposeEffects(camera);
  76654. }
  76655. if (this.bloom) {
  76656. this.bloom.disposeEffects(camera);
  76657. }
  76658. if (this.chromaticAberration) {
  76659. this.chromaticAberration.dispose(camera);
  76660. }
  76661. if (this.grain) {
  76662. this.grain.dispose(camera);
  76663. }
  76664. if (this._glowLayer) {
  76665. this._glowLayer.dispose();
  76666. }
  76667. }
  76668. }
  76669. this.imageProcessing = null;
  76670. this.fxaa = null;
  76671. if (disposeNonRecreated) {
  76672. this.sharpen = null;
  76673. this._sharpenEffect = null;
  76674. this.depthOfField = null;
  76675. this.bloom = null;
  76676. this.chromaticAberration = null;
  76677. this._chromaticAberrationEffect = null;
  76678. this.grain = null;
  76679. this._grainEffect = null;
  76680. this._glowLayer = null;
  76681. }
  76682. };
  76683. /**
  76684. * Dispose of the pipeline and stop all post processes
  76685. */
  76686. DefaultRenderingPipeline.prototype.dispose = function () {
  76687. this._disposePostProcesses(true);
  76688. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76689. this._scene.autoClear = true;
  76690. if (this._resizeObserver) {
  76691. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76692. this._resizeObserver = null;
  76693. }
  76694. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76695. _super.prototype.dispose.call(this);
  76696. };
  76697. /**
  76698. * Serialize the rendering pipeline (Used when exporting)
  76699. * @returns the serialized object
  76700. */
  76701. DefaultRenderingPipeline.prototype.serialize = function () {
  76702. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76703. serializationObject.customType = "DefaultRenderingPipeline";
  76704. return serializationObject;
  76705. };
  76706. /**
  76707. * Parse the serialized pipeline
  76708. * @param source Source pipeline.
  76709. * @param scene The scene to load the pipeline to.
  76710. * @param rootUrl The URL of the serialized pipeline.
  76711. * @returns An instantiated pipeline from the serialized object.
  76712. */
  76713. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76714. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76715. };
  76716. __decorate([
  76717. BABYLON.serialize()
  76718. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76719. __decorate([
  76720. BABYLON.serialize()
  76721. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76722. __decorate([
  76723. BABYLON.serialize()
  76724. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76725. __decorate([
  76726. BABYLON.serialize()
  76727. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76728. __decorate([
  76729. BABYLON.serialize()
  76730. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76731. __decorate([
  76732. BABYLON.serialize()
  76733. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76734. __decorate([
  76735. BABYLON.serialize()
  76736. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76737. __decorate([
  76738. BABYLON.serialize()
  76739. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76740. __decorate([
  76741. BABYLON.serialize()
  76742. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76743. __decorate([
  76744. BABYLON.serialize()
  76745. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76746. __decorate([
  76747. BABYLON.serialize()
  76748. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76749. __decorate([
  76750. BABYLON.serialize()
  76751. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76752. __decorate([
  76753. BABYLON.serialize()
  76754. ], DefaultRenderingPipeline.prototype, "samples", null);
  76755. __decorate([
  76756. BABYLON.serialize()
  76757. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76758. __decorate([
  76759. BABYLON.serialize()
  76760. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76761. __decorate([
  76762. BABYLON.serialize()
  76763. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76764. __decorate([
  76765. BABYLON.serialize()
  76766. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76767. return DefaultRenderingPipeline;
  76768. }(BABYLON.PostProcessRenderPipeline));
  76769. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76770. })(BABYLON || (BABYLON = {}));
  76771. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76772. var BABYLON;
  76773. (function (BABYLON) {
  76774. /**
  76775. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76776. */
  76777. var GeometryBufferRenderer = /** @class */ (function () {
  76778. /**
  76779. * Creates a new G Buffer for the scene
  76780. * @param scene The scene the buffer belongs to
  76781. * @param ratio How big is the buffer related to the main canvas.
  76782. */
  76783. function GeometryBufferRenderer(scene, ratio) {
  76784. if (ratio === void 0) { ratio = 1; }
  76785. this._enablePosition = false;
  76786. this._scene = scene;
  76787. this._ratio = ratio;
  76788. // Render target
  76789. this._createRenderTargets();
  76790. }
  76791. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76792. /**
  76793. * Set the render list (meshes to be rendered) used in the G buffer.
  76794. */
  76795. set: function (meshes) {
  76796. this._multiRenderTarget.renderList = meshes;
  76797. },
  76798. enumerable: true,
  76799. configurable: true
  76800. });
  76801. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76802. /**
  76803. * Gets wether or not G buffer are supported by the running hardware.
  76804. * This requires draw buffer supports
  76805. */
  76806. get: function () {
  76807. return this._multiRenderTarget.isSupported;
  76808. },
  76809. enumerable: true,
  76810. configurable: true
  76811. });
  76812. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76813. /**
  76814. * Gets wether or not position are enabled for the G buffer.
  76815. */
  76816. get: function () {
  76817. return this._enablePosition;
  76818. },
  76819. /**
  76820. * Sets wether or not position are enabled for the G buffer.
  76821. */
  76822. set: function (enable) {
  76823. this._enablePosition = enable;
  76824. this.dispose();
  76825. this._createRenderTargets();
  76826. },
  76827. enumerable: true,
  76828. configurable: true
  76829. });
  76830. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76831. /**
  76832. * Gets the scene associated with the buffer.
  76833. */
  76834. get: function () {
  76835. return this._scene;
  76836. },
  76837. enumerable: true,
  76838. configurable: true
  76839. });
  76840. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76841. /**
  76842. * Gets the ratio used by the buffer during its creation.
  76843. * How big is the buffer related to the main canvas.
  76844. */
  76845. get: function () {
  76846. return this._ratio;
  76847. },
  76848. enumerable: true,
  76849. configurable: true
  76850. });
  76851. /**
  76852. * Checks wether everything is ready to render a submesh to the G buffer.
  76853. * @param subMesh the submesh to check readiness for
  76854. * @param useInstances is the mesh drawn using instance or not
  76855. * @returns true if ready otherwise false
  76856. */
  76857. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76858. var material = subMesh.getMaterial();
  76859. if (material && material.disableDepthWrite) {
  76860. return false;
  76861. }
  76862. var defines = [];
  76863. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76864. var mesh = subMesh.getMesh();
  76865. // Alpha test
  76866. if (material && material.needAlphaTesting()) {
  76867. defines.push("#define ALPHATEST");
  76868. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76869. attribs.push(BABYLON.VertexBuffer.UVKind);
  76870. defines.push("#define UV1");
  76871. }
  76872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76873. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76874. defines.push("#define UV2");
  76875. }
  76876. }
  76877. // Buffers
  76878. if (this._enablePosition) {
  76879. defines.push("#define POSITION");
  76880. }
  76881. // Bones
  76882. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76883. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76884. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76885. if (mesh.numBoneInfluencers > 4) {
  76886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76888. }
  76889. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76890. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76891. }
  76892. else {
  76893. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76894. }
  76895. // Instances
  76896. if (useInstances) {
  76897. defines.push("#define INSTANCES");
  76898. attribs.push("world0");
  76899. attribs.push("world1");
  76900. attribs.push("world2");
  76901. attribs.push("world3");
  76902. }
  76903. // Get correct effect
  76904. var join = defines.join("\n");
  76905. if (this._cachedDefines !== join) {
  76906. this._cachedDefines = join;
  76907. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76908. }
  76909. return this._effect.isReady();
  76910. };
  76911. /**
  76912. * Gets the current underlying G Buffer.
  76913. * @returns the buffer
  76914. */
  76915. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76916. return this._multiRenderTarget;
  76917. };
  76918. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76919. /**
  76920. * Gets the number of samples used to render the buffer (anti aliasing).
  76921. */
  76922. get: function () {
  76923. return this._multiRenderTarget.samples;
  76924. },
  76925. /**
  76926. * Sets the number of samples used to render the buffer (anti aliasing).
  76927. */
  76928. set: function (value) {
  76929. this._multiRenderTarget.samples = value;
  76930. },
  76931. enumerable: true,
  76932. configurable: true
  76933. });
  76934. /**
  76935. * Disposes the renderer and frees up associated resources.
  76936. */
  76937. GeometryBufferRenderer.prototype.dispose = function () {
  76938. this.getGBuffer().dispose();
  76939. };
  76940. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76941. var _this = this;
  76942. var engine = this._scene.getEngine();
  76943. var count = this._enablePosition ? 3 : 2;
  76944. 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 });
  76945. if (!this.isSupported) {
  76946. return;
  76947. }
  76948. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76949. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76950. this._multiRenderTarget.refreshRate = 1;
  76951. this._multiRenderTarget.renderParticles = false;
  76952. this._multiRenderTarget.renderList = null;
  76953. // set default depth value to 1.0 (far away)
  76954. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76955. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76956. });
  76957. // Custom render function
  76958. var renderSubMesh = function (subMesh) {
  76959. var mesh = subMesh.getRenderingMesh();
  76960. var scene = _this._scene;
  76961. var engine = scene.getEngine();
  76962. var material = subMesh.getMaterial();
  76963. if (!material) {
  76964. return;
  76965. }
  76966. // Culling
  76967. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76968. // Managing instances
  76969. var batch = mesh._getInstancesRenderList(subMesh._id);
  76970. if (batch.mustReturn) {
  76971. return;
  76972. }
  76973. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76974. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76975. engine.enableEffect(_this._effect);
  76976. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76977. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76978. _this._effect.setMatrix("view", scene.getViewMatrix());
  76979. // Alpha test
  76980. if (material && material.needAlphaTesting()) {
  76981. var alphaTexture = material.getAlphaTestTexture();
  76982. if (alphaTexture) {
  76983. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76984. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76985. }
  76986. }
  76987. // Bones
  76988. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76989. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76990. }
  76991. // Draw
  76992. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76993. }
  76994. };
  76995. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76996. var index;
  76997. if (depthOnlySubMeshes.length) {
  76998. engine.setColorWrite(false);
  76999. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77000. renderSubMesh(depthOnlySubMeshes.data[index]);
  77001. }
  77002. engine.setColorWrite(true);
  77003. }
  77004. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77005. renderSubMesh(opaqueSubMeshes.data[index]);
  77006. }
  77007. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77008. renderSubMesh(alphaTestSubMeshes.data[index]);
  77009. }
  77010. };
  77011. };
  77012. return GeometryBufferRenderer;
  77013. }());
  77014. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77015. })(BABYLON || (BABYLON = {}));
  77016. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77017. var BABYLON;
  77018. (function (BABYLON) {
  77019. var RefractionPostProcess = /** @class */ (function (_super) {
  77020. __extends(RefractionPostProcess, _super);
  77021. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77022. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77023. _this.color = color;
  77024. _this.depth = depth;
  77025. _this.colorLevel = colorLevel;
  77026. _this._ownRefractionTexture = true;
  77027. _this.onActivateObservable.add(function (cam) {
  77028. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77029. });
  77030. _this.onApplyObservable.add(function (effect) {
  77031. effect.setColor3("baseColor", _this.color);
  77032. effect.setFloat("depth", _this.depth);
  77033. effect.setFloat("colorLevel", _this.colorLevel);
  77034. effect.setTexture("refractionSampler", _this._refTexture);
  77035. });
  77036. return _this;
  77037. }
  77038. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77039. /**
  77040. * Gets or sets the refraction texture
  77041. * Please note that you are responsible for disposing the texture if you set it manually
  77042. */
  77043. get: function () {
  77044. return this._refTexture;
  77045. },
  77046. set: function (value) {
  77047. if (this._refTexture && this._ownRefractionTexture) {
  77048. this._refTexture.dispose();
  77049. }
  77050. this._refTexture = value;
  77051. this._ownRefractionTexture = false;
  77052. },
  77053. enumerable: true,
  77054. configurable: true
  77055. });
  77056. // Methods
  77057. RefractionPostProcess.prototype.dispose = function (camera) {
  77058. if (this._refTexture && this._ownRefractionTexture) {
  77059. this._refTexture.dispose();
  77060. this._refTexture = null;
  77061. }
  77062. _super.prototype.dispose.call(this, camera);
  77063. };
  77064. return RefractionPostProcess;
  77065. }(BABYLON.PostProcess));
  77066. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77067. })(BABYLON || (BABYLON = {}));
  77068. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77069. var BABYLON;
  77070. (function (BABYLON) {
  77071. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77072. __extends(BlackAndWhitePostProcess, _super);
  77073. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77074. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77075. _this.degree = 1;
  77076. _this.onApplyObservable.add(function (effect) {
  77077. effect.setFloat("degree", _this.degree);
  77078. });
  77079. return _this;
  77080. }
  77081. return BlackAndWhitePostProcess;
  77082. }(BABYLON.PostProcess));
  77083. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77084. })(BABYLON || (BABYLON = {}));
  77085. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77086. var BABYLON;
  77087. (function (BABYLON) {
  77088. /**
  77089. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  77090. * input texture to perform effects such as edge detection or sharpening
  77091. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  77092. */
  77093. var ConvolutionPostProcess = /** @class */ (function (_super) {
  77094. __extends(ConvolutionPostProcess, _super);
  77095. /**
  77096. * Creates a new instance ConvolutionPostProcess
  77097. * @param name The name of the effect.
  77098. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  77099. * @param options The required width/height ratio to downsize to before computing the render pass.
  77100. * @param camera The camera to apply the render pass to.
  77101. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77102. * @param engine The engine which the post process will be applied. (default: current engine)
  77103. * @param reusable If the post process can be reused on the same frame. (default: false)
  77104. * @param textureType Type of textures used when performing the post process. (default: 0)
  77105. */
  77106. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  77107. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77108. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77109. _this.kernel = kernel;
  77110. _this.onApply = function (effect) {
  77111. effect.setFloat2("screenSize", _this.width, _this.height);
  77112. effect.setArray("kernel", _this.kernel);
  77113. };
  77114. return _this;
  77115. }
  77116. // Statics
  77117. /**
  77118. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77119. */
  77120. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  77121. /**
  77122. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77123. */
  77124. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  77125. /**
  77126. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77127. */
  77128. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  77129. /**
  77130. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77131. */
  77132. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  77133. /**
  77134. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77135. */
  77136. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  77137. /**
  77138. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  77139. */
  77140. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  77141. return ConvolutionPostProcess;
  77142. }(BABYLON.PostProcess));
  77143. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  77144. })(BABYLON || (BABYLON = {}));
  77145. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  77146. var BABYLON;
  77147. (function (BABYLON) {
  77148. var FilterPostProcess = /** @class */ (function (_super) {
  77149. __extends(FilterPostProcess, _super);
  77150. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  77151. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  77152. _this.kernelMatrix = kernelMatrix;
  77153. _this.onApply = function (effect) {
  77154. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  77155. };
  77156. return _this;
  77157. }
  77158. return FilterPostProcess;
  77159. }(BABYLON.PostProcess));
  77160. BABYLON.FilterPostProcess = FilterPostProcess;
  77161. })(BABYLON || (BABYLON = {}));
  77162. //# sourceMappingURL=babylon.filterPostProcess.js.map
  77163. var BABYLON;
  77164. (function (BABYLON) {
  77165. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  77166. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  77167. __extends(VolumetricLightScatteringPostProcess, _super);
  77168. /**
  77169. * @constructor
  77170. * @param {string} name - The post-process name
  77171. * @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)
  77172. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  77173. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  77174. * @param {number} samples - The post-process quality, default 100
  77175. * @param {number} samplingMode - The post-process filtering mode
  77176. * @param {BABYLON.Engine} engine - The babylon engine
  77177. * @param {boolean} reusable - If the post-process is reusable
  77178. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  77179. */
  77180. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  77181. if (samples === void 0) { samples = 100; }
  77182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77183. 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;
  77184. _this._screenCoordinates = BABYLON.Vector2.Zero();
  77185. /**
  77186. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  77187. */
  77188. _this.customMeshPosition = BABYLON.Vector3.Zero();
  77189. /**
  77190. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  77191. */
  77192. _this.useCustomMeshPosition = false;
  77193. /**
  77194. * If the post-process should inverse the light scattering direction
  77195. */
  77196. _this.invert = true;
  77197. /**
  77198. * Array containing the excluded meshes not rendered in the internal pass
  77199. */
  77200. _this.excludedMeshes = new Array();
  77201. /**
  77202. * Controls the overall intensity of the post-process
  77203. */
  77204. _this.exposure = 0.3;
  77205. /**
  77206. * Dissipates each sample's contribution in range [0, 1]
  77207. */
  77208. _this.decay = 0.96815;
  77209. /**
  77210. * Controls the overall intensity of each sample
  77211. */
  77212. _this.weight = 0.58767;
  77213. /**
  77214. * Controls the density of each sample
  77215. */
  77216. _this.density = 0.926;
  77217. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  77218. engine = scene.getEngine();
  77219. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  77220. // Configure mesh
  77221. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  77222. // Configure
  77223. _this._createPass(scene, ratio.passRatio || ratio);
  77224. _this.onActivate = function (camera) {
  77225. if (!_this.isSupported) {
  77226. _this.dispose(camera);
  77227. }
  77228. _this.onActivate = null;
  77229. };
  77230. _this.onApplyObservable.add(function (effect) {
  77231. _this._updateMeshScreenCoordinates(scene);
  77232. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  77233. effect.setFloat("exposure", _this.exposure);
  77234. effect.setFloat("decay", _this.decay);
  77235. effect.setFloat("weight", _this.weight);
  77236. effect.setFloat("density", _this.density);
  77237. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  77238. });
  77239. return _this;
  77240. }
  77241. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  77242. get: function () {
  77243. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77244. return false;
  77245. },
  77246. set: function (useDiffuseColor) {
  77247. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  77248. },
  77249. enumerable: true,
  77250. configurable: true
  77251. });
  77252. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  77253. return "VolumetricLightScatteringPostProcess";
  77254. };
  77255. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  77256. var mesh = subMesh.getMesh();
  77257. // Render this.mesh as default
  77258. if (mesh === this.mesh && mesh.material) {
  77259. return mesh.material.isReady(mesh);
  77260. }
  77261. var defines = [];
  77262. var attribs = [BABYLON.VertexBuffer.PositionKind];
  77263. var material = subMesh.getMaterial();
  77264. // Alpha test
  77265. if (material) {
  77266. if (material.needAlphaTesting()) {
  77267. defines.push("#define ALPHATEST");
  77268. }
  77269. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77270. attribs.push(BABYLON.VertexBuffer.UVKind);
  77271. defines.push("#define UV1");
  77272. }
  77273. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77274. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77275. defines.push("#define UV2");
  77276. }
  77277. }
  77278. // Bones
  77279. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77282. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77283. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77284. }
  77285. else {
  77286. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77287. }
  77288. // Instances
  77289. if (useInstances) {
  77290. defines.push("#define INSTANCES");
  77291. attribs.push("world0");
  77292. attribs.push("world1");
  77293. attribs.push("world2");
  77294. attribs.push("world3");
  77295. }
  77296. // Get correct effect
  77297. var join = defines.join("\n");
  77298. if (this._cachedDefines !== join) {
  77299. this._cachedDefines = join;
  77300. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  77301. }
  77302. return this._volumetricLightScatteringPass.isReady();
  77303. };
  77304. /**
  77305. * Sets the new light position for light scattering effect
  77306. * @param {BABYLON.Vector3} The new custom light position
  77307. */
  77308. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  77309. this.customMeshPosition = position;
  77310. };
  77311. /**
  77312. * Returns the light position for light scattering effect
  77313. * @return {BABYLON.Vector3} The custom light position
  77314. */
  77315. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  77316. return this.customMeshPosition;
  77317. };
  77318. /**
  77319. * Disposes the internal assets and detaches the post-process from the camera
  77320. */
  77321. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  77322. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  77323. if (rttIndex !== -1) {
  77324. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  77325. }
  77326. this._volumetricLightScatteringRTT.dispose();
  77327. _super.prototype.dispose.call(this, camera);
  77328. };
  77329. /**
  77330. * Returns the render target texture used by the post-process
  77331. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  77332. */
  77333. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  77334. return this._volumetricLightScatteringRTT;
  77335. };
  77336. // Private methods
  77337. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  77338. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  77339. return true;
  77340. }
  77341. return false;
  77342. };
  77343. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  77344. var _this = this;
  77345. var engine = scene.getEngine();
  77346. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77347. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77348. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77349. this._volumetricLightScatteringRTT.renderList = null;
  77350. this._volumetricLightScatteringRTT.renderParticles = false;
  77351. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  77352. var camera = this.getCamera();
  77353. if (camera) {
  77354. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77355. }
  77356. else {
  77357. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  77358. }
  77359. // Custom render function for submeshes
  77360. var renderSubMesh = function (subMesh) {
  77361. var mesh = subMesh.getRenderingMesh();
  77362. if (_this._meshExcluded(mesh)) {
  77363. return;
  77364. }
  77365. var material = subMesh.getMaterial();
  77366. if (!material) {
  77367. return;
  77368. }
  77369. var scene = mesh.getScene();
  77370. var engine = scene.getEngine();
  77371. // Culling
  77372. engine.setState(material.backFaceCulling);
  77373. // Managing instances
  77374. var batch = mesh._getInstancesRenderList(subMesh._id);
  77375. if (batch.mustReturn) {
  77376. return;
  77377. }
  77378. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77379. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  77380. var effect = _this._volumetricLightScatteringPass;
  77381. if (mesh === _this.mesh) {
  77382. if (subMesh.effect) {
  77383. effect = subMesh.effect;
  77384. }
  77385. else {
  77386. effect = material.getEffect();
  77387. }
  77388. }
  77389. engine.enableEffect(effect);
  77390. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  77391. if (mesh === _this.mesh) {
  77392. material.bind(mesh.getWorldMatrix(), mesh);
  77393. }
  77394. else {
  77395. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  77396. // Alpha test
  77397. if (material && material.needAlphaTesting()) {
  77398. var alphaTexture = material.getAlphaTestTexture();
  77399. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  77400. if (alphaTexture) {
  77401. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77402. }
  77403. }
  77404. // Bones
  77405. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77406. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77407. }
  77408. }
  77409. // Draw
  77410. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  77411. }
  77412. };
  77413. // Render target texture callbacks
  77414. var savedSceneClearColor;
  77415. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  77416. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  77417. savedSceneClearColor = scene.clearColor;
  77418. scene.clearColor = sceneClearColor;
  77419. });
  77420. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  77421. scene.clearColor = savedSceneClearColor;
  77422. });
  77423. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77424. var engine = scene.getEngine();
  77425. var index;
  77426. if (depthOnlySubMeshes.length) {
  77427. engine.setColorWrite(false);
  77428. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77429. renderSubMesh(depthOnlySubMeshes.data[index]);
  77430. }
  77431. engine.setColorWrite(true);
  77432. }
  77433. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77434. renderSubMesh(opaqueSubMeshes.data[index]);
  77435. }
  77436. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77437. renderSubMesh(alphaTestSubMeshes.data[index]);
  77438. }
  77439. if (transparentSubMeshes.length) {
  77440. // Sort sub meshes
  77441. for (index = 0; index < transparentSubMeshes.length; index++) {
  77442. var submesh = transparentSubMeshes.data[index];
  77443. var boundingInfo = submesh.getBoundingInfo();
  77444. if (boundingInfo && scene.activeCamera) {
  77445. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  77446. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  77447. }
  77448. }
  77449. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  77450. sortedArray.sort(function (a, b) {
  77451. // Alpha index first
  77452. if (a._alphaIndex > b._alphaIndex) {
  77453. return 1;
  77454. }
  77455. if (a._alphaIndex < b._alphaIndex) {
  77456. return -1;
  77457. }
  77458. // Then distance to camera
  77459. if (a._distanceToCamera < b._distanceToCamera) {
  77460. return 1;
  77461. }
  77462. if (a._distanceToCamera > b._distanceToCamera) {
  77463. return -1;
  77464. }
  77465. return 0;
  77466. });
  77467. // Render sub meshes
  77468. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  77469. for (index = 0; index < sortedArray.length; index++) {
  77470. renderSubMesh(sortedArray[index]);
  77471. }
  77472. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77473. }
  77474. };
  77475. };
  77476. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  77477. var transform = scene.getTransformMatrix();
  77478. var meshPosition;
  77479. if (this.useCustomMeshPosition) {
  77480. meshPosition = this.customMeshPosition;
  77481. }
  77482. else if (this.attachedNode) {
  77483. meshPosition = this.attachedNode.position;
  77484. }
  77485. else {
  77486. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  77487. }
  77488. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  77489. this._screenCoordinates.x = pos.x / this._viewPort.width;
  77490. this._screenCoordinates.y = pos.y / this._viewPort.height;
  77491. if (this.invert)
  77492. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  77493. };
  77494. // Static methods
  77495. /**
  77496. * Creates a default mesh for the Volumeric Light Scattering post-process
  77497. * @param {string} The mesh name
  77498. * @param {BABYLON.Scene} The scene where to create the mesh
  77499. * @return {BABYLON.Mesh} the default mesh
  77500. */
  77501. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  77502. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  77503. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  77504. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  77505. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  77506. mesh.material = material;
  77507. return mesh;
  77508. };
  77509. __decorate([
  77510. BABYLON.serializeAsVector3()
  77511. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  77512. __decorate([
  77513. BABYLON.serialize()
  77514. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  77515. __decorate([
  77516. BABYLON.serialize()
  77517. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  77518. __decorate([
  77519. BABYLON.serializeAsMeshReference()
  77520. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  77521. __decorate([
  77522. BABYLON.serialize()
  77523. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  77524. __decorate([
  77525. BABYLON.serialize()
  77526. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  77527. __decorate([
  77528. BABYLON.serialize()
  77529. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  77530. __decorate([
  77531. BABYLON.serialize()
  77532. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  77533. __decorate([
  77534. BABYLON.serialize()
  77535. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  77536. return VolumetricLightScatteringPostProcess;
  77537. }(BABYLON.PostProcess));
  77538. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  77539. })(BABYLON || (BABYLON = {}));
  77540. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  77541. //
  77542. // This post-process allows the modification of rendered colors by using
  77543. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77544. //
  77545. // The object needs to be provided an url to a texture containing the color
  77546. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77547. // Use an image editing software to tweak the LUT to match your needs.
  77548. //
  77549. // For an example of a color LUT, see here:
  77550. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77551. // For explanations on color grading, see here:
  77552. // http://udn.epicgames.com/Three/ColorGrading.html
  77553. //
  77554. var BABYLON;
  77555. (function (BABYLON) {
  77556. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77557. __extends(ColorCorrectionPostProcess, _super);
  77558. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77559. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77560. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77561. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77562. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77563. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77564. _this.onApply = function (effect) {
  77565. effect.setTexture("colorTable", _this._colorTableTexture);
  77566. };
  77567. return _this;
  77568. }
  77569. return ColorCorrectionPostProcess;
  77570. }(BABYLON.PostProcess));
  77571. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77572. })(BABYLON || (BABYLON = {}));
  77573. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77574. var BABYLON;
  77575. (function (BABYLON) {
  77576. /** Defines operator used for tonemapping */
  77577. var TonemappingOperator;
  77578. (function (TonemappingOperator) {
  77579. /** Hable */
  77580. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77581. /** Reinhard */
  77582. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77583. /** HejiDawson */
  77584. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77585. /** Photographic */
  77586. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77587. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77588. ;
  77589. /**
  77590. * Defines a post process to apply tone mapping
  77591. */
  77592. var TonemapPostProcess = /** @class */ (function (_super) {
  77593. __extends(TonemapPostProcess, _super);
  77594. /**
  77595. * Creates a new TonemapPostProcess
  77596. * @param name defines the name of the postprocess
  77597. * @param _operator defines the operator to use
  77598. * @param exposureAdjustment defines the required exposure adjustement
  77599. * @param camera defines the camera to use (can be null)
  77600. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77601. * @param engine defines the hosting engine (can be ignore if camera is set)
  77602. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77603. */
  77604. function TonemapPostProcess(name, _operator,
  77605. /** Defines the required exposure adjustement */
  77606. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77608. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77609. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77610. _this._operator = _operator;
  77611. _this.exposureAdjustment = exposureAdjustment;
  77612. var defines = "#define ";
  77613. if (_this._operator === TonemappingOperator.Hable)
  77614. defines += "HABLE_TONEMAPPING";
  77615. else if (_this._operator === TonemappingOperator.Reinhard)
  77616. defines += "REINHARD_TONEMAPPING";
  77617. else if (_this._operator === TonemappingOperator.HejiDawson)
  77618. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77619. else if (_this._operator === TonemappingOperator.Photographic)
  77620. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77621. //sadly a second call to create the effect.
  77622. _this.updateEffect(defines);
  77623. _this.onApply = function (effect) {
  77624. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77625. };
  77626. return _this;
  77627. }
  77628. return TonemapPostProcess;
  77629. }(BABYLON.PostProcess));
  77630. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77631. })(BABYLON || (BABYLON = {}));
  77632. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77633. var BABYLON;
  77634. (function (BABYLON) {
  77635. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77636. __extends(DisplayPassPostProcess, _super);
  77637. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77638. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77639. }
  77640. return DisplayPassPostProcess;
  77641. }(BABYLON.PostProcess));
  77642. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77643. })(BABYLON || (BABYLON = {}));
  77644. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77645. var BABYLON;
  77646. (function (BABYLON) {
  77647. var HighlightsPostProcess = /** @class */ (function (_super) {
  77648. __extends(HighlightsPostProcess, _super);
  77649. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77650. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77651. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77652. }
  77653. return HighlightsPostProcess;
  77654. }(BABYLON.PostProcess));
  77655. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77656. })(BABYLON || (BABYLON = {}));
  77657. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77658. var BABYLON;
  77659. (function (BABYLON) {
  77660. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77661. __extends(ImageProcessingPostProcess, _super);
  77662. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77663. if (camera === void 0) { camera = null; }
  77664. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77665. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77666. _this._fromLinearSpace = true;
  77667. /**
  77668. * Defines cache preventing GC.
  77669. */
  77670. _this._defines = {
  77671. IMAGEPROCESSING: false,
  77672. VIGNETTE: false,
  77673. VIGNETTEBLENDMODEMULTIPLY: false,
  77674. VIGNETTEBLENDMODEOPAQUE: false,
  77675. TONEMAPPING: false,
  77676. CONTRAST: false,
  77677. COLORCURVES: false,
  77678. COLORGRADING: false,
  77679. COLORGRADING3D: false,
  77680. FROMLINEARSPACE: false,
  77681. SAMPLER3DGREENDEPTH: false,
  77682. SAMPLER3DBGRMAP: false,
  77683. IMAGEPROCESSINGPOSTPROCESS: false,
  77684. EXPOSURE: false,
  77685. };
  77686. // Setup the configuration as forced by the constructor. This would then not force the
  77687. // scene materials output in linear space and let untouched the default forward pass.
  77688. if (imageProcessingConfiguration) {
  77689. imageProcessingConfiguration.applyByPostProcess = true;
  77690. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77691. // This will cause the shader to be compiled
  77692. _this.fromLinearSpace = false;
  77693. }
  77694. // Setup the default processing configuration to the scene.
  77695. else {
  77696. _this._attachImageProcessingConfiguration(null, true);
  77697. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77698. }
  77699. _this.onApply = function (effect) {
  77700. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77701. };
  77702. return _this;
  77703. }
  77704. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77705. /**
  77706. * Gets the image processing configuration used either in this material.
  77707. */
  77708. get: function () {
  77709. return this._imageProcessingConfiguration;
  77710. },
  77711. /**
  77712. * Sets the Default image processing configuration used either in the this material.
  77713. *
  77714. * If sets to null, the scene one is in use.
  77715. */
  77716. set: function (value) {
  77717. this._attachImageProcessingConfiguration(value);
  77718. },
  77719. enumerable: true,
  77720. configurable: true
  77721. });
  77722. /**
  77723. * Attaches a new image processing configuration to the PBR Material.
  77724. * @param configuration
  77725. */
  77726. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77727. var _this = this;
  77728. if (doNotBuild === void 0) { doNotBuild = false; }
  77729. if (configuration === this._imageProcessingConfiguration) {
  77730. return;
  77731. }
  77732. // Detaches observer.
  77733. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77734. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77735. }
  77736. // Pick the scene configuration if needed.
  77737. if (!configuration) {
  77738. var scene = null;
  77739. var engine = this.getEngine();
  77740. var camera = this.getCamera();
  77741. if (camera) {
  77742. scene = camera.getScene();
  77743. }
  77744. else if (engine && engine.scenes) {
  77745. var scenes = engine.scenes;
  77746. scene = scenes[scenes.length - 1];
  77747. }
  77748. else {
  77749. scene = BABYLON.Engine.LastCreatedScene;
  77750. }
  77751. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77752. }
  77753. else {
  77754. this._imageProcessingConfiguration = configuration;
  77755. }
  77756. // Attaches observer.
  77757. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77758. _this._updateParameters();
  77759. });
  77760. // Ensure the effect will be rebuilt.
  77761. if (!doNotBuild) {
  77762. this._updateParameters();
  77763. }
  77764. };
  77765. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77766. /**
  77767. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77768. */
  77769. get: function () {
  77770. return this.imageProcessingConfiguration.colorCurves;
  77771. },
  77772. /**
  77773. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77774. */
  77775. set: function (value) {
  77776. this.imageProcessingConfiguration.colorCurves = value;
  77777. },
  77778. enumerable: true,
  77779. configurable: true
  77780. });
  77781. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77782. /**
  77783. * Gets wether the color curves effect is enabled.
  77784. */
  77785. get: function () {
  77786. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77787. },
  77788. /**
  77789. * Sets wether the color curves effect is enabled.
  77790. */
  77791. set: function (value) {
  77792. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77793. },
  77794. enumerable: true,
  77795. configurable: true
  77796. });
  77797. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77798. /**
  77799. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77800. */
  77801. get: function () {
  77802. return this.imageProcessingConfiguration.colorGradingTexture;
  77803. },
  77804. /**
  77805. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77806. */
  77807. set: function (value) {
  77808. this.imageProcessingConfiguration.colorGradingTexture = value;
  77809. },
  77810. enumerable: true,
  77811. configurable: true
  77812. });
  77813. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77814. /**
  77815. * Gets wether the color grading effect is enabled.
  77816. */
  77817. get: function () {
  77818. return this.imageProcessingConfiguration.colorGradingEnabled;
  77819. },
  77820. /**
  77821. * Gets wether the color grading effect is enabled.
  77822. */
  77823. set: function (value) {
  77824. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77825. },
  77826. enumerable: true,
  77827. configurable: true
  77828. });
  77829. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77830. /**
  77831. * Gets exposure used in the effect.
  77832. */
  77833. get: function () {
  77834. return this.imageProcessingConfiguration.exposure;
  77835. },
  77836. /**
  77837. * Sets exposure used in the effect.
  77838. */
  77839. set: function (value) {
  77840. this.imageProcessingConfiguration.exposure = value;
  77841. },
  77842. enumerable: true,
  77843. configurable: true
  77844. });
  77845. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77846. /**
  77847. * Gets wether tonemapping is enabled or not.
  77848. */
  77849. get: function () {
  77850. return this._imageProcessingConfiguration.toneMappingEnabled;
  77851. },
  77852. /**
  77853. * Sets wether tonemapping is enabled or not
  77854. */
  77855. set: function (value) {
  77856. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77857. },
  77858. enumerable: true,
  77859. configurable: true
  77860. });
  77861. ;
  77862. ;
  77863. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77864. /**
  77865. * Gets contrast used in the effect.
  77866. */
  77867. get: function () {
  77868. return this.imageProcessingConfiguration.contrast;
  77869. },
  77870. /**
  77871. * Sets contrast used in the effect.
  77872. */
  77873. set: function (value) {
  77874. this.imageProcessingConfiguration.contrast = value;
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77880. /**
  77881. * Gets Vignette stretch size.
  77882. */
  77883. get: function () {
  77884. return this.imageProcessingConfiguration.vignetteStretch;
  77885. },
  77886. /**
  77887. * Sets Vignette stretch size.
  77888. */
  77889. set: function (value) {
  77890. this.imageProcessingConfiguration.vignetteStretch = value;
  77891. },
  77892. enumerable: true,
  77893. configurable: true
  77894. });
  77895. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77896. /**
  77897. * Gets Vignette centre X Offset.
  77898. */
  77899. get: function () {
  77900. return this.imageProcessingConfiguration.vignetteCentreX;
  77901. },
  77902. /**
  77903. * Sets Vignette centre X Offset.
  77904. */
  77905. set: function (value) {
  77906. this.imageProcessingConfiguration.vignetteCentreX = value;
  77907. },
  77908. enumerable: true,
  77909. configurable: true
  77910. });
  77911. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77912. /**
  77913. * Gets Vignette centre Y Offset.
  77914. */
  77915. get: function () {
  77916. return this.imageProcessingConfiguration.vignetteCentreY;
  77917. },
  77918. /**
  77919. * Sets Vignette centre Y Offset.
  77920. */
  77921. set: function (value) {
  77922. this.imageProcessingConfiguration.vignetteCentreY = value;
  77923. },
  77924. enumerable: true,
  77925. configurable: true
  77926. });
  77927. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77928. /**
  77929. * Gets Vignette weight or intensity of the vignette effect.
  77930. */
  77931. get: function () {
  77932. return this.imageProcessingConfiguration.vignetteWeight;
  77933. },
  77934. /**
  77935. * Sets Vignette weight or intensity of the vignette effect.
  77936. */
  77937. set: function (value) {
  77938. this.imageProcessingConfiguration.vignetteWeight = value;
  77939. },
  77940. enumerable: true,
  77941. configurable: true
  77942. });
  77943. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77944. /**
  77945. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77946. * if vignetteEnabled is set to true.
  77947. */
  77948. get: function () {
  77949. return this.imageProcessingConfiguration.vignetteColor;
  77950. },
  77951. /**
  77952. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77953. * if vignetteEnabled is set to true.
  77954. */
  77955. set: function (value) {
  77956. this.imageProcessingConfiguration.vignetteColor = value;
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77962. /**
  77963. * Gets Camera field of view used by the Vignette effect.
  77964. */
  77965. get: function () {
  77966. return this.imageProcessingConfiguration.vignetteCameraFov;
  77967. },
  77968. /**
  77969. * Sets Camera field of view used by the Vignette effect.
  77970. */
  77971. set: function (value) {
  77972. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77973. },
  77974. enumerable: true,
  77975. configurable: true
  77976. });
  77977. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77978. /**
  77979. * Gets the vignette blend mode allowing different kind of effect.
  77980. */
  77981. get: function () {
  77982. return this.imageProcessingConfiguration.vignetteBlendMode;
  77983. },
  77984. /**
  77985. * Sets the vignette blend mode allowing different kind of effect.
  77986. */
  77987. set: function (value) {
  77988. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77989. },
  77990. enumerable: true,
  77991. configurable: true
  77992. });
  77993. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77994. /**
  77995. * Gets wether the vignette effect is enabled.
  77996. */
  77997. get: function () {
  77998. return this.imageProcessingConfiguration.vignetteEnabled;
  77999. },
  78000. /**
  78001. * Sets wether the vignette effect is enabled.
  78002. */
  78003. set: function (value) {
  78004. this.imageProcessingConfiguration.vignetteEnabled = value;
  78005. },
  78006. enumerable: true,
  78007. configurable: true
  78008. });
  78009. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78010. /**
  78011. * Gets wether the input of the processing is in Gamma or Linear Space.
  78012. */
  78013. get: function () {
  78014. return this._fromLinearSpace;
  78015. },
  78016. /**
  78017. * Sets wether the input of the processing is in Gamma or Linear Space.
  78018. */
  78019. set: function (value) {
  78020. if (this._fromLinearSpace === value) {
  78021. return;
  78022. }
  78023. this._fromLinearSpace = value;
  78024. this._updateParameters();
  78025. },
  78026. enumerable: true,
  78027. configurable: true
  78028. });
  78029. ImageProcessingPostProcess.prototype.getClassName = function () {
  78030. return "ImageProcessingPostProcess";
  78031. };
  78032. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78033. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78034. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78035. var defines = "";
  78036. for (var define in this._defines) {
  78037. if (this._defines[define]) {
  78038. defines += "#define " + define + ";\r\n";
  78039. }
  78040. }
  78041. var samplers = ["textureSampler"];
  78042. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78043. var uniforms = ["scale"];
  78044. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78045. this.updateEffect(defines, uniforms, samplers);
  78046. };
  78047. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78048. _super.prototype.dispose.call(this, camera);
  78049. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78050. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78051. }
  78052. this.imageProcessingConfiguration.applyByPostProcess = false;
  78053. };
  78054. __decorate([
  78055. BABYLON.serialize()
  78056. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78057. return ImageProcessingPostProcess;
  78058. }(BABYLON.PostProcess));
  78059. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78060. })(BABYLON || (BABYLON = {}));
  78061. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78062. var BABYLON;
  78063. (function (BABYLON) {
  78064. /**
  78065. * Class used to store bone information
  78066. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78067. */
  78068. var Bone = /** @class */ (function (_super) {
  78069. __extends(Bone, _super);
  78070. /**
  78071. * Create a new bone
  78072. * @param name defines the bone name
  78073. * @param skeleton defines the parent skeleton
  78074. * @param parentBone defines the parent (can be null if the bone is the root)
  78075. * @param localMatrix defines the local matrix
  78076. * @param restPose defines the rest pose matrix
  78077. * @param baseMatrix defines the base matrix
  78078. * @param index defines index of the bone in the hiearchy
  78079. */
  78080. function Bone(
  78081. /**
  78082. * defines the bone name
  78083. */
  78084. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  78085. if (parentBone === void 0) { parentBone = null; }
  78086. if (localMatrix === void 0) { localMatrix = null; }
  78087. if (restPose === void 0) { restPose = null; }
  78088. if (baseMatrix === void 0) { baseMatrix = null; }
  78089. if (index === void 0) { index = null; }
  78090. var _this = _super.call(this, name, skeleton.getScene()) || this;
  78091. _this.name = name;
  78092. /**
  78093. * Gets the list of child bones
  78094. */
  78095. _this.children = new Array();
  78096. /** Gets the animations associated with this bone */
  78097. _this.animations = new Array();
  78098. /**
  78099. * @hidden Internal only
  78100. * Set this value to map this bone to a different index in the transform matrices
  78101. * Set this value to -1 to exclude the bone from the transform matrices
  78102. */
  78103. _this._index = null;
  78104. _this._absoluteTransform = new BABYLON.Matrix();
  78105. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  78106. _this._scalingDeterminant = 1;
  78107. _this._worldTransform = new BABYLON.Matrix();
  78108. _this._needToDecompose = true;
  78109. _this._needToCompose = false;
  78110. _this._skeleton = skeleton;
  78111. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  78112. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  78113. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  78114. _this._index = index;
  78115. skeleton.bones.push(_this);
  78116. _this.setParent(parentBone, false);
  78117. if (baseMatrix || localMatrix) {
  78118. _this._updateDifferenceMatrix();
  78119. }
  78120. return _this;
  78121. }
  78122. Object.defineProperty(Bone.prototype, "_matrix", {
  78123. /** @hidden */
  78124. get: function () {
  78125. this._compose();
  78126. return this._localMatrix;
  78127. },
  78128. /** @hidden */
  78129. set: function (value) {
  78130. this._localMatrix.copyFrom(value);
  78131. this._needToDecompose = true;
  78132. },
  78133. enumerable: true,
  78134. configurable: true
  78135. });
  78136. // Members
  78137. /**
  78138. * Gets the parent skeleton
  78139. * @returns a skeleton
  78140. */
  78141. Bone.prototype.getSkeleton = function () {
  78142. return this._skeleton;
  78143. };
  78144. /**
  78145. * Gets parent bone
  78146. * @returns a bone or null if the bone is the root of the bone hierarchy
  78147. */
  78148. Bone.prototype.getParent = function () {
  78149. return this._parent;
  78150. };
  78151. /**
  78152. * Sets the parent bone
  78153. * @param parent defines the parent (can be null if the bone is the root)
  78154. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78155. */
  78156. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  78157. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78158. if (this._parent === parent) {
  78159. return;
  78160. }
  78161. if (this._parent) {
  78162. var index = this._parent.children.indexOf(this);
  78163. if (index !== -1) {
  78164. this._parent.children.splice(index, 1);
  78165. }
  78166. }
  78167. this._parent = parent;
  78168. if (this._parent) {
  78169. this._parent.children.push(this);
  78170. }
  78171. if (updateDifferenceMatrix) {
  78172. this._updateDifferenceMatrix();
  78173. }
  78174. this.markAsDirty();
  78175. };
  78176. /**
  78177. * Gets the local matrix
  78178. * @returns a matrix
  78179. */
  78180. Bone.prototype.getLocalMatrix = function () {
  78181. this._compose();
  78182. return this._localMatrix;
  78183. };
  78184. /**
  78185. * Gets the base matrix (initial matrix which remains unchanged)
  78186. * @returns a matrix
  78187. */
  78188. Bone.prototype.getBaseMatrix = function () {
  78189. return this._baseMatrix;
  78190. };
  78191. /**
  78192. * Gets the rest pose matrix
  78193. * @returns a matrix
  78194. */
  78195. Bone.prototype.getRestPose = function () {
  78196. return this._restPose;
  78197. };
  78198. /**
  78199. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  78200. */
  78201. Bone.prototype.getWorldMatrix = function () {
  78202. return this._worldTransform;
  78203. };
  78204. /**
  78205. * Sets the local matrix to rest pose matrix
  78206. */
  78207. Bone.prototype.returnToRest = function () {
  78208. this.updateMatrix(this._restPose.clone());
  78209. };
  78210. /**
  78211. * Gets the inverse of the absolute transform matrix.
  78212. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  78213. * @returns a matrix
  78214. */
  78215. Bone.prototype.getInvertedAbsoluteTransform = function () {
  78216. return this._invertedAbsoluteTransform;
  78217. };
  78218. /**
  78219. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  78220. * @returns a matrix
  78221. */
  78222. Bone.prototype.getAbsoluteTransform = function () {
  78223. return this._absoluteTransform;
  78224. };
  78225. Object.defineProperty(Bone.prototype, "position", {
  78226. // Properties (matches AbstractMesh properties)
  78227. /** Gets or sets current position (in local space) */
  78228. get: function () {
  78229. this._decompose();
  78230. return this._localPosition;
  78231. },
  78232. set: function (newPosition) {
  78233. this._decompose();
  78234. this._localPosition.copyFrom(newPosition);
  78235. this._markAsDirtyAndCompose();
  78236. },
  78237. enumerable: true,
  78238. configurable: true
  78239. });
  78240. Object.defineProperty(Bone.prototype, "rotation", {
  78241. /** Gets or sets current rotation (in local space) */
  78242. get: function () {
  78243. return this.getRotation();
  78244. },
  78245. set: function (newRotation) {
  78246. this.setRotation(newRotation);
  78247. },
  78248. enumerable: true,
  78249. configurable: true
  78250. });
  78251. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  78252. /** Gets or sets current rotation quaternion (in local space) */
  78253. get: function () {
  78254. this._decompose();
  78255. return this._localRotation;
  78256. },
  78257. set: function (newRotation) {
  78258. this.setRotationQuaternion(newRotation);
  78259. },
  78260. enumerable: true,
  78261. configurable: true
  78262. });
  78263. Object.defineProperty(Bone.prototype, "scaling", {
  78264. /** Gets or sets current scaling (in local space) */
  78265. get: function () {
  78266. return this.getScale();
  78267. },
  78268. set: function (newScaling) {
  78269. this.setScale(newScaling);
  78270. },
  78271. enumerable: true,
  78272. configurable: true
  78273. });
  78274. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  78275. /**
  78276. * Gets the animation properties override
  78277. */
  78278. get: function () {
  78279. return this._skeleton.animationPropertiesOverride;
  78280. },
  78281. enumerable: true,
  78282. configurable: true
  78283. });
  78284. // Methods
  78285. Bone.prototype._decompose = function () {
  78286. if (!this._needToDecompose) {
  78287. return;
  78288. }
  78289. this._needToDecompose = false;
  78290. if (!this._localScaling) {
  78291. this._localScaling = BABYLON.Vector3.Zero();
  78292. this._localRotation = BABYLON.Quaternion.Zero();
  78293. this._localPosition = BABYLON.Vector3.Zero();
  78294. }
  78295. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  78296. };
  78297. Bone.prototype._compose = function () {
  78298. if (!this._needToCompose) {
  78299. return;
  78300. }
  78301. this._needToCompose = false;
  78302. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  78303. };
  78304. /**
  78305. * Update the base and local matrices
  78306. * @param matrix defines the new base or local matrix
  78307. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  78308. * @param updateLocalMatrix defines if the local matrix should be updated
  78309. */
  78310. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  78311. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  78312. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  78313. this._baseMatrix.copyFrom(matrix);
  78314. if (updateDifferenceMatrix) {
  78315. this._updateDifferenceMatrix();
  78316. }
  78317. if (updateLocalMatrix) {
  78318. this._localMatrix.copyFrom(matrix);
  78319. this._markAsDirtyAndDecompose();
  78320. }
  78321. else {
  78322. this.markAsDirty();
  78323. }
  78324. };
  78325. /** @hidden */
  78326. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  78327. if (updateChildren === void 0) { updateChildren = true; }
  78328. if (!rootMatrix) {
  78329. rootMatrix = this._baseMatrix;
  78330. }
  78331. if (this._parent) {
  78332. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78333. }
  78334. else {
  78335. this._absoluteTransform.copyFrom(rootMatrix);
  78336. }
  78337. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  78338. if (updateChildren) {
  78339. for (var index = 0; index < this.children.length; index++) {
  78340. this.children[index]._updateDifferenceMatrix();
  78341. }
  78342. }
  78343. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  78344. };
  78345. /**
  78346. * Flag the bone as dirty (Forcing it to update everything)
  78347. */
  78348. Bone.prototype.markAsDirty = function () {
  78349. this._currentRenderId++;
  78350. this._childRenderId++;
  78351. this._skeleton._markAsDirty();
  78352. };
  78353. Bone.prototype._markAsDirtyAndCompose = function () {
  78354. this.markAsDirty();
  78355. this._needToCompose = true;
  78356. };
  78357. Bone.prototype._markAsDirtyAndDecompose = function () {
  78358. this.markAsDirty();
  78359. this._needToDecompose = true;
  78360. };
  78361. /**
  78362. * Copy an animation range from another bone
  78363. * @param source defines the source bone
  78364. * @param rangeName defines the range name to copy
  78365. * @param frameOffset defines the frame offset
  78366. * @param rescaleAsRequired defines if rescaling must be applied if required
  78367. * @param skelDimensionsRatio defines the scaling ratio
  78368. * @returns true if operation was successful
  78369. */
  78370. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  78371. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78372. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  78373. // all animation may be coming from a library skeleton, so may need to create animation
  78374. if (this.animations.length === 0) {
  78375. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  78376. this.animations[0].setKeys([]);
  78377. }
  78378. // get animation info / verify there is such a range from the source bone
  78379. var sourceRange = source.animations[0].getRange(rangeName);
  78380. if (!sourceRange) {
  78381. return false;
  78382. }
  78383. var from = sourceRange.from;
  78384. var to = sourceRange.to;
  78385. var sourceKeys = source.animations[0].getKeys();
  78386. // rescaling prep
  78387. var sourceBoneLength = source.length;
  78388. var sourceParent = source.getParent();
  78389. var parent = this.getParent();
  78390. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  78391. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  78392. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  78393. var destKeys = this.animations[0].getKeys();
  78394. // loop vars declaration
  78395. var orig;
  78396. var origTranslation;
  78397. var mat;
  78398. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  78399. orig = sourceKeys[key];
  78400. if (orig.frame >= from && orig.frame <= to) {
  78401. if (rescaleAsRequired) {
  78402. mat = orig.value.clone();
  78403. // scale based on parent ratio, when bone has parent
  78404. if (parentScalingReqd) {
  78405. origTranslation = mat.getTranslation();
  78406. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  78407. // scale based on skeleton dimension ratio when root bone, and value is passed
  78408. }
  78409. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  78410. origTranslation = mat.getTranslation();
  78411. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  78412. // use original when root bone, and no data for skelDimensionsRatio
  78413. }
  78414. else {
  78415. mat = orig.value;
  78416. }
  78417. }
  78418. else {
  78419. mat = orig.value;
  78420. }
  78421. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  78422. }
  78423. }
  78424. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  78425. return true;
  78426. };
  78427. /**
  78428. * Translate the bone in local or world space
  78429. * @param vec The amount to translate the bone
  78430. * @param space The space that the translation is in
  78431. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78432. */
  78433. Bone.prototype.translate = function (vec, space, mesh) {
  78434. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78435. var lm = this.getLocalMatrix();
  78436. if (space == BABYLON.Space.LOCAL) {
  78437. lm.m[12] += vec.x;
  78438. lm.m[13] += vec.y;
  78439. lm.m[14] += vec.z;
  78440. }
  78441. else {
  78442. var wm = null;
  78443. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78444. if (mesh) {
  78445. wm = mesh.getWorldMatrix();
  78446. }
  78447. this._skeleton.computeAbsoluteTransforms();
  78448. var tmat = Bone._tmpMats[0];
  78449. var tvec = Bone._tmpVecs[0];
  78450. if (this._parent) {
  78451. if (mesh && wm) {
  78452. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78453. tmat.multiplyToRef(wm, tmat);
  78454. }
  78455. else {
  78456. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78457. }
  78458. }
  78459. tmat.m[12] = 0;
  78460. tmat.m[13] = 0;
  78461. tmat.m[14] = 0;
  78462. tmat.invert();
  78463. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  78464. lm.m[12] += tvec.x;
  78465. lm.m[13] += tvec.y;
  78466. lm.m[14] += tvec.z;
  78467. }
  78468. this._markAsDirtyAndDecompose();
  78469. };
  78470. /**
  78471. * Set the postion of the bone in local or world space
  78472. * @param position The position to set the bone
  78473. * @param space The space that the position is in
  78474. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78475. */
  78476. Bone.prototype.setPosition = function (position, space, mesh) {
  78477. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78478. var lm = this.getLocalMatrix();
  78479. if (space == BABYLON.Space.LOCAL) {
  78480. lm.m[12] = position.x;
  78481. lm.m[13] = position.y;
  78482. lm.m[14] = position.z;
  78483. }
  78484. else {
  78485. var wm = null;
  78486. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78487. if (mesh) {
  78488. wm = mesh.getWorldMatrix();
  78489. }
  78490. this._skeleton.computeAbsoluteTransforms();
  78491. var tmat = Bone._tmpMats[0];
  78492. var vec = Bone._tmpVecs[0];
  78493. if (this._parent) {
  78494. if (mesh && wm) {
  78495. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78496. tmat.multiplyToRef(wm, tmat);
  78497. }
  78498. else {
  78499. tmat.copyFrom(this._parent.getAbsoluteTransform());
  78500. }
  78501. }
  78502. tmat.invert();
  78503. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  78504. lm.m[12] = vec.x;
  78505. lm.m[13] = vec.y;
  78506. lm.m[14] = vec.z;
  78507. }
  78508. this._markAsDirtyAndDecompose();
  78509. };
  78510. /**
  78511. * Set the absolute position of the bone (world space)
  78512. * @param position The position to set the bone
  78513. * @param mesh The mesh that this bone is attached to
  78514. */
  78515. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  78516. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  78517. };
  78518. /**
  78519. * Scale the bone on the x, y and z axes (in local space)
  78520. * @param x The amount to scale the bone on the x axis
  78521. * @param y The amount to scale the bone on the y axis
  78522. * @param z The amount to scale the bone on the z axis
  78523. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  78524. */
  78525. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  78526. if (scaleChildren === void 0) { scaleChildren = false; }
  78527. var locMat = this.getLocalMatrix();
  78528. // Apply new scaling on top of current local matrix
  78529. var scaleMat = Bone._tmpMats[0];
  78530. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  78531. scaleMat.multiplyToRef(locMat, locMat);
  78532. // Invert scaling matrix and apply the inverse to all children
  78533. scaleMat.invert();
  78534. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  78535. var child = _a[_i];
  78536. var cm = child.getLocalMatrix();
  78537. cm.multiplyToRef(scaleMat, cm);
  78538. cm.m[12] *= x;
  78539. cm.m[13] *= y;
  78540. cm.m[14] *= z;
  78541. child._markAsDirtyAndDecompose();
  78542. }
  78543. this._markAsDirtyAndDecompose();
  78544. if (scaleChildren) {
  78545. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78546. var child = _c[_b];
  78547. child.scale(x, y, z, scaleChildren);
  78548. }
  78549. }
  78550. };
  78551. /**
  78552. * Set the bone scaling in local space
  78553. * @param scale defines the scaling vector
  78554. */
  78555. Bone.prototype.setScale = function (scale) {
  78556. this._decompose();
  78557. this._localScaling.copyFrom(scale);
  78558. this._markAsDirtyAndCompose();
  78559. };
  78560. /**
  78561. * Gets the current scaling in local space
  78562. * @returns the current scaling vector
  78563. */
  78564. Bone.prototype.getScale = function () {
  78565. this._decompose();
  78566. return this._localScaling;
  78567. };
  78568. /**
  78569. * Gets the current scaling in local space and stores it in a target vector
  78570. * @param result defines the target vector
  78571. */
  78572. Bone.prototype.getScaleToRef = function (result) {
  78573. this._decompose();
  78574. result.copyFrom(this._localScaling);
  78575. };
  78576. /**
  78577. * Set the yaw, pitch, and roll of the bone in local or world space
  78578. * @param yaw The rotation of the bone on the y axis
  78579. * @param pitch The rotation of the bone on the x axis
  78580. * @param roll The rotation of the bone on the z axis
  78581. * @param space The space that the axes of rotation are in
  78582. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78583. */
  78584. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78586. if (space === BABYLON.Space.LOCAL) {
  78587. var quat = Bone._tmpQuat;
  78588. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78589. this.setRotationQuaternion(quat, space, mesh);
  78590. return;
  78591. }
  78592. var rotMatInv = Bone._tmpMats[0];
  78593. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78594. return;
  78595. }
  78596. var rotMat = Bone._tmpMats[1];
  78597. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78598. rotMatInv.multiplyToRef(rotMat, rotMat);
  78599. this._rotateWithMatrix(rotMat, space, mesh);
  78600. };
  78601. /**
  78602. * Add a rotation to the bone on an axis in local or world space
  78603. * @param axis The axis to rotate the bone on
  78604. * @param amount The amount to rotate the bone
  78605. * @param space The space that the axis is in
  78606. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78607. */
  78608. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78610. var rmat = Bone._tmpMats[0];
  78611. rmat.m[12] = 0;
  78612. rmat.m[13] = 0;
  78613. rmat.m[14] = 0;
  78614. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78615. this._rotateWithMatrix(rmat, space, mesh);
  78616. };
  78617. /**
  78618. * Set the rotation of the bone to a particular axis angle in local or world space
  78619. * @param axis The axis to rotate the bone on
  78620. * @param angle The angle that the bone should be rotated to
  78621. * @param space The space that the axis is in
  78622. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78623. */
  78624. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78625. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78626. if (space === BABYLON.Space.LOCAL) {
  78627. var quat = Bone._tmpQuat;
  78628. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78629. this.setRotationQuaternion(quat, space, mesh);
  78630. return;
  78631. }
  78632. var rotMatInv = Bone._tmpMats[0];
  78633. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78634. return;
  78635. }
  78636. var rotMat = Bone._tmpMats[1];
  78637. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78638. rotMatInv.multiplyToRef(rotMat, rotMat);
  78639. this._rotateWithMatrix(rotMat, space, mesh);
  78640. };
  78641. /**
  78642. * Set the euler rotation of the bone in local of world space
  78643. * @param rotation The euler rotation that the bone should be set to
  78644. * @param space The space that the rotation is in
  78645. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78646. */
  78647. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78649. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78650. };
  78651. /**
  78652. * Set the quaternion rotation of the bone in local of world space
  78653. * @param quat The quaternion rotation that the bone should be set to
  78654. * @param space The space that the rotation is in
  78655. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78656. */
  78657. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78658. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78659. if (space === BABYLON.Space.LOCAL) {
  78660. this._decompose();
  78661. this._localRotation.copyFrom(quat);
  78662. this._markAsDirtyAndCompose();
  78663. return;
  78664. }
  78665. var rotMatInv = Bone._tmpMats[0];
  78666. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78667. return;
  78668. }
  78669. var rotMat = Bone._tmpMats[1];
  78670. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78671. rotMatInv.multiplyToRef(rotMat, rotMat);
  78672. this._rotateWithMatrix(rotMat, space, mesh);
  78673. };
  78674. /**
  78675. * Set the rotation matrix of the bone in local of world space
  78676. * @param rotMat The rotation matrix that the bone should be set to
  78677. * @param space The space that the rotation is in
  78678. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78679. */
  78680. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78682. if (space === BABYLON.Space.LOCAL) {
  78683. var quat = Bone._tmpQuat;
  78684. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78685. this.setRotationQuaternion(quat, space, mesh);
  78686. return;
  78687. }
  78688. var rotMatInv = Bone._tmpMats[0];
  78689. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78690. return;
  78691. }
  78692. var rotMat2 = Bone._tmpMats[1];
  78693. rotMat2.copyFrom(rotMat);
  78694. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78695. this._rotateWithMatrix(rotMat2, space, mesh);
  78696. };
  78697. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78699. var lmat = this.getLocalMatrix();
  78700. var lx = lmat.m[12];
  78701. var ly = lmat.m[13];
  78702. var lz = lmat.m[14];
  78703. var parent = this.getParent();
  78704. var parentScale = Bone._tmpMats[3];
  78705. var parentScaleInv = Bone._tmpMats[4];
  78706. if (parent && space == BABYLON.Space.WORLD) {
  78707. if (mesh) {
  78708. parentScale.copyFrom(mesh.getWorldMatrix());
  78709. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78710. }
  78711. else {
  78712. parentScale.copyFrom(parent.getAbsoluteTransform());
  78713. }
  78714. parentScaleInv.copyFrom(parentScale);
  78715. parentScaleInv.invert();
  78716. lmat.multiplyToRef(parentScale, lmat);
  78717. lmat.multiplyToRef(rmat, lmat);
  78718. lmat.multiplyToRef(parentScaleInv, lmat);
  78719. }
  78720. else {
  78721. if (space == BABYLON.Space.WORLD && mesh) {
  78722. parentScale.copyFrom(mesh.getWorldMatrix());
  78723. parentScaleInv.copyFrom(parentScale);
  78724. parentScaleInv.invert();
  78725. lmat.multiplyToRef(parentScale, lmat);
  78726. lmat.multiplyToRef(rmat, lmat);
  78727. lmat.multiplyToRef(parentScaleInv, lmat);
  78728. }
  78729. else {
  78730. lmat.multiplyToRef(rmat, lmat);
  78731. }
  78732. }
  78733. lmat.m[12] = lx;
  78734. lmat.m[13] = ly;
  78735. lmat.m[14] = lz;
  78736. this.computeAbsoluteTransforms();
  78737. this._markAsDirtyAndDecompose();
  78738. };
  78739. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78740. var scaleMatrix = Bone._tmpMats[2];
  78741. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78742. if (mesh) {
  78743. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78744. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78745. }
  78746. rotMatInv.invert();
  78747. if (isNaN(rotMatInv.m[0])) {
  78748. // Matrix failed to invert.
  78749. // This can happen if scale is zero for example.
  78750. return false;
  78751. }
  78752. scaleMatrix.m[0] *= this._scalingDeterminant;
  78753. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78754. return true;
  78755. };
  78756. /**
  78757. * Get the position of the bone in local or world space
  78758. * @param space The space that the returned position is in
  78759. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78760. * @returns The position of the bone
  78761. */
  78762. Bone.prototype.getPosition = function (space, mesh) {
  78763. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78764. if (mesh === void 0) { mesh = null; }
  78765. var pos = BABYLON.Vector3.Zero();
  78766. this.getPositionToRef(space, mesh, pos);
  78767. return pos;
  78768. };
  78769. /**
  78770. * Copy the position of the bone to a vector3 in local or world space
  78771. * @param space The space that the returned position is in
  78772. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78773. * @param result The vector3 to copy the position to
  78774. */
  78775. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78776. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78777. if (space == BABYLON.Space.LOCAL) {
  78778. var lm = this.getLocalMatrix();
  78779. result.x = lm.m[12];
  78780. result.y = lm.m[13];
  78781. result.z = lm.m[14];
  78782. }
  78783. else {
  78784. var wm = null;
  78785. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78786. if (mesh) {
  78787. wm = mesh.getWorldMatrix();
  78788. }
  78789. this._skeleton.computeAbsoluteTransforms();
  78790. var tmat = Bone._tmpMats[0];
  78791. if (mesh && wm) {
  78792. tmat.copyFrom(this.getAbsoluteTransform());
  78793. tmat.multiplyToRef(wm, tmat);
  78794. }
  78795. else {
  78796. tmat = this.getAbsoluteTransform();
  78797. }
  78798. result.x = tmat.m[12];
  78799. result.y = tmat.m[13];
  78800. result.z = tmat.m[14];
  78801. }
  78802. };
  78803. /**
  78804. * Get the absolute position of the bone (world space)
  78805. * @param mesh The mesh that this bone is attached to
  78806. * @returns The absolute position of the bone
  78807. */
  78808. Bone.prototype.getAbsolutePosition = function (mesh) {
  78809. if (mesh === void 0) { mesh = null; }
  78810. var pos = BABYLON.Vector3.Zero();
  78811. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78812. return pos;
  78813. };
  78814. /**
  78815. * Copy the absolute position of the bone (world space) to the result param
  78816. * @param mesh The mesh that this bone is attached to
  78817. * @param result The vector3 to copy the absolute position to
  78818. */
  78819. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78820. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78821. };
  78822. /**
  78823. * Compute the absolute transforms of this bone and its children
  78824. */
  78825. Bone.prototype.computeAbsoluteTransforms = function () {
  78826. this._compose();
  78827. if (this._parent) {
  78828. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78829. }
  78830. else {
  78831. this._absoluteTransform.copyFrom(this._localMatrix);
  78832. var poseMatrix = this._skeleton.getPoseMatrix();
  78833. if (poseMatrix) {
  78834. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78835. }
  78836. }
  78837. var children = this.children;
  78838. var len = children.length;
  78839. for (var i = 0; i < len; i++) {
  78840. children[i].computeAbsoluteTransforms();
  78841. }
  78842. };
  78843. /**
  78844. * Get the world direction from an axis that is in the local space of the bone
  78845. * @param localAxis The local direction that is used to compute the world direction
  78846. * @param mesh The mesh that this bone is attached to
  78847. * @returns The world direction
  78848. */
  78849. Bone.prototype.getDirection = function (localAxis, mesh) {
  78850. if (mesh === void 0) { mesh = null; }
  78851. var result = BABYLON.Vector3.Zero();
  78852. this.getDirectionToRef(localAxis, mesh, result);
  78853. return result;
  78854. };
  78855. /**
  78856. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78857. * @param localAxis The local direction that is used to compute the world direction
  78858. * @param mesh The mesh that this bone is attached to
  78859. * @param result The vector3 that the world direction will be copied to
  78860. */
  78861. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78862. if (mesh === void 0) { mesh = null; }
  78863. var wm = null;
  78864. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78865. if (mesh) {
  78866. wm = mesh.getWorldMatrix();
  78867. }
  78868. this._skeleton.computeAbsoluteTransforms();
  78869. var mat = Bone._tmpMats[0];
  78870. mat.copyFrom(this.getAbsoluteTransform());
  78871. if (mesh && wm) {
  78872. mat.multiplyToRef(wm, mat);
  78873. }
  78874. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78875. result.normalize();
  78876. };
  78877. /**
  78878. * Get the euler rotation of the bone in local or world space
  78879. * @param space The space that the rotation should be in
  78880. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78881. * @returns The euler rotation
  78882. */
  78883. Bone.prototype.getRotation = function (space, mesh) {
  78884. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78885. if (mesh === void 0) { mesh = null; }
  78886. var result = BABYLON.Vector3.Zero();
  78887. this.getRotationToRef(space, mesh, result);
  78888. return result;
  78889. };
  78890. /**
  78891. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78892. * @param space The space that the rotation should be in
  78893. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78894. * @param result The vector3 that the rotation should be copied to
  78895. */
  78896. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78897. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78898. if (mesh === void 0) { mesh = null; }
  78899. var quat = Bone._tmpQuat;
  78900. this.getRotationQuaternionToRef(space, mesh, quat);
  78901. quat.toEulerAnglesToRef(result);
  78902. };
  78903. /**
  78904. * Get the quaternion rotation of the bone in either local or world space
  78905. * @param space The space that the rotation should be in
  78906. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78907. * @returns The quaternion rotation
  78908. */
  78909. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78911. if (mesh === void 0) { mesh = null; }
  78912. var result = BABYLON.Quaternion.Identity();
  78913. this.getRotationQuaternionToRef(space, mesh, result);
  78914. return result;
  78915. };
  78916. /**
  78917. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78918. * @param space The space that the rotation should be in
  78919. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78920. * @param result The quaternion that the rotation should be copied to
  78921. */
  78922. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78923. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78924. if (mesh === void 0) { mesh = null; }
  78925. if (space == BABYLON.Space.LOCAL) {
  78926. this._decompose();
  78927. result.copyFrom(this._localRotation);
  78928. }
  78929. else {
  78930. var mat = Bone._tmpMats[0];
  78931. var amat = this.getAbsoluteTransform();
  78932. if (mesh) {
  78933. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78934. }
  78935. else {
  78936. mat.copyFrom(amat);
  78937. }
  78938. mat.m[0] *= this._scalingDeterminant;
  78939. mat.m[1] *= this._scalingDeterminant;
  78940. mat.m[2] *= this._scalingDeterminant;
  78941. mat.decompose(undefined, result, undefined);
  78942. }
  78943. };
  78944. /**
  78945. * Get the rotation matrix of the bone in local or world space
  78946. * @param space The space that the rotation should be in
  78947. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78948. * @returns The rotation matrix
  78949. */
  78950. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78951. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78952. var result = BABYLON.Matrix.Identity();
  78953. this.getRotationMatrixToRef(space, mesh, result);
  78954. return result;
  78955. };
  78956. /**
  78957. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78958. * @param space The space that the rotation should be in
  78959. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78960. * @param result The quaternion that the rotation should be copied to
  78961. */
  78962. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78963. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78964. if (space == BABYLON.Space.LOCAL) {
  78965. this.getLocalMatrix().getRotationMatrixToRef(result);
  78966. }
  78967. else {
  78968. var mat = Bone._tmpMats[0];
  78969. var amat = this.getAbsoluteTransform();
  78970. if (mesh) {
  78971. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78972. }
  78973. else {
  78974. mat.copyFrom(amat);
  78975. }
  78976. mat.m[0] *= this._scalingDeterminant;
  78977. mat.m[1] *= this._scalingDeterminant;
  78978. mat.m[2] *= this._scalingDeterminant;
  78979. mat.getRotationMatrixToRef(result);
  78980. }
  78981. };
  78982. /**
  78983. * Get the world position of a point that is in the local space of the bone
  78984. * @param position The local position
  78985. * @param mesh The mesh that this bone is attached to
  78986. * @returns The world position
  78987. */
  78988. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78989. if (mesh === void 0) { mesh = null; }
  78990. var result = BABYLON.Vector3.Zero();
  78991. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78992. return result;
  78993. };
  78994. /**
  78995. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78996. * @param position The local position
  78997. * @param mesh The mesh that this bone is attached to
  78998. * @param result The vector3 that the world position should be copied to
  78999. */
  79000. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79001. if (mesh === void 0) { mesh = null; }
  79002. var wm = null;
  79003. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79004. if (mesh) {
  79005. wm = mesh.getWorldMatrix();
  79006. }
  79007. this._skeleton.computeAbsoluteTransforms();
  79008. var tmat = Bone._tmpMats[0];
  79009. if (mesh && wm) {
  79010. tmat.copyFrom(this.getAbsoluteTransform());
  79011. tmat.multiplyToRef(wm, tmat);
  79012. }
  79013. else {
  79014. tmat = this.getAbsoluteTransform();
  79015. }
  79016. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79017. };
  79018. /**
  79019. * Get the local position of a point that is in world space
  79020. * @param position The world position
  79021. * @param mesh The mesh that this bone is attached to
  79022. * @returns The local position
  79023. */
  79024. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79025. if (mesh === void 0) { mesh = null; }
  79026. var result = BABYLON.Vector3.Zero();
  79027. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79028. return result;
  79029. };
  79030. /**
  79031. * Get the local position of a point that is in world space and copy it to the result param
  79032. * @param position The world position
  79033. * @param mesh The mesh that this bone is attached to
  79034. * @param result The vector3 that the local position should be copied to
  79035. */
  79036. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79037. if (mesh === void 0) { mesh = null; }
  79038. var wm = null;
  79039. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79040. if (mesh) {
  79041. wm = mesh.getWorldMatrix();
  79042. }
  79043. this._skeleton.computeAbsoluteTransforms();
  79044. var tmat = Bone._tmpMats[0];
  79045. tmat.copyFrom(this.getAbsoluteTransform());
  79046. if (mesh && wm) {
  79047. tmat.multiplyToRef(wm, tmat);
  79048. }
  79049. tmat.invert();
  79050. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79051. };
  79052. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79053. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79054. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79055. return Bone;
  79056. }(BABYLON.Node));
  79057. BABYLON.Bone = Bone;
  79058. })(BABYLON || (BABYLON = {}));
  79059. //# sourceMappingURL=babylon.bone.js.map
  79060. var BABYLON;
  79061. (function (BABYLON) {
  79062. /**
  79063. * Class used to apply inverse kinematics to bones
  79064. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79065. */
  79066. var BoneIKController = /** @class */ (function () {
  79067. /**
  79068. * Creates a new BoneIKController
  79069. * @param mesh defines the mesh to control
  79070. * @param bone defines the bone to control
  79071. * @param options defines options to set up the controller
  79072. */
  79073. function BoneIKController(mesh, bone, options) {
  79074. /**
  79075. * Gets or sets the target position
  79076. */
  79077. this.targetPosition = BABYLON.Vector3.Zero();
  79078. /**
  79079. * Gets or sets the pole target position
  79080. */
  79081. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79082. /**
  79083. * Gets or sets the pole target local offset
  79084. */
  79085. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  79086. /**
  79087. * Gets or sets the pole angle
  79088. */
  79089. this.poleAngle = 0;
  79090. /**
  79091. * 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)
  79092. */
  79093. this.slerpAmount = 1;
  79094. this._bone1Quat = BABYLON.Quaternion.Identity();
  79095. this._bone1Mat = BABYLON.Matrix.Identity();
  79096. this._bone2Ang = Math.PI;
  79097. this._maxAngle = Math.PI;
  79098. this._rightHandedSystem = false;
  79099. this._bendAxis = BABYLON.Vector3.Right();
  79100. this._slerping = false;
  79101. this._adjustRoll = 0;
  79102. this._bone2 = bone;
  79103. this._bone1 = bone.getParent();
  79104. if (!this._bone1) {
  79105. return;
  79106. }
  79107. this.mesh = mesh;
  79108. var bonePos = bone.getPosition();
  79109. if (bone.getAbsoluteTransform().determinant() > 0) {
  79110. this._rightHandedSystem = true;
  79111. this._bendAxis.x = 0;
  79112. this._bendAxis.y = 0;
  79113. this._bendAxis.z = -1;
  79114. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  79115. this._adjustRoll = Math.PI * .5;
  79116. this._bendAxis.z = 1;
  79117. }
  79118. }
  79119. if (this._bone1.length) {
  79120. var boneScale1 = this._bone1.getScale();
  79121. var boneScale2 = this._bone2.getScale();
  79122. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  79123. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  79124. }
  79125. else if (this._bone1.children[0]) {
  79126. mesh.computeWorldMatrix(true);
  79127. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  79128. var pos2 = this._bone2.getAbsolutePosition(mesh);
  79129. var pos3 = this._bone1.getAbsolutePosition(mesh);
  79130. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  79131. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  79132. }
  79133. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  79134. this.maxAngle = Math.PI;
  79135. if (options) {
  79136. if (options.targetMesh) {
  79137. this.targetMesh = options.targetMesh;
  79138. this.targetMesh.computeWorldMatrix(true);
  79139. }
  79140. if (options.poleTargetMesh) {
  79141. this.poleTargetMesh = options.poleTargetMesh;
  79142. this.poleTargetMesh.computeWorldMatrix(true);
  79143. }
  79144. else if (options.poleTargetBone) {
  79145. this.poleTargetBone = options.poleTargetBone;
  79146. }
  79147. else if (this._bone1.getParent()) {
  79148. this.poleTargetBone = this._bone1.getParent();
  79149. }
  79150. if (options.poleTargetLocalOffset) {
  79151. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  79152. }
  79153. if (options.poleAngle) {
  79154. this.poleAngle = options.poleAngle;
  79155. }
  79156. if (options.bendAxis) {
  79157. this._bendAxis.copyFrom(options.bendAxis);
  79158. }
  79159. if (options.maxAngle) {
  79160. this.maxAngle = options.maxAngle;
  79161. }
  79162. if (options.slerpAmount) {
  79163. this.slerpAmount = options.slerpAmount;
  79164. }
  79165. }
  79166. }
  79167. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  79168. /**
  79169. * Gets or sets maximum allowed angle
  79170. */
  79171. get: function () {
  79172. return this._maxAngle;
  79173. },
  79174. set: function (value) {
  79175. this._setMaxAngle(value);
  79176. },
  79177. enumerable: true,
  79178. configurable: true
  79179. });
  79180. BoneIKController.prototype._setMaxAngle = function (ang) {
  79181. if (ang < 0) {
  79182. ang = 0;
  79183. }
  79184. if (ang > Math.PI || ang == undefined) {
  79185. ang = Math.PI;
  79186. }
  79187. this._maxAngle = ang;
  79188. var a = this._bone1Length;
  79189. var b = this._bone2Length;
  79190. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  79191. };
  79192. /**
  79193. * Force the controller to update the bones
  79194. */
  79195. BoneIKController.prototype.update = function () {
  79196. var bone1 = this._bone1;
  79197. if (!bone1) {
  79198. return;
  79199. }
  79200. var target = this.targetPosition;
  79201. var poleTarget = this.poleTargetPosition;
  79202. var mat1 = BoneIKController._tmpMats[0];
  79203. var mat2 = BoneIKController._tmpMats[1];
  79204. if (this.targetMesh) {
  79205. target.copyFrom(this.targetMesh.getAbsolutePosition());
  79206. }
  79207. if (this.poleTargetBone) {
  79208. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  79209. }
  79210. else if (this.poleTargetMesh) {
  79211. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  79212. }
  79213. var bonePos = BoneIKController._tmpVecs[0];
  79214. var zaxis = BoneIKController._tmpVecs[1];
  79215. var xaxis = BoneIKController._tmpVecs[2];
  79216. var yaxis = BoneIKController._tmpVecs[3];
  79217. var upAxis = BoneIKController._tmpVecs[4];
  79218. var _tmpQuat = BoneIKController._tmpQuat;
  79219. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  79220. poleTarget.subtractToRef(bonePos, upAxis);
  79221. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  79222. upAxis.y = 1;
  79223. }
  79224. else {
  79225. upAxis.normalize();
  79226. }
  79227. target.subtractToRef(bonePos, yaxis);
  79228. yaxis.normalize();
  79229. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  79230. zaxis.normalize();
  79231. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  79232. xaxis.normalize();
  79233. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  79234. var a = this._bone1Length;
  79235. var b = this._bone2Length;
  79236. var c = BABYLON.Vector3.Distance(bonePos, target);
  79237. if (this._maxReach > 0) {
  79238. c = Math.min(this._maxReach, c);
  79239. }
  79240. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  79241. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  79242. if (acosa > 1) {
  79243. acosa = 1;
  79244. }
  79245. if (acosb > 1) {
  79246. acosb = 1;
  79247. }
  79248. if (acosa < -1) {
  79249. acosa = -1;
  79250. }
  79251. if (acosb < -1) {
  79252. acosb = -1;
  79253. }
  79254. var angA = Math.acos(acosa);
  79255. var angB = Math.acos(acosb);
  79256. var angC = -angA - angB;
  79257. if (this._rightHandedSystem) {
  79258. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  79259. mat2.multiplyToRef(mat1, mat1);
  79260. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  79261. mat2.multiplyToRef(mat1, mat1);
  79262. }
  79263. else {
  79264. var _tmpVec = BoneIKController._tmpVecs[5];
  79265. _tmpVec.copyFrom(this._bendAxis);
  79266. _tmpVec.x *= -1;
  79267. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  79268. mat2.multiplyToRef(mat1, mat1);
  79269. }
  79270. if (this.poleAngle) {
  79271. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  79272. mat1.multiplyToRef(mat2, mat1);
  79273. }
  79274. if (this._bone1) {
  79275. if (this.slerpAmount < 1) {
  79276. if (!this._slerping) {
  79277. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  79278. }
  79279. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  79280. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  79281. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  79282. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  79283. this._slerping = true;
  79284. }
  79285. else {
  79286. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  79287. this._bone1Mat.copyFrom(mat1);
  79288. this._slerping = false;
  79289. }
  79290. }
  79291. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  79292. this._bone2Ang = angC;
  79293. };
  79294. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79295. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  79296. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79297. return BoneIKController;
  79298. }());
  79299. BABYLON.BoneIKController = BoneIKController;
  79300. })(BABYLON || (BABYLON = {}));
  79301. //# sourceMappingURL=babylon.boneIKController.js.map
  79302. var BABYLON;
  79303. (function (BABYLON) {
  79304. /**
  79305. * Class used to make a bone look toward a point in space
  79306. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  79307. */
  79308. var BoneLookController = /** @class */ (function () {
  79309. /**
  79310. * Create a BoneLookController
  79311. * @param mesh the mesh that the bone belongs to
  79312. * @param bone the bone that will be looking to the target
  79313. * @param target the target Vector3 to look at
  79314. * @param settings optional settings:
  79315. * * maxYaw: the maximum angle the bone will yaw to
  79316. * * minYaw: the minimum angle the bone will yaw to
  79317. * * maxPitch: the maximum angle the bone will pitch to
  79318. * * minPitch: the minimum angle the bone will yaw to
  79319. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  79320. * * upAxis: the up axis of the coordinate system
  79321. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  79322. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  79323. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  79324. * * adjustYaw: used to make an adjustment to the yaw of the bone
  79325. * * adjustPitch: used to make an adjustment to the pitch of the bone
  79326. * * adjustRoll: used to make an adjustment to the roll of the bone
  79327. **/
  79328. function BoneLookController(mesh, bone, target, options) {
  79329. /**
  79330. * The up axis of the coordinate system that is used when the bone is rotated
  79331. */
  79332. this.upAxis = BABYLON.Vector3.Up();
  79333. /**
  79334. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  79335. */
  79336. this.upAxisSpace = BABYLON.Space.LOCAL;
  79337. /**
  79338. * Used to make an adjustment to the yaw of the bone
  79339. */
  79340. this.adjustYaw = 0;
  79341. /**
  79342. * Used to make an adjustment to the pitch of the bone
  79343. */
  79344. this.adjustPitch = 0;
  79345. /**
  79346. * Used to make an adjustment to the roll of the bone
  79347. */
  79348. this.adjustRoll = 0;
  79349. /**
  79350. * 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)
  79351. */
  79352. this.slerpAmount = 1;
  79353. this._boneQuat = BABYLON.Quaternion.Identity();
  79354. this._slerping = false;
  79355. this._firstFrameSkipped = false;
  79356. this._fowardAxis = BABYLON.Vector3.Forward();
  79357. this.mesh = mesh;
  79358. this.bone = bone;
  79359. this.target = target;
  79360. if (options) {
  79361. if (options.adjustYaw) {
  79362. this.adjustYaw = options.adjustYaw;
  79363. }
  79364. if (options.adjustPitch) {
  79365. this.adjustPitch = options.adjustPitch;
  79366. }
  79367. if (options.adjustRoll) {
  79368. this.adjustRoll = options.adjustRoll;
  79369. }
  79370. if (options.maxYaw != null) {
  79371. this.maxYaw = options.maxYaw;
  79372. }
  79373. else {
  79374. this.maxYaw = Math.PI;
  79375. }
  79376. if (options.minYaw != null) {
  79377. this.minYaw = options.minYaw;
  79378. }
  79379. else {
  79380. this.minYaw = -Math.PI;
  79381. }
  79382. if (options.maxPitch != null) {
  79383. this.maxPitch = options.maxPitch;
  79384. }
  79385. else {
  79386. this.maxPitch = Math.PI;
  79387. }
  79388. if (options.minPitch != null) {
  79389. this.minPitch = options.minPitch;
  79390. }
  79391. else {
  79392. this.minPitch = -Math.PI;
  79393. }
  79394. if (options.slerpAmount != null) {
  79395. this.slerpAmount = options.slerpAmount;
  79396. }
  79397. if (options.upAxis != null) {
  79398. this.upAxis = options.upAxis;
  79399. }
  79400. if (options.upAxisSpace != null) {
  79401. this.upAxisSpace = options.upAxisSpace;
  79402. }
  79403. if (options.yawAxis != null || options.pitchAxis != null) {
  79404. var newYawAxis = BABYLON.Axis.Y;
  79405. var newPitchAxis = BABYLON.Axis.X;
  79406. if (options.yawAxis != null) {
  79407. newYawAxis = options.yawAxis.clone();
  79408. newYawAxis.normalize();
  79409. }
  79410. if (options.pitchAxis != null) {
  79411. newPitchAxis = options.pitchAxis.clone();
  79412. newPitchAxis.normalize();
  79413. }
  79414. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  79415. this._transformYawPitch = BABYLON.Matrix.Identity();
  79416. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  79417. this._transformYawPitchInv = this._transformYawPitch.clone();
  79418. this._transformYawPitch.invert();
  79419. }
  79420. }
  79421. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  79422. this.upAxisSpace = BABYLON.Space.LOCAL;
  79423. }
  79424. }
  79425. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  79426. /**
  79427. * Gets or sets the minimum yaw angle that the bone can look to
  79428. */
  79429. get: function () {
  79430. return this._minYaw;
  79431. },
  79432. set: function (value) {
  79433. this._minYaw = value;
  79434. this._minYawSin = Math.sin(value);
  79435. this._minYawCos = Math.cos(value);
  79436. if (this._maxYaw != null) {
  79437. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79438. this._yawRange = this._maxYaw - this._minYaw;
  79439. }
  79440. },
  79441. enumerable: true,
  79442. configurable: true
  79443. });
  79444. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  79445. /**
  79446. * Gets or sets the maximum yaw angle that the bone can look to
  79447. */
  79448. get: function () {
  79449. return this._maxYaw;
  79450. },
  79451. set: function (value) {
  79452. this._maxYaw = value;
  79453. this._maxYawSin = Math.sin(value);
  79454. this._maxYawCos = Math.cos(value);
  79455. if (this._minYaw != null) {
  79456. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  79457. this._yawRange = this._maxYaw - this._minYaw;
  79458. }
  79459. },
  79460. enumerable: true,
  79461. configurable: true
  79462. });
  79463. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  79464. /**
  79465. * Gets or sets the minimum pitch angle that the bone can look to
  79466. */
  79467. get: function () {
  79468. return this._minPitch;
  79469. },
  79470. set: function (value) {
  79471. this._minPitch = value;
  79472. this._minPitchTan = Math.tan(value);
  79473. },
  79474. enumerable: true,
  79475. configurable: true
  79476. });
  79477. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  79478. /**
  79479. * Gets or sets the maximum pitch angle that the bone can look to
  79480. */
  79481. get: function () {
  79482. return this._maxPitch;
  79483. },
  79484. set: function (value) {
  79485. this._maxPitch = value;
  79486. this._maxPitchTan = Math.tan(value);
  79487. },
  79488. enumerable: true,
  79489. configurable: true
  79490. });
  79491. /**
  79492. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  79493. */
  79494. BoneLookController.prototype.update = function () {
  79495. //skip the first frame when slerping so that the mesh rotation is correct
  79496. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  79497. this._firstFrameSkipped = true;
  79498. return;
  79499. }
  79500. var bone = this.bone;
  79501. var bonePos = BoneLookController._tmpVecs[0];
  79502. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  79503. var target = this.target;
  79504. var _tmpMat1 = BoneLookController._tmpMats[0];
  79505. var _tmpMat2 = BoneLookController._tmpMats[1];
  79506. var mesh = this.mesh;
  79507. var parentBone = bone.getParent();
  79508. var upAxis = BoneLookController._tmpVecs[1];
  79509. upAxis.copyFrom(this.upAxis);
  79510. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  79511. if (this._transformYawPitch) {
  79512. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  79513. }
  79514. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  79515. }
  79516. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  79517. mesh.getDirectionToRef(upAxis, upAxis);
  79518. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  79519. upAxis.normalize();
  79520. }
  79521. }
  79522. var checkYaw = false;
  79523. var checkPitch = false;
  79524. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  79525. checkYaw = true;
  79526. }
  79527. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  79528. checkPitch = true;
  79529. }
  79530. if (checkYaw || checkPitch) {
  79531. var spaceMat = BoneLookController._tmpMats[2];
  79532. var spaceMatInv = BoneLookController._tmpMats[3];
  79533. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  79534. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  79535. }
  79536. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  79537. spaceMat.copyFrom(mesh.getWorldMatrix());
  79538. }
  79539. else {
  79540. var forwardAxis = BoneLookController._tmpVecs[2];
  79541. forwardAxis.copyFrom(this._fowardAxis);
  79542. if (this._transformYawPitch) {
  79543. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79544. }
  79545. if (parentBone) {
  79546. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79547. }
  79548. else {
  79549. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79550. }
  79551. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79552. rightAxis.normalize();
  79553. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79554. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79555. }
  79556. spaceMat.invertToRef(spaceMatInv);
  79557. var xzlen = null;
  79558. if (checkPitch) {
  79559. var localTarget = BoneLookController._tmpVecs[3];
  79560. target.subtractToRef(bonePos, localTarget);
  79561. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79562. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79563. var pitch = Math.atan2(localTarget.y, xzlen);
  79564. var newPitch = pitch;
  79565. if (pitch > this._maxPitch) {
  79566. localTarget.y = this._maxPitchTan * xzlen;
  79567. newPitch = this._maxPitch;
  79568. }
  79569. else if (pitch < this._minPitch) {
  79570. localTarget.y = this._minPitchTan * xzlen;
  79571. newPitch = this._minPitch;
  79572. }
  79573. if (pitch != newPitch) {
  79574. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79575. localTarget.addInPlace(bonePos);
  79576. target = localTarget;
  79577. }
  79578. }
  79579. if (checkYaw) {
  79580. var localTarget = BoneLookController._tmpVecs[4];
  79581. target.subtractToRef(bonePos, localTarget);
  79582. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79583. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79584. var newYaw = yaw;
  79585. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79586. if (xzlen == null) {
  79587. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79588. }
  79589. if (this._yawRange > Math.PI) {
  79590. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79591. localTarget.z = this._maxYawCos * xzlen;
  79592. localTarget.x = this._maxYawSin * xzlen;
  79593. newYaw = this._maxYaw;
  79594. }
  79595. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79596. localTarget.z = this._minYawCos * xzlen;
  79597. localTarget.x = this._minYawSin * xzlen;
  79598. newYaw = this._minYaw;
  79599. }
  79600. }
  79601. else {
  79602. if (yaw > this._maxYaw) {
  79603. localTarget.z = this._maxYawCos * xzlen;
  79604. localTarget.x = this._maxYawSin * xzlen;
  79605. newYaw = this._maxYaw;
  79606. }
  79607. else if (yaw < this._minYaw) {
  79608. localTarget.z = this._minYawCos * xzlen;
  79609. localTarget.x = this._minYawSin * xzlen;
  79610. newYaw = this._minYaw;
  79611. }
  79612. }
  79613. }
  79614. if (this._slerping && this._yawRange > Math.PI) {
  79615. //are we going to be crossing into the min/max region?
  79616. var boneFwd = BoneLookController._tmpVecs[8];
  79617. boneFwd.copyFrom(BABYLON.Axis.Z);
  79618. if (this._transformYawPitch) {
  79619. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79620. }
  79621. var boneRotMat = BoneLookController._tmpMats[4];
  79622. this._boneQuat.toRotationMatrix(boneRotMat);
  79623. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79624. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79625. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79626. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79627. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79628. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79629. if (angBtwTar > angBtwMidYaw) {
  79630. if (xzlen == null) {
  79631. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79632. }
  79633. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79634. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79635. if (angBtwMin < angBtwMax) {
  79636. newYaw = boneYaw + Math.PI * .75;
  79637. localTarget.z = Math.cos(newYaw) * xzlen;
  79638. localTarget.x = Math.sin(newYaw) * xzlen;
  79639. }
  79640. else {
  79641. newYaw = boneYaw - Math.PI * .75;
  79642. localTarget.z = Math.cos(newYaw) * xzlen;
  79643. localTarget.x = Math.sin(newYaw) * xzlen;
  79644. }
  79645. }
  79646. }
  79647. if (yaw != newYaw) {
  79648. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79649. localTarget.addInPlace(bonePos);
  79650. target = localTarget;
  79651. }
  79652. }
  79653. }
  79654. var zaxis = BoneLookController._tmpVecs[5];
  79655. var xaxis = BoneLookController._tmpVecs[6];
  79656. var yaxis = BoneLookController._tmpVecs[7];
  79657. var _tmpQuat = BoneLookController._tmpQuat;
  79658. target.subtractToRef(bonePos, zaxis);
  79659. zaxis.normalize();
  79660. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79661. xaxis.normalize();
  79662. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79663. yaxis.normalize();
  79664. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79665. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79666. return;
  79667. }
  79668. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79669. return;
  79670. }
  79671. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79672. return;
  79673. }
  79674. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79675. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79676. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79677. }
  79678. if (this.slerpAmount < 1) {
  79679. if (!this._slerping) {
  79680. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79681. }
  79682. if (this._transformYawPitch) {
  79683. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79684. }
  79685. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79686. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79687. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79688. this._slerping = true;
  79689. }
  79690. else {
  79691. if (this._transformYawPitch) {
  79692. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79693. }
  79694. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79695. this._slerping = false;
  79696. }
  79697. };
  79698. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79699. var angDiff = ang2 - ang1;
  79700. angDiff %= Math.PI * 2;
  79701. if (angDiff > Math.PI) {
  79702. angDiff -= Math.PI * 2;
  79703. }
  79704. else if (angDiff < -Math.PI) {
  79705. angDiff += Math.PI * 2;
  79706. }
  79707. return angDiff;
  79708. };
  79709. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79710. ang1 %= (2 * Math.PI);
  79711. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79712. ang2 %= (2 * Math.PI);
  79713. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79714. var ab = 0;
  79715. if (ang1 < ang2) {
  79716. ab = ang2 - ang1;
  79717. }
  79718. else {
  79719. ab = ang1 - ang2;
  79720. }
  79721. if (ab > Math.PI) {
  79722. ab = Math.PI * 2 - ab;
  79723. }
  79724. return ab;
  79725. };
  79726. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79727. ang %= (2 * Math.PI);
  79728. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79729. ang1 %= (2 * Math.PI);
  79730. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79731. ang2 %= (2 * Math.PI);
  79732. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79733. if (ang1 < ang2) {
  79734. if (ang > ang1 && ang < ang2) {
  79735. return true;
  79736. }
  79737. }
  79738. else {
  79739. if (ang > ang2 && ang < ang1) {
  79740. return true;
  79741. }
  79742. }
  79743. return false;
  79744. };
  79745. 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()];
  79746. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79747. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79748. return BoneLookController;
  79749. }());
  79750. BABYLON.BoneLookController = BoneLookController;
  79751. })(BABYLON || (BABYLON = {}));
  79752. //# sourceMappingURL=babylon.boneLookController.js.map
  79753. var BABYLON;
  79754. (function (BABYLON) {
  79755. /**
  79756. * Class used to handle skinning animations
  79757. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79758. */
  79759. var Skeleton = /** @class */ (function () {
  79760. /**
  79761. * Creates a new skeleton
  79762. * @param name defines the skeleton name
  79763. * @param id defines the skeleton Id
  79764. * @param scene defines the hosting scene
  79765. */
  79766. function Skeleton(
  79767. /** defines the skeleton name */
  79768. name,
  79769. /** defines the skeleton Id */
  79770. id, scene) {
  79771. this.name = name;
  79772. this.id = id;
  79773. /**
  79774. * Gets the list of child bones
  79775. */
  79776. this.bones = new Array();
  79777. /**
  79778. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79779. */
  79780. this.needInitialSkinMatrix = false;
  79781. this._isDirty = true;
  79782. this._meshesWithPoseMatrix = new Array();
  79783. this._identity = BABYLON.Matrix.Identity();
  79784. this._ranges = {};
  79785. this._lastAbsoluteTransformsUpdateId = -1;
  79786. /**
  79787. * Specifies if the skeleton should be serialized
  79788. */
  79789. this.doNotSerialize = false;
  79790. this._animationPropertiesOverride = null;
  79791. // Events
  79792. /**
  79793. * An observable triggered before computing the skeleton's matrices
  79794. */
  79795. this.onBeforeComputeObservable = new BABYLON.Observable();
  79796. this.bones = [];
  79797. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79798. scene.skeletons.push(this);
  79799. //make sure it will recalculate the matrix next time prepare is called.
  79800. this._isDirty = true;
  79801. }
  79802. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79803. /**
  79804. * Gets or sets the animation properties override
  79805. */
  79806. get: function () {
  79807. if (!this._animationPropertiesOverride) {
  79808. return this._scene.animationPropertiesOverride;
  79809. }
  79810. return this._animationPropertiesOverride;
  79811. },
  79812. set: function (value) {
  79813. this._animationPropertiesOverride = value;
  79814. },
  79815. enumerable: true,
  79816. configurable: true
  79817. });
  79818. // Members
  79819. /**
  79820. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79821. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79822. * @returns a Float32Array containing matrices data
  79823. */
  79824. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79825. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79826. return mesh._bonesTransformMatrices;
  79827. }
  79828. if (!this._transformMatrices) {
  79829. this.prepare();
  79830. }
  79831. return this._transformMatrices;
  79832. };
  79833. /**
  79834. * Gets the current hosting scene
  79835. * @returns a scene object
  79836. */
  79837. Skeleton.prototype.getScene = function () {
  79838. return this._scene;
  79839. };
  79840. // Methods
  79841. /**
  79842. * Gets a string representing the current skeleton data
  79843. * @param fullDetails defines a boolean indicating if we want a verbose version
  79844. * @returns a string representing the current skeleton data
  79845. */
  79846. Skeleton.prototype.toString = function (fullDetails) {
  79847. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79848. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79849. if (fullDetails) {
  79850. ret += ", Ranges: {";
  79851. var first = true;
  79852. for (var name_1 in this._ranges) {
  79853. if (first) {
  79854. ret += ", ";
  79855. first = false;
  79856. }
  79857. ret += name_1;
  79858. }
  79859. ret += "}";
  79860. }
  79861. return ret;
  79862. };
  79863. /**
  79864. * Get bone's index searching by name
  79865. * @param name defines bone's name to search for
  79866. * @return the indice of the bone. Returns -1 if not found
  79867. */
  79868. Skeleton.prototype.getBoneIndexByName = function (name) {
  79869. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79870. if (this.bones[boneIndex].name === name) {
  79871. return boneIndex;
  79872. }
  79873. }
  79874. return -1;
  79875. };
  79876. /**
  79877. * Creater a new animation range
  79878. * @param name defines the name of the range
  79879. * @param from defines the start key
  79880. * @param to defines the end key
  79881. */
  79882. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79883. // check name not already in use
  79884. if (!this._ranges[name]) {
  79885. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79886. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79887. if (this.bones[i].animations[0]) {
  79888. this.bones[i].animations[0].createRange(name, from, to);
  79889. }
  79890. }
  79891. }
  79892. };
  79893. /**
  79894. * Delete a specific animation range
  79895. * @param name defines the name of the range
  79896. * @param deleteFrames defines if frames must be removed as well
  79897. */
  79898. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79899. if (deleteFrames === void 0) { deleteFrames = true; }
  79900. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79901. if (this.bones[i].animations[0]) {
  79902. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79903. }
  79904. }
  79905. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79906. };
  79907. /**
  79908. * Gets a specific animation range
  79909. * @param name defines the name of the range to look for
  79910. * @returns the requested animation range or null if not found
  79911. */
  79912. Skeleton.prototype.getAnimationRange = function (name) {
  79913. return this._ranges[name];
  79914. };
  79915. /**
  79916. * Gets the list of all animation ranges defined on this skeleton
  79917. * @returns an array
  79918. */
  79919. Skeleton.prototype.getAnimationRanges = function () {
  79920. var animationRanges = [];
  79921. var name;
  79922. var i = 0;
  79923. for (name in this._ranges) {
  79924. animationRanges[i] = this._ranges[name];
  79925. i++;
  79926. }
  79927. return animationRanges;
  79928. };
  79929. /**
  79930. * Copy animation range from a source skeleton.
  79931. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79932. * @param source defines the source skeleton
  79933. * @param name defines the name of the range to copy
  79934. * @param rescaleAsRequired defines if rescaling must be applied if required
  79935. * @returns true if operation was successful
  79936. */
  79937. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79938. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79939. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79940. return false;
  79941. }
  79942. var ret = true;
  79943. var frameOffset = this._getHighestAnimationFrame() + 1;
  79944. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79945. var boneDict = {};
  79946. var sourceBones = source.bones;
  79947. var nBones;
  79948. var i;
  79949. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79950. boneDict[sourceBones[i].name] = sourceBones[i];
  79951. }
  79952. if (this.bones.length !== sourceBones.length) {
  79953. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79954. ret = false;
  79955. }
  79956. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79957. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79958. var boneName = this.bones[i].name;
  79959. var sourceBone = boneDict[boneName];
  79960. if (sourceBone) {
  79961. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79962. }
  79963. else {
  79964. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79965. ret = false;
  79966. }
  79967. }
  79968. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79969. var range = source.getAnimationRange(name);
  79970. if (range) {
  79971. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79972. }
  79973. return ret;
  79974. };
  79975. /**
  79976. * Forces the skeleton to go to rest pose
  79977. */
  79978. Skeleton.prototype.returnToRest = function () {
  79979. for (var index = 0; index < this.bones.length; index++) {
  79980. this.bones[index].returnToRest();
  79981. }
  79982. };
  79983. Skeleton.prototype._getHighestAnimationFrame = function () {
  79984. var ret = 0;
  79985. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79986. if (this.bones[i].animations[0]) {
  79987. var highest = this.bones[i].animations[0].getHighestFrame();
  79988. if (ret < highest) {
  79989. ret = highest;
  79990. }
  79991. }
  79992. }
  79993. return ret;
  79994. };
  79995. /**
  79996. * Begin a specific animation range
  79997. * @param name defines the name of the range to start
  79998. * @param loop defines if looping must be turned on (false by default)
  79999. * @param speedRatio defines the speed ratio to apply (1 by default)
  80000. * @param onAnimationEnd defines a callback which will be called when animation will end
  80001. * @returns a new animatable
  80002. */
  80003. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80004. var range = this.getAnimationRange(name);
  80005. if (!range) {
  80006. return null;
  80007. }
  80008. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80009. };
  80010. /** @hidden */
  80011. Skeleton.prototype._markAsDirty = function () {
  80012. this._isDirty = true;
  80013. };
  80014. /** @hidden */
  80015. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80016. this._meshesWithPoseMatrix.push(mesh);
  80017. };
  80018. /** @hidden */
  80019. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80020. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80021. if (index > -1) {
  80022. this._meshesWithPoseMatrix.splice(index, 1);
  80023. }
  80024. };
  80025. /** @hidden */
  80026. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80027. this.onBeforeComputeObservable.notifyObservers(this);
  80028. for (var index = 0; index < this.bones.length; index++) {
  80029. var bone = this.bones[index];
  80030. var parentBone = bone.getParent();
  80031. if (parentBone) {
  80032. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80033. }
  80034. else {
  80035. if (initialSkinMatrix) {
  80036. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80037. }
  80038. else {
  80039. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80040. }
  80041. }
  80042. if (bone._index !== -1) {
  80043. var mappedIndex = bone._index === null ? index : bone._index;
  80044. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80045. }
  80046. }
  80047. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80048. };
  80049. /**
  80050. * Build all resources required to render a skeleton
  80051. */
  80052. Skeleton.prototype.prepare = function () {
  80053. if (!this._isDirty) {
  80054. return;
  80055. }
  80056. if (this.needInitialSkinMatrix) {
  80057. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80058. var mesh = this._meshesWithPoseMatrix[index];
  80059. var poseMatrix = mesh.getPoseMatrix();
  80060. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80061. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80062. }
  80063. if (this._synchronizedWithMesh !== mesh) {
  80064. this._synchronizedWithMesh = mesh;
  80065. // Prepare bones
  80066. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80067. var bone = this.bones[boneIndex];
  80068. if (!bone.getParent()) {
  80069. var matrix = bone.getBaseMatrix();
  80070. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80071. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80072. }
  80073. }
  80074. }
  80075. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80076. }
  80077. }
  80078. else {
  80079. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80080. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80081. }
  80082. this._computeTransformMatrices(this._transformMatrices, null);
  80083. }
  80084. this._isDirty = false;
  80085. this._scene._activeBones.addCount(this.bones.length, false);
  80086. };
  80087. /**
  80088. * Gets the list of animatables currently running for this skeleton
  80089. * @returns an array of animatables
  80090. */
  80091. Skeleton.prototype.getAnimatables = function () {
  80092. if (!this._animatables || this._animatables.length !== this.bones.length) {
  80093. this._animatables = [];
  80094. for (var index = 0; index < this.bones.length; index++) {
  80095. this._animatables.push(this.bones[index]);
  80096. }
  80097. }
  80098. return this._animatables;
  80099. };
  80100. /**
  80101. * Clone the current skeleton
  80102. * @param name defines the name of the new skeleton
  80103. * @param id defines the id of the enw skeleton
  80104. * @returns the new skeleton
  80105. */
  80106. Skeleton.prototype.clone = function (name, id) {
  80107. var result = new Skeleton(name, id || name, this._scene);
  80108. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80109. for (var index = 0; index < this.bones.length; index++) {
  80110. var source = this.bones[index];
  80111. var parentBone = null;
  80112. var parent_1 = source.getParent();
  80113. if (parent_1) {
  80114. var parentIndex = this.bones.indexOf(parent_1);
  80115. parentBone = result.bones[parentIndex];
  80116. }
  80117. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  80118. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  80119. }
  80120. if (this._ranges) {
  80121. result._ranges = {};
  80122. for (var rangeName in this._ranges) {
  80123. var range = this._ranges[rangeName];
  80124. if (range) {
  80125. result._ranges[rangeName] = range.clone();
  80126. }
  80127. }
  80128. }
  80129. this._isDirty = true;
  80130. return result;
  80131. };
  80132. /**
  80133. * Enable animation blending for this skeleton
  80134. * @param blendingSpeed defines the blending speed to apply
  80135. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  80136. */
  80137. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  80138. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  80139. this.bones.forEach(function (bone) {
  80140. bone.animations.forEach(function (animation) {
  80141. animation.enableBlending = true;
  80142. animation.blendingSpeed = blendingSpeed;
  80143. });
  80144. });
  80145. };
  80146. /**
  80147. * Releases all resources associated with the current skeleton
  80148. */
  80149. Skeleton.prototype.dispose = function () {
  80150. this._meshesWithPoseMatrix = [];
  80151. // Animations
  80152. this.getScene().stopAnimation(this);
  80153. // Remove from scene
  80154. this.getScene().removeSkeleton(this);
  80155. };
  80156. /**
  80157. * Serialize the skeleton in a JSON object
  80158. * @returns a JSON object
  80159. */
  80160. Skeleton.prototype.serialize = function () {
  80161. var serializationObject = {};
  80162. serializationObject.name = this.name;
  80163. serializationObject.id = this.id;
  80164. if (this.dimensionsAtRest) {
  80165. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  80166. }
  80167. serializationObject.bones = [];
  80168. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  80169. for (var index = 0; index < this.bones.length; index++) {
  80170. var bone = this.bones[index];
  80171. var parent_2 = bone.getParent();
  80172. var serializedBone = {
  80173. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  80174. name: bone.name,
  80175. matrix: bone.getBaseMatrix().toArray(),
  80176. rest: bone.getRestPose().toArray()
  80177. };
  80178. serializationObject.bones.push(serializedBone);
  80179. if (bone.length) {
  80180. serializedBone.length = bone.length;
  80181. }
  80182. if (bone.metadata) {
  80183. serializedBone.metadata = bone.metadata;
  80184. }
  80185. if (bone.animations && bone.animations.length > 0) {
  80186. serializedBone.animation = bone.animations[0].serialize();
  80187. }
  80188. serializationObject.ranges = [];
  80189. for (var name in this._ranges) {
  80190. var source = this._ranges[name];
  80191. if (!source) {
  80192. continue;
  80193. }
  80194. var range = {};
  80195. range.name = name;
  80196. range.from = source.from;
  80197. range.to = source.to;
  80198. serializationObject.ranges.push(range);
  80199. }
  80200. }
  80201. return serializationObject;
  80202. };
  80203. /**
  80204. * Creates a new skeleton from serialized data
  80205. * @param parsedSkeleton defines the serialized data
  80206. * @param scene defines the hosting scene
  80207. * @returns a new skeleton
  80208. */
  80209. Skeleton.Parse = function (parsedSkeleton, scene) {
  80210. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  80211. if (parsedSkeleton.dimensionsAtRest) {
  80212. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  80213. }
  80214. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  80215. var index;
  80216. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  80217. var parsedBone = parsedSkeleton.bones[index];
  80218. var parentBone = null;
  80219. if (parsedBone.parentBoneIndex > -1) {
  80220. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  80221. }
  80222. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  80223. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  80224. if (parsedBone.length) {
  80225. bone.length = parsedBone.length;
  80226. }
  80227. if (parsedBone.metadata) {
  80228. bone.metadata = parsedBone.metadata;
  80229. }
  80230. if (parsedBone.animation) {
  80231. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  80232. }
  80233. }
  80234. // placed after bones, so createAnimationRange can cascade down
  80235. if (parsedSkeleton.ranges) {
  80236. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  80237. var data = parsedSkeleton.ranges[index];
  80238. skeleton.createAnimationRange(data.name, data.from, data.to);
  80239. }
  80240. }
  80241. return skeleton;
  80242. };
  80243. /**
  80244. * Compute all node absolute transforms
  80245. * @param forceUpdate defines if computation must be done even if cache is up to date
  80246. */
  80247. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  80248. if (forceUpdate === void 0) { forceUpdate = false; }
  80249. var renderId = this._scene.getRenderId();
  80250. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  80251. this.bones[0].computeAbsoluteTransforms();
  80252. this._lastAbsoluteTransformsUpdateId = renderId;
  80253. }
  80254. };
  80255. /**
  80256. * Gets the root pose matrix
  80257. * @returns a matrix
  80258. */
  80259. Skeleton.prototype.getPoseMatrix = function () {
  80260. var poseMatrix = null;
  80261. if (this._meshesWithPoseMatrix.length > 0) {
  80262. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  80263. }
  80264. return poseMatrix;
  80265. };
  80266. /**
  80267. * Sorts bones per internal index
  80268. */
  80269. Skeleton.prototype.sortBones = function () {
  80270. var bones = new Array();
  80271. var visited = new Array(this.bones.length);
  80272. for (var index = 0; index < this.bones.length; index++) {
  80273. this._sortBones(index, bones, visited);
  80274. }
  80275. this.bones = bones;
  80276. };
  80277. Skeleton.prototype._sortBones = function (index, bones, visited) {
  80278. if (visited[index]) {
  80279. return;
  80280. }
  80281. visited[index] = true;
  80282. var bone = this.bones[index];
  80283. if (bone._index === undefined) {
  80284. bone._index = index;
  80285. }
  80286. var parentBone = bone.getParent();
  80287. if (parentBone) {
  80288. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  80289. }
  80290. bones.push(bone);
  80291. };
  80292. return Skeleton;
  80293. }());
  80294. BABYLON.Skeleton = Skeleton;
  80295. })(BABYLON || (BABYLON = {}));
  80296. //# sourceMappingURL=babylon.skeleton.js.map
  80297. var BABYLON;
  80298. (function (BABYLON) {
  80299. var SphericalPolynomial = /** @class */ (function () {
  80300. function SphericalPolynomial() {
  80301. this.x = BABYLON.Vector3.Zero();
  80302. this.y = BABYLON.Vector3.Zero();
  80303. this.z = BABYLON.Vector3.Zero();
  80304. this.xx = BABYLON.Vector3.Zero();
  80305. this.yy = BABYLON.Vector3.Zero();
  80306. this.zz = BABYLON.Vector3.Zero();
  80307. this.xy = BABYLON.Vector3.Zero();
  80308. this.yz = BABYLON.Vector3.Zero();
  80309. this.zx = BABYLON.Vector3.Zero();
  80310. }
  80311. SphericalPolynomial.prototype.addAmbient = function (color) {
  80312. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80313. this.xx = this.xx.add(colorVector);
  80314. this.yy = this.yy.add(colorVector);
  80315. this.zz = this.zz.add(colorVector);
  80316. };
  80317. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  80318. var result = new SphericalPolynomial();
  80319. result.x = harmonics.L11.scale(1.02333);
  80320. result.y = harmonics.L1_1.scale(1.02333);
  80321. result.z = harmonics.L10.scale(1.02333);
  80322. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  80323. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  80324. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  80325. result.yz = harmonics.L2_1.scale(0.858086);
  80326. result.zx = harmonics.L21.scale(0.858086);
  80327. result.xy = harmonics.L2_2.scale(0.858086);
  80328. result.scale(1.0 / Math.PI);
  80329. return result;
  80330. };
  80331. SphericalPolynomial.prototype.scale = function (scale) {
  80332. this.x = this.x.scale(scale);
  80333. this.y = this.y.scale(scale);
  80334. this.z = this.z.scale(scale);
  80335. this.xx = this.xx.scale(scale);
  80336. this.yy = this.yy.scale(scale);
  80337. this.zz = this.zz.scale(scale);
  80338. this.yz = this.yz.scale(scale);
  80339. this.zx = this.zx.scale(scale);
  80340. this.xy = this.xy.scale(scale);
  80341. };
  80342. return SphericalPolynomial;
  80343. }());
  80344. BABYLON.SphericalPolynomial = SphericalPolynomial;
  80345. var SphericalHarmonics = /** @class */ (function () {
  80346. function SphericalHarmonics() {
  80347. this.L00 = BABYLON.Vector3.Zero();
  80348. this.L1_1 = BABYLON.Vector3.Zero();
  80349. this.L10 = BABYLON.Vector3.Zero();
  80350. this.L11 = BABYLON.Vector3.Zero();
  80351. this.L2_2 = BABYLON.Vector3.Zero();
  80352. this.L2_1 = BABYLON.Vector3.Zero();
  80353. this.L20 = BABYLON.Vector3.Zero();
  80354. this.L21 = BABYLON.Vector3.Zero();
  80355. this.L22 = BABYLON.Vector3.Zero();
  80356. }
  80357. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  80358. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  80359. var c = colorVector.scale(deltaSolidAngle);
  80360. this.L00 = this.L00.add(c.scale(0.282095));
  80361. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  80362. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  80363. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  80364. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  80365. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  80366. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  80367. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  80368. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  80369. };
  80370. SphericalHarmonics.prototype.scale = function (scale) {
  80371. this.L00 = this.L00.scale(scale);
  80372. this.L1_1 = this.L1_1.scale(scale);
  80373. this.L10 = this.L10.scale(scale);
  80374. this.L11 = this.L11.scale(scale);
  80375. this.L2_2 = this.L2_2.scale(scale);
  80376. this.L2_1 = this.L2_1.scale(scale);
  80377. this.L20 = this.L20.scale(scale);
  80378. this.L21 = this.L21.scale(scale);
  80379. this.L22 = this.L22.scale(scale);
  80380. };
  80381. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  80382. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  80383. //
  80384. // E_lm = A_l * L_lm
  80385. //
  80386. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  80387. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  80388. // the scaling factors are given in equation 9.
  80389. // Constant (Band 0)
  80390. this.L00 = this.L00.scale(3.141593);
  80391. // Linear (Band 1)
  80392. this.L1_1 = this.L1_1.scale(2.094395);
  80393. this.L10 = this.L10.scale(2.094395);
  80394. this.L11 = this.L11.scale(2.094395);
  80395. // Quadratic (Band 2)
  80396. this.L2_2 = this.L2_2.scale(0.785398);
  80397. this.L2_1 = this.L2_1.scale(0.785398);
  80398. this.L20 = this.L20.scale(0.785398);
  80399. this.L21 = this.L21.scale(0.785398);
  80400. this.L22 = this.L22.scale(0.785398);
  80401. };
  80402. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  80403. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  80404. // L = (1/pi) * E * rho
  80405. //
  80406. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  80407. this.scale(1.0 / Math.PI);
  80408. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  80409. // (The pixel shader must apply albedo after texture fetches, etc).
  80410. };
  80411. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  80412. var result = new SphericalHarmonics();
  80413. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  80414. result.L1_1 = polynomial.y.scale(0.977204);
  80415. result.L10 = polynomial.z.scale(0.977204);
  80416. result.L11 = polynomial.x.scale(0.977204);
  80417. result.L2_2 = polynomial.xy.scale(1.16538);
  80418. result.L2_1 = polynomial.yz.scale(1.16538);
  80419. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  80420. result.L21 = polynomial.zx.scale(1.16538);
  80421. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  80422. result.scale(Math.PI);
  80423. return result;
  80424. };
  80425. return SphericalHarmonics;
  80426. }());
  80427. BABYLON.SphericalHarmonics = SphericalHarmonics;
  80428. })(BABYLON || (BABYLON = {}));
  80429. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  80430. var BABYLON;
  80431. (function (BABYLON) {
  80432. var FileFaceOrientation = /** @class */ (function () {
  80433. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  80434. this.name = name;
  80435. this.worldAxisForNormal = worldAxisForNormal;
  80436. this.worldAxisForFileX = worldAxisForFileX;
  80437. this.worldAxisForFileY = worldAxisForFileY;
  80438. }
  80439. return FileFaceOrientation;
  80440. }());
  80441. ;
  80442. /**
  80443. * Helper class dealing with the extraction of spherical polynomial dataArray
  80444. * from a cube map.
  80445. */
  80446. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  80447. function CubeMapToSphericalPolynomialTools() {
  80448. }
  80449. /**
  80450. * Converts a texture to the according Spherical Polynomial data.
  80451. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80452. *
  80453. * @param texture The texture to extract the information from.
  80454. * @return The Spherical Polynomial data.
  80455. */
  80456. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  80457. if (!texture.isCube) {
  80458. // Only supports cube Textures currently.
  80459. return null;
  80460. }
  80461. var size = texture.getSize().width;
  80462. var right = texture.readPixels(0);
  80463. var left = texture.readPixels(1);
  80464. var up;
  80465. var down;
  80466. if (texture.isRenderTarget) {
  80467. up = texture.readPixels(3);
  80468. down = texture.readPixels(2);
  80469. }
  80470. else {
  80471. up = texture.readPixels(2);
  80472. down = texture.readPixels(3);
  80473. }
  80474. var front = texture.readPixels(4);
  80475. var back = texture.readPixels(5);
  80476. var gammaSpace = texture.gammaSpace;
  80477. // Always read as RGBA.
  80478. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  80479. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80480. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80481. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80482. }
  80483. var cubeInfo = {
  80484. size: size,
  80485. right: right,
  80486. left: left,
  80487. up: up,
  80488. down: down,
  80489. front: front,
  80490. back: back,
  80491. format: format,
  80492. type: type,
  80493. gammaSpace: gammaSpace,
  80494. };
  80495. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  80496. };
  80497. /**
  80498. * Converts a cubemap to the according Spherical Polynomial data.
  80499. * This extracts the first 3 orders only as they are the only one used in the lighting.
  80500. *
  80501. * @param cubeInfo The Cube map to extract the information from.
  80502. * @return The Spherical Polynomial data.
  80503. */
  80504. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  80505. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  80506. var totalSolidAngle = 0.0;
  80507. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  80508. var du = 2.0 / cubeInfo.size;
  80509. var dv = du;
  80510. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  80511. var minUV = du * 0.5 - 1.0;
  80512. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  80513. var fileFace = this.FileFaces[faceIndex];
  80514. var dataArray = cubeInfo[fileFace.name];
  80515. var v = minUV;
  80516. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  80517. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  80518. // Because SP is still linear, so summation is fine in that basis.
  80519. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  80520. for (var y = 0; y < cubeInfo.size; y++) {
  80521. var u = minUV;
  80522. for (var x = 0; x < cubeInfo.size; x++) {
  80523. // World direction (not normalised)
  80524. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  80525. worldDirection.normalize();
  80526. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  80527. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  80528. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  80529. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  80530. // Handle Integer types.
  80531. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  80532. r /= 255;
  80533. g /= 255;
  80534. b /= 255;
  80535. }
  80536. // Handle Gamma space textures.
  80537. if (cubeInfo.gammaSpace) {
  80538. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  80539. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  80540. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  80541. }
  80542. var color = new BABYLON.Color3(r, g, b);
  80543. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80544. totalSolidAngle += deltaSolidAngle;
  80545. u += du;
  80546. }
  80547. v += dv;
  80548. }
  80549. }
  80550. // Solid angle for entire sphere is 4*pi
  80551. var sphereSolidAngle = 4.0 * Math.PI;
  80552. // Adjust the solid angle to allow for how many faces we processed.
  80553. var facesProcessed = 6.0;
  80554. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80555. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80556. // This is needed because the numerical integration over the cube uses a
  80557. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80558. // and also to compensate for accumulative error due to float precision in the summation.
  80559. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80560. sphericalHarmonics.scale(correctionFactor);
  80561. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80562. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80563. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80564. };
  80565. CubeMapToSphericalPolynomialTools.FileFaces = [
  80566. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80567. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80568. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80569. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80570. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80571. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80572. ];
  80573. return CubeMapToSphericalPolynomialTools;
  80574. }());
  80575. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80576. })(BABYLON || (BABYLON = {}));
  80577. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80578. var BABYLON;
  80579. (function (BABYLON) {
  80580. /**
  80581. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80582. */
  80583. var PanoramaToCubeMapTools = /** @class */ (function () {
  80584. function PanoramaToCubeMapTools() {
  80585. }
  80586. /**
  80587. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80588. *
  80589. * @param float32Array The source data.
  80590. * @param inputWidth The width of the input panorama.
  80591. * @param inputhHeight The height of the input panorama.
  80592. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80593. * @return The cubemap data
  80594. */
  80595. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80596. if (!float32Array) {
  80597. throw "ConvertPanoramaToCubemap: input cannot be null";
  80598. }
  80599. if (float32Array.length != inputWidth * inputHeight * 3) {
  80600. throw "ConvertPanoramaToCubemap: input size is wrong";
  80601. }
  80602. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80603. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80604. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80605. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80606. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80607. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80608. return {
  80609. front: textureFront,
  80610. back: textureBack,
  80611. left: textureLeft,
  80612. right: textureRight,
  80613. up: textureUp,
  80614. down: textureDown,
  80615. size: size,
  80616. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80617. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80618. gammaSpace: false,
  80619. };
  80620. };
  80621. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80622. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80623. var textureArray = new Float32Array(buffer);
  80624. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80625. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80626. var dy = 1 / texSize;
  80627. var fy = 0;
  80628. for (var y = 0; y < texSize; y++) {
  80629. var xv1 = faceData[0];
  80630. var xv2 = faceData[2];
  80631. for (var x = 0; x < texSize; x++) {
  80632. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80633. v.normalize();
  80634. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80635. // 3 channels per pixels
  80636. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80637. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80638. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80639. xv1 = xv1.add(rotDX1);
  80640. xv2 = xv2.add(rotDX2);
  80641. }
  80642. fy += dy;
  80643. }
  80644. return textureArray;
  80645. };
  80646. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80647. var theta = Math.atan2(vDir.z, vDir.x);
  80648. var phi = Math.acos(vDir.y);
  80649. while (theta < -Math.PI)
  80650. theta += 2 * Math.PI;
  80651. while (theta > Math.PI)
  80652. theta -= 2 * Math.PI;
  80653. var dx = theta / Math.PI;
  80654. var dy = phi / Math.PI;
  80655. // recenter.
  80656. dx = dx * 0.5 + 0.5;
  80657. var px = Math.round(dx * inputWidth);
  80658. if (px < 0)
  80659. px = 0;
  80660. else if (px >= inputWidth)
  80661. px = inputWidth - 1;
  80662. var py = Math.round(dy * inputHeight);
  80663. if (py < 0)
  80664. py = 0;
  80665. else if (py >= inputHeight)
  80666. py = inputHeight - 1;
  80667. var inputY = (inputHeight - py - 1);
  80668. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80669. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80670. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80671. return {
  80672. r: r,
  80673. g: g,
  80674. b: b
  80675. };
  80676. };
  80677. PanoramaToCubeMapTools.FACE_FRONT = [
  80678. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80679. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80680. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80681. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80682. ];
  80683. PanoramaToCubeMapTools.FACE_BACK = [
  80684. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80685. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80686. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80687. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80688. ];
  80689. PanoramaToCubeMapTools.FACE_RIGHT = [
  80690. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80691. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80692. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80693. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80694. ];
  80695. PanoramaToCubeMapTools.FACE_LEFT = [
  80696. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80697. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80698. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80699. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80700. ];
  80701. PanoramaToCubeMapTools.FACE_DOWN = [
  80702. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80703. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80704. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80705. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80706. ];
  80707. PanoramaToCubeMapTools.FACE_UP = [
  80708. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80709. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80710. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80711. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80712. ];
  80713. return PanoramaToCubeMapTools;
  80714. }());
  80715. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80716. })(BABYLON || (BABYLON = {}));
  80717. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80718. var BABYLON;
  80719. (function (BABYLON) {
  80720. ;
  80721. /**
  80722. * This groups tools to convert HDR texture to native colors array.
  80723. */
  80724. var HDRTools = /** @class */ (function () {
  80725. function HDRTools() {
  80726. }
  80727. HDRTools.Ldexp = function (mantissa, exponent) {
  80728. if (exponent > 1023) {
  80729. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80730. }
  80731. if (exponent < -1074) {
  80732. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80733. }
  80734. return mantissa * Math.pow(2, exponent);
  80735. };
  80736. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80737. if (exponent > 0) { /*nonzero pixel*/
  80738. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80739. float32array[index + 0] = red * exponent;
  80740. float32array[index + 1] = green * exponent;
  80741. float32array[index + 2] = blue * exponent;
  80742. }
  80743. else {
  80744. float32array[index + 0] = 0;
  80745. float32array[index + 1] = 0;
  80746. float32array[index + 2] = 0;
  80747. }
  80748. };
  80749. HDRTools.readStringLine = function (uint8array, startIndex) {
  80750. var line = "";
  80751. var character = "";
  80752. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80753. character = String.fromCharCode(uint8array[i]);
  80754. if (character == "\n") {
  80755. break;
  80756. }
  80757. line += character;
  80758. }
  80759. return line;
  80760. };
  80761. /**
  80762. * Reads header information from an RGBE texture stored in a native array.
  80763. * More information on this format are available here:
  80764. * https://en.wikipedia.org/wiki/RGBE_image_format
  80765. *
  80766. * @param uint8array The binary file stored in native array.
  80767. * @return The header information.
  80768. */
  80769. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80770. var height = 0;
  80771. var width = 0;
  80772. var line = this.readStringLine(uint8array, 0);
  80773. if (line[0] != '#' || line[1] != '?') {
  80774. throw "Bad HDR Format.";
  80775. }
  80776. var endOfHeader = false;
  80777. var findFormat = false;
  80778. var lineIndex = 0;
  80779. do {
  80780. lineIndex += (line.length + 1);
  80781. line = this.readStringLine(uint8array, lineIndex);
  80782. if (line == "FORMAT=32-bit_rle_rgbe") {
  80783. findFormat = true;
  80784. }
  80785. else if (line.length == 0) {
  80786. endOfHeader = true;
  80787. }
  80788. } while (!endOfHeader);
  80789. if (!findFormat) {
  80790. throw "HDR Bad header format, unsupported FORMAT";
  80791. }
  80792. lineIndex += (line.length + 1);
  80793. line = this.readStringLine(uint8array, lineIndex);
  80794. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80795. var match = sizeRegexp.exec(line);
  80796. // TODO. Support +Y and -X if needed.
  80797. if (!match || match.length < 3) {
  80798. throw "HDR Bad header format, no size";
  80799. }
  80800. width = parseInt(match[2]);
  80801. height = parseInt(match[1]);
  80802. if (width < 8 || width > 0x7fff) {
  80803. throw "HDR Bad header format, unsupported size";
  80804. }
  80805. lineIndex += (line.length + 1);
  80806. return {
  80807. height: height,
  80808. width: width,
  80809. dataPosition: lineIndex
  80810. };
  80811. };
  80812. /**
  80813. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80814. * This RGBE texture needs to store the information as a panorama.
  80815. *
  80816. * More information on this format are available here:
  80817. * https://en.wikipedia.org/wiki/RGBE_image_format
  80818. *
  80819. * @param buffer The binary file stored in an array buffer.
  80820. * @param size The expected size of the extracted cubemap.
  80821. * @return The Cube Map information.
  80822. */
  80823. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80824. var uint8array = new Uint8Array(buffer);
  80825. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80826. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80827. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80828. return cubeMapData;
  80829. };
  80830. /**
  80831. * Returns the pixels data extracted from an RGBE texture.
  80832. * This pixels will be stored left to right up to down in the R G B order in one array.
  80833. *
  80834. * More information on this format are available here:
  80835. * https://en.wikipedia.org/wiki/RGBE_image_format
  80836. *
  80837. * @param uint8array The binary file stored in an array buffer.
  80838. * @param hdrInfo The header information of the file.
  80839. * @return The pixels data in RGB right to left up to down order.
  80840. */
  80841. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80842. // Keep for multi format supports.
  80843. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80844. };
  80845. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80846. var num_scanlines = hdrInfo.height;
  80847. var scanline_width = hdrInfo.width;
  80848. var a, b, c, d, count;
  80849. var dataIndex = hdrInfo.dataPosition;
  80850. var index = 0, endIndex = 0, i = 0;
  80851. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80852. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80853. // 3 channels of 4 bytes per pixel in float.
  80854. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80855. var resultArray = new Float32Array(resultBuffer);
  80856. // read in each successive scanline
  80857. while (num_scanlines > 0) {
  80858. a = uint8array[dataIndex++];
  80859. b = uint8array[dataIndex++];
  80860. c = uint8array[dataIndex++];
  80861. d = uint8array[dataIndex++];
  80862. if (a != 2 || b != 2 || (c & 0x80)) {
  80863. // this file is not run length encoded
  80864. throw "HDR Bad header format, not RLE";
  80865. }
  80866. if (((c << 8) | d) != scanline_width) {
  80867. throw "HDR Bad header format, wrong scan line width";
  80868. }
  80869. index = 0;
  80870. // read each of the four channels for the scanline into the buffer
  80871. for (i = 0; i < 4; i++) {
  80872. endIndex = (i + 1) * scanline_width;
  80873. while (index < endIndex) {
  80874. a = uint8array[dataIndex++];
  80875. b = uint8array[dataIndex++];
  80876. if (a > 128) {
  80877. // a run of the same value
  80878. count = a - 128;
  80879. if ((count == 0) || (count > endIndex - index)) {
  80880. throw "HDR Bad Format, bad scanline data (run)";
  80881. }
  80882. while (count-- > 0) {
  80883. scanLineArray[index++] = b;
  80884. }
  80885. }
  80886. else {
  80887. // a non-run
  80888. count = a;
  80889. if ((count == 0) || (count > endIndex - index)) {
  80890. throw "HDR Bad Format, bad scanline data (non-run)";
  80891. }
  80892. scanLineArray[index++] = b;
  80893. if (--count > 0) {
  80894. for (var j = 0; j < count; j++) {
  80895. scanLineArray[index++] = uint8array[dataIndex++];
  80896. }
  80897. }
  80898. }
  80899. }
  80900. }
  80901. // now convert data from buffer into floats
  80902. for (i = 0; i < scanline_width; i++) {
  80903. a = scanLineArray[i];
  80904. b = scanLineArray[i + scanline_width];
  80905. c = scanLineArray[i + 2 * scanline_width];
  80906. d = scanLineArray[i + 3 * scanline_width];
  80907. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80908. }
  80909. num_scanlines--;
  80910. }
  80911. return resultArray;
  80912. };
  80913. return HDRTools;
  80914. }());
  80915. BABYLON.HDRTools = HDRTools;
  80916. })(BABYLON || (BABYLON = {}));
  80917. //# sourceMappingURL=babylon.hdr.js.map
  80918. var BABYLON;
  80919. (function (BABYLON) {
  80920. /**
  80921. * This represents a texture coming from an HDR input.
  80922. *
  80923. * The only supported format is currently panorama picture stored in RGBE format.
  80924. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80925. */
  80926. var HDRCubeTexture = /** @class */ (function (_super) {
  80927. __extends(HDRCubeTexture, _super);
  80928. /**
  80929. * Instantiates an HDRTexture from the following parameters.
  80930. *
  80931. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80932. * @param scene The scene the texture will be used in
  80933. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80934. * @param noMipmap Forces to not generate the mipmap if true
  80935. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80936. * @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)
  80937. * @param reserved Reserved flag for internal use.
  80938. */
  80939. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80940. if (noMipmap === void 0) { noMipmap = false; }
  80941. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80942. if (gammaSpace === void 0) { gammaSpace = false; }
  80943. if (reserved === void 0) { reserved = false; }
  80944. if (onLoad === void 0) { onLoad = null; }
  80945. if (onError === void 0) { onError = null; }
  80946. var _this = _super.call(this, scene) || this;
  80947. _this._generateHarmonics = true;
  80948. _this._onLoad = null;
  80949. _this._onError = null;
  80950. /**
  80951. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80952. */
  80953. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80954. _this._isBlocking = true;
  80955. _this._rotationY = 0;
  80956. /**
  80957. * Gets or sets the center of the bounding box associated with the cube texture
  80958. * It must define where the camera used to render the texture was set
  80959. */
  80960. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80961. if (!url) {
  80962. return _this;
  80963. }
  80964. _this.name = url;
  80965. _this.url = url;
  80966. _this.hasAlpha = false;
  80967. _this.isCube = true;
  80968. _this._textureMatrix = BABYLON.Matrix.Identity();
  80969. _this._onLoad = onLoad;
  80970. _this._onError = onError;
  80971. _this.gammaSpace = gammaSpace;
  80972. _this._noMipmap = noMipmap;
  80973. _this._size = size;
  80974. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80975. if (!_this._texture) {
  80976. if (!scene.useDelayedTextureLoading) {
  80977. _this.loadTexture();
  80978. }
  80979. else {
  80980. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80981. }
  80982. }
  80983. return _this;
  80984. }
  80985. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80986. /**
  80987. * Gets wether or not the texture is blocking during loading.
  80988. */
  80989. get: function () {
  80990. return this._isBlocking;
  80991. },
  80992. /**
  80993. * Sets wether or not the texture is blocking during loading.
  80994. */
  80995. set: function (value) {
  80996. this._isBlocking = value;
  80997. },
  80998. enumerable: true,
  80999. configurable: true
  81000. });
  81001. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  81002. /**
  81003. * Gets texture matrix rotation angle around Y axis radians.
  81004. */
  81005. get: function () {
  81006. return this._rotationY;
  81007. },
  81008. /**
  81009. * Sets texture matrix rotation angle around Y axis in radians.
  81010. */
  81011. set: function (value) {
  81012. this._rotationY = value;
  81013. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  81014. },
  81015. enumerable: true,
  81016. configurable: true
  81017. });
  81018. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  81019. get: function () {
  81020. return this._boundingBoxSize;
  81021. },
  81022. /**
  81023. * Gets or sets the size of the bounding box associated with the cube texture
  81024. * When defined, the cubemap will switch to local mode
  81025. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  81026. * @example https://www.babylonjs-playground.com/#RNASML
  81027. */
  81028. set: function (value) {
  81029. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  81030. return;
  81031. }
  81032. this._boundingBoxSize = value;
  81033. var scene = this.getScene();
  81034. if (scene) {
  81035. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  81036. }
  81037. },
  81038. enumerable: true,
  81039. configurable: true
  81040. });
  81041. /**
  81042. * Occurs when the file is raw .hdr file.
  81043. */
  81044. HDRCubeTexture.prototype.loadTexture = function () {
  81045. var _this = this;
  81046. var callback = function (buffer) {
  81047. var scene = _this.getScene();
  81048. if (!scene) {
  81049. return null;
  81050. }
  81051. // Extract the raw linear data.
  81052. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  81053. // Generate harmonics if needed.
  81054. if (_this._generateHarmonics) {
  81055. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  81056. _this.sphericalPolynomial = sphericalPolynomial;
  81057. }
  81058. var results = [];
  81059. var byteArray = null;
  81060. // Push each faces.
  81061. for (var j = 0; j < 6; j++) {
  81062. // Create uintarray fallback.
  81063. if (!scene.getEngine().getCaps().textureFloat) {
  81064. // 3 channels of 1 bytes per pixel in bytes.
  81065. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  81066. byteArray = new Uint8Array(byteBuffer);
  81067. }
  81068. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  81069. // If special cases.
  81070. if (_this.gammaSpace || byteArray) {
  81071. for (var i = 0; i < _this._size * _this._size; i++) {
  81072. // Put in gamma space if requested.
  81073. if (_this.gammaSpace) {
  81074. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  81075. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  81076. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  81077. }
  81078. // Convert to int texture for fallback.
  81079. if (byteArray) {
  81080. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  81081. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  81082. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  81083. // May use luminance instead if the result is not accurate.
  81084. var max = Math.max(Math.max(r, g), b);
  81085. if (max > 255) {
  81086. var scale = 255 / max;
  81087. r *= scale;
  81088. g *= scale;
  81089. b *= scale;
  81090. }
  81091. byteArray[(i * 3) + 0] = r;
  81092. byteArray[(i * 3) + 1] = g;
  81093. byteArray[(i * 3) + 2] = b;
  81094. }
  81095. }
  81096. }
  81097. if (byteArray) {
  81098. results.push(byteArray);
  81099. }
  81100. else {
  81101. results.push(dataFace);
  81102. }
  81103. }
  81104. return results;
  81105. };
  81106. var scene = this.getScene();
  81107. if (scene) {
  81108. 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);
  81109. }
  81110. };
  81111. HDRCubeTexture.prototype.clone = function () {
  81112. var scene = this.getScene();
  81113. if (!scene) {
  81114. return this;
  81115. }
  81116. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  81117. // Base texture
  81118. newTexture.level = this.level;
  81119. newTexture.wrapU = this.wrapU;
  81120. newTexture.wrapV = this.wrapV;
  81121. newTexture.coordinatesIndex = this.coordinatesIndex;
  81122. newTexture.coordinatesMode = this.coordinatesMode;
  81123. return newTexture;
  81124. };
  81125. // Methods
  81126. HDRCubeTexture.prototype.delayLoad = function () {
  81127. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  81128. return;
  81129. }
  81130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  81131. this._texture = this._getFromCache(this.url, this._noMipmap);
  81132. if (!this._texture) {
  81133. this.loadTexture();
  81134. }
  81135. };
  81136. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  81137. return this._textureMatrix;
  81138. };
  81139. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  81140. this._textureMatrix = value;
  81141. };
  81142. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  81143. var texture = null;
  81144. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  81145. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  81146. texture.name = parsedTexture.name;
  81147. texture.hasAlpha = parsedTexture.hasAlpha;
  81148. texture.level = parsedTexture.level;
  81149. texture.coordinatesMode = parsedTexture.coordinatesMode;
  81150. texture.isBlocking = parsedTexture.isBlocking;
  81151. }
  81152. if (texture) {
  81153. if (parsedTexture.boundingBoxPosition) {
  81154. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  81155. }
  81156. if (parsedTexture.boundingBoxSize) {
  81157. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  81158. }
  81159. if (parsedTexture.rotationY) {
  81160. texture.rotationY = parsedTexture.rotationY;
  81161. }
  81162. }
  81163. return texture;
  81164. };
  81165. HDRCubeTexture.prototype.serialize = function () {
  81166. if (!this.name) {
  81167. return null;
  81168. }
  81169. var serializationObject = {};
  81170. serializationObject.name = this.name;
  81171. serializationObject.hasAlpha = this.hasAlpha;
  81172. serializationObject.isCube = true;
  81173. serializationObject.level = this.level;
  81174. serializationObject.size = this._size;
  81175. serializationObject.coordinatesMode = this.coordinatesMode;
  81176. serializationObject.useInGammaSpace = this.gammaSpace;
  81177. serializationObject.generateHarmonics = this._generateHarmonics;
  81178. serializationObject.customType = "BABYLON.HDRCubeTexture";
  81179. serializationObject.noMipmap = this._noMipmap;
  81180. serializationObject.isBlocking = this._isBlocking;
  81181. serializationObject.rotationY = this._rotationY;
  81182. return serializationObject;
  81183. };
  81184. HDRCubeTexture._facesMapping = [
  81185. "right",
  81186. "left",
  81187. "up",
  81188. "down",
  81189. "front",
  81190. "back"
  81191. ];
  81192. return HDRCubeTexture;
  81193. }(BABYLON.BaseTexture));
  81194. BABYLON.HDRCubeTexture = HDRCubeTexture;
  81195. })(BABYLON || (BABYLON = {}));
  81196. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  81197. var BABYLON;
  81198. (function (BABYLON) {
  81199. var IndexedVector2 = /** @class */ (function (_super) {
  81200. __extends(IndexedVector2, _super);
  81201. function IndexedVector2(original, index) {
  81202. var _this = _super.call(this, original.x, original.y) || this;
  81203. _this.index = index;
  81204. return _this;
  81205. }
  81206. return IndexedVector2;
  81207. }(BABYLON.Vector2));
  81208. var PolygonPoints = /** @class */ (function () {
  81209. function PolygonPoints() {
  81210. this.elements = new Array();
  81211. }
  81212. PolygonPoints.prototype.add = function (originalPoints) {
  81213. var _this = this;
  81214. var result = new Array();
  81215. originalPoints.forEach(function (point) {
  81216. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  81217. var newPoint = new IndexedVector2(point, _this.elements.length);
  81218. result.push(newPoint);
  81219. _this.elements.push(newPoint);
  81220. }
  81221. });
  81222. return result;
  81223. };
  81224. PolygonPoints.prototype.computeBounds = function () {
  81225. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81226. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  81227. this.elements.forEach(function (point) {
  81228. // x
  81229. if (point.x < lmin.x) {
  81230. lmin.x = point.x;
  81231. }
  81232. else if (point.x > lmax.x) {
  81233. lmax.x = point.x;
  81234. }
  81235. // y
  81236. if (point.y < lmin.y) {
  81237. lmin.y = point.y;
  81238. }
  81239. else if (point.y > lmax.y) {
  81240. lmax.y = point.y;
  81241. }
  81242. });
  81243. return {
  81244. min: lmin,
  81245. max: lmax,
  81246. width: lmax.x - lmin.x,
  81247. height: lmax.y - lmin.y
  81248. };
  81249. };
  81250. return PolygonPoints;
  81251. }());
  81252. var Polygon = /** @class */ (function () {
  81253. function Polygon() {
  81254. }
  81255. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  81256. return [
  81257. new BABYLON.Vector2(xmin, ymin),
  81258. new BABYLON.Vector2(xmax, ymin),
  81259. new BABYLON.Vector2(xmax, ymax),
  81260. new BABYLON.Vector2(xmin, ymax)
  81261. ];
  81262. };
  81263. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  81264. if (cx === void 0) { cx = 0; }
  81265. if (cy === void 0) { cy = 0; }
  81266. if (numberOfSides === void 0) { numberOfSides = 32; }
  81267. var result = new Array();
  81268. var angle = 0;
  81269. var increment = (Math.PI * 2) / numberOfSides;
  81270. for (var i = 0; i < numberOfSides; i++) {
  81271. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  81272. angle -= increment;
  81273. }
  81274. return result;
  81275. };
  81276. Polygon.Parse = function (input) {
  81277. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  81278. var i, result = [];
  81279. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  81280. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  81281. }
  81282. return result;
  81283. };
  81284. Polygon.StartingAt = function (x, y) {
  81285. return BABYLON.Path2.StartingAt(x, y);
  81286. };
  81287. return Polygon;
  81288. }());
  81289. BABYLON.Polygon = Polygon;
  81290. var PolygonMeshBuilder = /** @class */ (function () {
  81291. function PolygonMeshBuilder(name, contours, scene) {
  81292. this._points = new PolygonPoints();
  81293. this._outlinepoints = new PolygonPoints();
  81294. this._holes = new Array();
  81295. this._epoints = new Array();
  81296. this._eholes = new Array();
  81297. this._name = name;
  81298. this._scene = scene;
  81299. var points;
  81300. if (contours instanceof BABYLON.Path2) {
  81301. points = contours.getPoints();
  81302. }
  81303. else {
  81304. points = contours;
  81305. }
  81306. this._addToepoint(points);
  81307. this._points.add(points);
  81308. this._outlinepoints.add(points);
  81309. if (typeof earcut === 'undefined') {
  81310. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  81311. }
  81312. }
  81313. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  81314. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  81315. var p = points_1[_i];
  81316. this._epoints.push(p.x, p.y);
  81317. }
  81318. };
  81319. PolygonMeshBuilder.prototype.addHole = function (hole) {
  81320. this._points.add(hole);
  81321. var holepoints = new PolygonPoints();
  81322. holepoints.add(hole);
  81323. this._holes.push(holepoints);
  81324. this._eholes.push(this._epoints.length / 2);
  81325. this._addToepoint(hole);
  81326. return this;
  81327. };
  81328. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  81329. var _this = this;
  81330. if (updatable === void 0) { updatable = false; }
  81331. if (depth === void 0) { depth = 0; }
  81332. var result = new BABYLON.Mesh(this._name, this._scene);
  81333. var normals = new Array();
  81334. var positions = new Array();
  81335. var uvs = new Array();
  81336. var bounds = this._points.computeBounds();
  81337. this._points.elements.forEach(function (p) {
  81338. normals.push(0, 1.0, 0);
  81339. positions.push(p.x, 0, p.y);
  81340. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  81341. });
  81342. var indices = new Array();
  81343. var res = earcut(this._epoints, this._eholes, 2);
  81344. for (var i = 0; i < res.length; i++) {
  81345. indices.push(res[i]);
  81346. }
  81347. if (depth > 0) {
  81348. var positionscount = (positions.length / 3); //get the current pointcount
  81349. this._points.elements.forEach(function (p) {
  81350. normals.push(0, -1.0, 0);
  81351. positions.push(p.x, -depth, p.y);
  81352. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  81353. });
  81354. var totalCount = indices.length;
  81355. for (var i = 0; i < totalCount; i += 3) {
  81356. var i0 = indices[i + 0];
  81357. var i1 = indices[i + 1];
  81358. var i2 = indices[i + 2];
  81359. indices.push(i2 + positionscount);
  81360. indices.push(i1 + positionscount);
  81361. indices.push(i0 + positionscount);
  81362. }
  81363. //Add the sides
  81364. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  81365. this._holes.forEach(function (hole) {
  81366. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  81367. });
  81368. }
  81369. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  81370. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  81371. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  81372. result.setIndices(indices);
  81373. return result;
  81374. };
  81375. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  81376. var StartIndex = positions.length / 3;
  81377. var ulength = 0;
  81378. for (var i = 0; i < points.elements.length; i++) {
  81379. var p = points.elements[i];
  81380. var p1;
  81381. if ((i + 1) > points.elements.length - 1) {
  81382. p1 = points.elements[0];
  81383. }
  81384. else {
  81385. p1 = points.elements[i + 1];
  81386. }
  81387. positions.push(p.x, 0, p.y);
  81388. positions.push(p.x, -depth, p.y);
  81389. positions.push(p1.x, 0, p1.y);
  81390. positions.push(p1.x, -depth, p1.y);
  81391. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  81392. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  81393. var v3 = v2.subtract(v1);
  81394. var v4 = new BABYLON.Vector3(0, 1, 0);
  81395. var vn = BABYLON.Vector3.Cross(v3, v4);
  81396. vn = vn.normalize();
  81397. uvs.push(ulength / bounds.width, 0);
  81398. uvs.push(ulength / bounds.width, 1);
  81399. ulength += v3.length();
  81400. uvs.push((ulength / bounds.width), 0);
  81401. uvs.push((ulength / bounds.width), 1);
  81402. if (!flip) {
  81403. normals.push(-vn.x, -vn.y, -vn.z);
  81404. normals.push(-vn.x, -vn.y, -vn.z);
  81405. normals.push(-vn.x, -vn.y, -vn.z);
  81406. normals.push(-vn.x, -vn.y, -vn.z);
  81407. indices.push(StartIndex);
  81408. indices.push(StartIndex + 1);
  81409. indices.push(StartIndex + 2);
  81410. indices.push(StartIndex + 1);
  81411. indices.push(StartIndex + 3);
  81412. indices.push(StartIndex + 2);
  81413. }
  81414. else {
  81415. normals.push(vn.x, vn.y, vn.z);
  81416. normals.push(vn.x, vn.y, vn.z);
  81417. normals.push(vn.x, vn.y, vn.z);
  81418. normals.push(vn.x, vn.y, vn.z);
  81419. indices.push(StartIndex);
  81420. indices.push(StartIndex + 2);
  81421. indices.push(StartIndex + 1);
  81422. indices.push(StartIndex + 1);
  81423. indices.push(StartIndex + 2);
  81424. indices.push(StartIndex + 3);
  81425. }
  81426. StartIndex += 4;
  81427. }
  81428. ;
  81429. };
  81430. return PolygonMeshBuilder;
  81431. }());
  81432. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  81433. })(BABYLON || (BABYLON = {}));
  81434. //# sourceMappingURL=babylon.polygonMesh.js.map
  81435. var BABYLON;
  81436. (function (BABYLON) {
  81437. // Unique ID when we import meshes from Babylon to CSG
  81438. var currentCSGMeshId = 0;
  81439. // # class Vertex
  81440. // Represents a vertex of a polygon. Use your own vertex class instead of this
  81441. // one to provide additional features like texture coordinates and vertex
  81442. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  81443. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  81444. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  81445. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  81446. // is not used anywhere else.
  81447. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  81448. var Vertex = /** @class */ (function () {
  81449. function Vertex(pos, normal, uv) {
  81450. this.pos = pos;
  81451. this.normal = normal;
  81452. this.uv = uv;
  81453. }
  81454. Vertex.prototype.clone = function () {
  81455. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  81456. };
  81457. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  81458. // orientation of a polygon is flipped.
  81459. Vertex.prototype.flip = function () {
  81460. this.normal = this.normal.scale(-1);
  81461. };
  81462. // Create a new vertex between this vertex and `other` by linearly
  81463. // interpolating all properties using a parameter of `t`. Subclasses should
  81464. // override this to interpolate additional properties.
  81465. Vertex.prototype.interpolate = function (other, t) {
  81466. 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));
  81467. };
  81468. return Vertex;
  81469. }());
  81470. // # class Plane
  81471. // Represents a plane in 3D space.
  81472. var Plane = /** @class */ (function () {
  81473. function Plane(normal, w) {
  81474. this.normal = normal;
  81475. this.w = w;
  81476. }
  81477. Plane.FromPoints = function (a, b, c) {
  81478. var v0 = c.subtract(a);
  81479. var v1 = b.subtract(a);
  81480. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  81481. return null;
  81482. }
  81483. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  81484. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  81485. };
  81486. Plane.prototype.clone = function () {
  81487. return new Plane(this.normal.clone(), this.w);
  81488. };
  81489. Plane.prototype.flip = function () {
  81490. this.normal.scaleInPlace(-1);
  81491. this.w = -this.w;
  81492. };
  81493. // Split `polygon` by this plane if needed, then put the polygon or polygon
  81494. // fragments in the appropriate lists. Coplanar polygons go into either
  81495. // `coplanarFront` or `coplanarBack` depending on their orientation with
  81496. // respect to this plane. Polygons in front or in back of this plane go into
  81497. // either `front` or `back`.
  81498. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  81499. var COPLANAR = 0;
  81500. var FRONT = 1;
  81501. var BACK = 2;
  81502. var SPANNING = 3;
  81503. // Classify each point as well as the entire polygon into one of the above
  81504. // four classes.
  81505. var polygonType = 0;
  81506. var types = [];
  81507. var i;
  81508. var t;
  81509. for (i = 0; i < polygon.vertices.length; i++) {
  81510. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  81511. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  81512. polygonType |= type;
  81513. types.push(type);
  81514. }
  81515. // Put the polygon in the correct list, splitting it when necessary.
  81516. switch (polygonType) {
  81517. case COPLANAR:
  81518. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  81519. break;
  81520. case FRONT:
  81521. front.push(polygon);
  81522. break;
  81523. case BACK:
  81524. back.push(polygon);
  81525. break;
  81526. case SPANNING:
  81527. var f = [], b = [];
  81528. for (i = 0; i < polygon.vertices.length; i++) {
  81529. var j = (i + 1) % polygon.vertices.length;
  81530. var ti = types[i], tj = types[j];
  81531. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  81532. if (ti !== BACK)
  81533. f.push(vi);
  81534. if (ti !== FRONT)
  81535. b.push(ti !== BACK ? vi.clone() : vi);
  81536. if ((ti | tj) === SPANNING) {
  81537. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  81538. var v = vi.interpolate(vj, t);
  81539. f.push(v);
  81540. b.push(v.clone());
  81541. }
  81542. }
  81543. var poly;
  81544. if (f.length >= 3) {
  81545. poly = new Polygon(f, polygon.shared);
  81546. if (poly.plane)
  81547. front.push(poly);
  81548. }
  81549. if (b.length >= 3) {
  81550. poly = new Polygon(b, polygon.shared);
  81551. if (poly.plane)
  81552. back.push(poly);
  81553. }
  81554. break;
  81555. }
  81556. };
  81557. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81558. // point is on the plane.
  81559. Plane.EPSILON = 1e-5;
  81560. return Plane;
  81561. }());
  81562. // # class Polygon
  81563. // Represents a convex polygon. The vertices used to initialize a polygon must
  81564. // be coplanar and form a convex loop.
  81565. //
  81566. // Each convex polygon has a `shared` property, which is shared between all
  81567. // polygons that are clones of each other or were split from the same polygon.
  81568. // This can be used to define per-polygon properties (such as surface color).
  81569. var Polygon = /** @class */ (function () {
  81570. function Polygon(vertices, shared) {
  81571. this.vertices = vertices;
  81572. this.shared = shared;
  81573. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81574. }
  81575. Polygon.prototype.clone = function () {
  81576. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81577. return new Polygon(vertices, this.shared);
  81578. };
  81579. Polygon.prototype.flip = function () {
  81580. this.vertices.reverse().map(function (v) { v.flip(); });
  81581. this.plane.flip();
  81582. };
  81583. return Polygon;
  81584. }());
  81585. // # class Node
  81586. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81587. // by picking a polygon to split along. That polygon (and all other coplanar
  81588. // polygons) are added directly to that node and the other polygons are added to
  81589. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81590. // no distinction between internal and leaf nodes.
  81591. var Node = /** @class */ (function () {
  81592. function Node(polygons) {
  81593. this.plane = null;
  81594. this.front = null;
  81595. this.back = null;
  81596. this.polygons = new Array();
  81597. if (polygons) {
  81598. this.build(polygons);
  81599. }
  81600. }
  81601. Node.prototype.clone = function () {
  81602. var node = new Node();
  81603. node.plane = this.plane && this.plane.clone();
  81604. node.front = this.front && this.front.clone();
  81605. node.back = this.back && this.back.clone();
  81606. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81607. return node;
  81608. };
  81609. // Convert solid space to empty space and empty space to solid space.
  81610. Node.prototype.invert = function () {
  81611. for (var i = 0; i < this.polygons.length; i++) {
  81612. this.polygons[i].flip();
  81613. }
  81614. if (this.plane) {
  81615. this.plane.flip();
  81616. }
  81617. if (this.front) {
  81618. this.front.invert();
  81619. }
  81620. if (this.back) {
  81621. this.back.invert();
  81622. }
  81623. var temp = this.front;
  81624. this.front = this.back;
  81625. this.back = temp;
  81626. };
  81627. // Recursively remove all polygons in `polygons` that are inside this BSP
  81628. // tree.
  81629. Node.prototype.clipPolygons = function (polygons) {
  81630. if (!this.plane)
  81631. return polygons.slice();
  81632. var front = new Array(), back = new Array();
  81633. for (var i = 0; i < polygons.length; i++) {
  81634. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81635. }
  81636. if (this.front) {
  81637. front = this.front.clipPolygons(front);
  81638. }
  81639. if (this.back) {
  81640. back = this.back.clipPolygons(back);
  81641. }
  81642. else {
  81643. back = [];
  81644. }
  81645. return front.concat(back);
  81646. };
  81647. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81648. // `bsp`.
  81649. Node.prototype.clipTo = function (bsp) {
  81650. this.polygons = bsp.clipPolygons(this.polygons);
  81651. if (this.front)
  81652. this.front.clipTo(bsp);
  81653. if (this.back)
  81654. this.back.clipTo(bsp);
  81655. };
  81656. // Return a list of all polygons in this BSP tree.
  81657. Node.prototype.allPolygons = function () {
  81658. var polygons = this.polygons.slice();
  81659. if (this.front)
  81660. polygons = polygons.concat(this.front.allPolygons());
  81661. if (this.back)
  81662. polygons = polygons.concat(this.back.allPolygons());
  81663. return polygons;
  81664. };
  81665. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81666. // new polygons are filtered down to the bottom of the tree and become new
  81667. // nodes there. Each set of polygons is partitioned using the first polygon
  81668. // (no heuristic is used to pick a good split).
  81669. Node.prototype.build = function (polygons) {
  81670. if (!polygons.length)
  81671. return;
  81672. if (!this.plane)
  81673. this.plane = polygons[0].plane.clone();
  81674. var front = new Array(), back = new Array();
  81675. for (var i = 0; i < polygons.length; i++) {
  81676. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81677. }
  81678. if (front.length) {
  81679. if (!this.front)
  81680. this.front = new Node();
  81681. this.front.build(front);
  81682. }
  81683. if (back.length) {
  81684. if (!this.back)
  81685. this.back = new Node();
  81686. this.back.build(back);
  81687. }
  81688. };
  81689. return Node;
  81690. }());
  81691. var CSG = /** @class */ (function () {
  81692. function CSG() {
  81693. this.polygons = new Array();
  81694. }
  81695. // Convert BABYLON.Mesh to BABYLON.CSG
  81696. CSG.FromMesh = function (mesh) {
  81697. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81698. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81699. if (mesh instanceof BABYLON.Mesh) {
  81700. mesh.computeWorldMatrix(true);
  81701. matrix = mesh.getWorldMatrix();
  81702. meshPosition = mesh.position.clone();
  81703. meshRotation = mesh.rotation.clone();
  81704. if (mesh.rotationQuaternion) {
  81705. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81706. }
  81707. meshScaling = mesh.scaling.clone();
  81708. }
  81709. else {
  81710. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81711. }
  81712. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81713. var subMeshes = mesh.subMeshes;
  81714. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81715. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81716. vertices = [];
  81717. for (var j = 0; j < 3; j++) {
  81718. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81719. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81720. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81721. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81722. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81723. vertex = new Vertex(position, normal, uv);
  81724. vertices.push(vertex);
  81725. }
  81726. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81727. // To handle the case of degenerated triangle
  81728. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81729. if (polygon.plane)
  81730. polygons.push(polygon);
  81731. }
  81732. }
  81733. var csg = CSG.FromPolygons(polygons);
  81734. csg.matrix = matrix;
  81735. csg.position = meshPosition;
  81736. csg.rotation = meshRotation;
  81737. csg.scaling = meshScaling;
  81738. csg.rotationQuaternion = meshRotationQuaternion;
  81739. currentCSGMeshId++;
  81740. return csg;
  81741. };
  81742. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81743. CSG.FromPolygons = function (polygons) {
  81744. var csg = new CSG();
  81745. csg.polygons = polygons;
  81746. return csg;
  81747. };
  81748. CSG.prototype.clone = function () {
  81749. var csg = new CSG();
  81750. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81751. csg.copyTransformAttributes(this);
  81752. return csg;
  81753. };
  81754. CSG.prototype.union = function (csg) {
  81755. var a = new Node(this.clone().polygons);
  81756. var b = new Node(csg.clone().polygons);
  81757. a.clipTo(b);
  81758. b.clipTo(a);
  81759. b.invert();
  81760. b.clipTo(a);
  81761. b.invert();
  81762. a.build(b.allPolygons());
  81763. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81764. };
  81765. CSG.prototype.unionInPlace = function (csg) {
  81766. var a = new Node(this.polygons);
  81767. var b = new Node(csg.polygons);
  81768. a.clipTo(b);
  81769. b.clipTo(a);
  81770. b.invert();
  81771. b.clipTo(a);
  81772. b.invert();
  81773. a.build(b.allPolygons());
  81774. this.polygons = a.allPolygons();
  81775. };
  81776. CSG.prototype.subtract = function (csg) {
  81777. var a = new Node(this.clone().polygons);
  81778. var b = new Node(csg.clone().polygons);
  81779. a.invert();
  81780. a.clipTo(b);
  81781. b.clipTo(a);
  81782. b.invert();
  81783. b.clipTo(a);
  81784. b.invert();
  81785. a.build(b.allPolygons());
  81786. a.invert();
  81787. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81788. };
  81789. CSG.prototype.subtractInPlace = function (csg) {
  81790. var a = new Node(this.polygons);
  81791. var b = new Node(csg.polygons);
  81792. a.invert();
  81793. a.clipTo(b);
  81794. b.clipTo(a);
  81795. b.invert();
  81796. b.clipTo(a);
  81797. b.invert();
  81798. a.build(b.allPolygons());
  81799. a.invert();
  81800. this.polygons = a.allPolygons();
  81801. };
  81802. CSG.prototype.intersect = function (csg) {
  81803. var a = new Node(this.clone().polygons);
  81804. var b = new Node(csg.clone().polygons);
  81805. a.invert();
  81806. b.clipTo(a);
  81807. b.invert();
  81808. a.clipTo(b);
  81809. b.clipTo(a);
  81810. a.build(b.allPolygons());
  81811. a.invert();
  81812. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81813. };
  81814. CSG.prototype.intersectInPlace = function (csg) {
  81815. var a = new Node(this.polygons);
  81816. var b = new Node(csg.polygons);
  81817. a.invert();
  81818. b.clipTo(a);
  81819. b.invert();
  81820. a.clipTo(b);
  81821. b.clipTo(a);
  81822. a.build(b.allPolygons());
  81823. a.invert();
  81824. this.polygons = a.allPolygons();
  81825. };
  81826. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81827. // not modified.
  81828. CSG.prototype.inverse = function () {
  81829. var csg = this.clone();
  81830. csg.inverseInPlace();
  81831. return csg;
  81832. };
  81833. CSG.prototype.inverseInPlace = function () {
  81834. this.polygons.map(function (p) { p.flip(); });
  81835. };
  81836. // This is used to keep meshes transformations so they can be restored
  81837. // when we build back a Babylon Mesh
  81838. // NB : All CSG operations are performed in world coordinates
  81839. CSG.prototype.copyTransformAttributes = function (csg) {
  81840. this.matrix = csg.matrix;
  81841. this.position = csg.position;
  81842. this.rotation = csg.rotation;
  81843. this.scaling = csg.scaling;
  81844. this.rotationQuaternion = csg.rotationQuaternion;
  81845. return this;
  81846. };
  81847. // Build Raw mesh from CSG
  81848. // Coordinates here are in world space
  81849. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81850. var matrix = this.matrix.clone();
  81851. matrix.invert();
  81852. 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;
  81853. if (keepSubMeshes) {
  81854. // Sort Polygons, since subMeshes are indices range
  81855. polygons.sort(function (a, b) {
  81856. if (a.shared.meshId === b.shared.meshId) {
  81857. return a.shared.subMeshId - b.shared.subMeshId;
  81858. }
  81859. else {
  81860. return a.shared.meshId - b.shared.meshId;
  81861. }
  81862. });
  81863. }
  81864. for (var i = 0, il = polygons.length; i < il; i++) {
  81865. polygon = polygons[i];
  81866. // Building SubMeshes
  81867. if (!subMesh_dict[polygon.shared.meshId]) {
  81868. subMesh_dict[polygon.shared.meshId] = {};
  81869. }
  81870. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81871. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81872. indexStart: +Infinity,
  81873. indexEnd: -Infinity,
  81874. materialIndex: polygon.shared.materialIndex
  81875. };
  81876. }
  81877. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81878. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81879. polygonIndices[0] = 0;
  81880. polygonIndices[1] = j - 1;
  81881. polygonIndices[2] = j;
  81882. for (var k = 0; k < 3; k++) {
  81883. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81884. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81885. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81886. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81887. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81888. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81889. // Check if 2 points can be merged
  81890. if (!(typeof vertex_idx !== 'undefined' &&
  81891. normals[vertex_idx * 3] === localNormal.x &&
  81892. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81893. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81894. uvs[vertex_idx * 2] === uv.x &&
  81895. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81896. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81897. uvs.push(uv.x, uv.y);
  81898. normals.push(normal.x, normal.y, normal.z);
  81899. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81900. }
  81901. indices.push(vertex_idx);
  81902. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81903. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81904. currentIndex++;
  81905. }
  81906. }
  81907. }
  81908. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81909. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81910. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81911. mesh.setIndices(indices, null);
  81912. if (keepSubMeshes) {
  81913. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81914. var materialIndexOffset = 0, materialMaxIndex;
  81915. mesh.subMeshes = new Array();
  81916. for (var m in subMesh_dict) {
  81917. materialMaxIndex = -1;
  81918. for (var sm in subMesh_dict[m]) {
  81919. subMesh_obj = subMesh_dict[m][sm];
  81920. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81921. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81922. }
  81923. materialIndexOffset += ++materialMaxIndex;
  81924. }
  81925. }
  81926. return mesh;
  81927. };
  81928. // Build Mesh from CSG taking material and transforms into account
  81929. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81930. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81931. mesh.material = material;
  81932. mesh.position.copyFrom(this.position);
  81933. mesh.rotation.copyFrom(this.rotation);
  81934. if (this.rotationQuaternion) {
  81935. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81936. }
  81937. mesh.scaling.copyFrom(this.scaling);
  81938. mesh.computeWorldMatrix(true);
  81939. return mesh;
  81940. };
  81941. return CSG;
  81942. }());
  81943. BABYLON.CSG = CSG;
  81944. })(BABYLON || (BABYLON = {}));
  81945. //# sourceMappingURL=babylon.csg.js.map
  81946. var BABYLON;
  81947. (function (BABYLON) {
  81948. var LensFlare = /** @class */ (function () {
  81949. function LensFlare(size, position, color, imgUrl, system) {
  81950. this.size = size;
  81951. this.position = position;
  81952. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81953. this.color = color || new BABYLON.Color3(1, 1, 1);
  81954. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81955. this._system = system;
  81956. system.lensFlares.push(this);
  81957. }
  81958. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81959. return new LensFlare(size, position, color, imgUrl, system);
  81960. };
  81961. LensFlare.prototype.dispose = function () {
  81962. if (this.texture) {
  81963. this.texture.dispose();
  81964. }
  81965. // Remove from scene
  81966. var index = this._system.lensFlares.indexOf(this);
  81967. this._system.lensFlares.splice(index, 1);
  81968. };
  81969. ;
  81970. return LensFlare;
  81971. }());
  81972. BABYLON.LensFlare = LensFlare;
  81973. })(BABYLON || (BABYLON = {}));
  81974. //# sourceMappingURL=babylon.lensFlare.js.map
  81975. var BABYLON;
  81976. (function (BABYLON) {
  81977. var LensFlareSystem = /** @class */ (function () {
  81978. function LensFlareSystem(name, emitter, scene) {
  81979. this.name = name;
  81980. this.lensFlares = new Array();
  81981. this.borderLimit = 300;
  81982. this.viewportBorder = 0;
  81983. this.layerMask = 0x0FFFFFFF;
  81984. this._vertexBuffers = {};
  81985. this._isEnabled = true;
  81986. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81987. this._emitter = emitter;
  81988. this.id = name;
  81989. scene.lensFlareSystems.push(this);
  81990. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81991. var engine = scene.getEngine();
  81992. // VBO
  81993. var vertices = [];
  81994. vertices.push(1, 1);
  81995. vertices.push(-1, 1);
  81996. vertices.push(-1, -1);
  81997. vertices.push(1, -1);
  81998. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81999. // Indices
  82000. var indices = [];
  82001. indices.push(0);
  82002. indices.push(1);
  82003. indices.push(2);
  82004. indices.push(0);
  82005. indices.push(2);
  82006. indices.push(3);
  82007. this._indexBuffer = engine.createIndexBuffer(indices);
  82008. // Effects
  82009. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  82010. }
  82011. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  82012. get: function () {
  82013. return this._isEnabled;
  82014. },
  82015. set: function (value) {
  82016. this._isEnabled = value;
  82017. },
  82018. enumerable: true,
  82019. configurable: true
  82020. });
  82021. LensFlareSystem.prototype.getScene = function () {
  82022. return this._scene;
  82023. };
  82024. LensFlareSystem.prototype.getEmitter = function () {
  82025. return this._emitter;
  82026. };
  82027. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  82028. this._emitter = newEmitter;
  82029. };
  82030. LensFlareSystem.prototype.getEmitterPosition = function () {
  82031. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  82032. };
  82033. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  82034. var position = this.getEmitterPosition();
  82035. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  82036. this._positionX = position.x;
  82037. this._positionY = position.y;
  82038. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  82039. if (this.viewportBorder > 0) {
  82040. globalViewport.x -= this.viewportBorder;
  82041. globalViewport.y -= this.viewportBorder;
  82042. globalViewport.width += this.viewportBorder * 2;
  82043. globalViewport.height += this.viewportBorder * 2;
  82044. position.x += this.viewportBorder;
  82045. position.y += this.viewportBorder;
  82046. this._positionX += this.viewportBorder;
  82047. this._positionY += this.viewportBorder;
  82048. }
  82049. if (position.z > 0) {
  82050. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  82051. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  82052. return true;
  82053. }
  82054. return true;
  82055. }
  82056. return false;
  82057. };
  82058. LensFlareSystem.prototype._isVisible = function () {
  82059. if (!this._isEnabled || !this._scene.activeCamera) {
  82060. return false;
  82061. }
  82062. var emitterPosition = this.getEmitterPosition();
  82063. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  82064. var distance = direction.length();
  82065. direction.normalize();
  82066. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  82067. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  82068. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  82069. };
  82070. LensFlareSystem.prototype.render = function () {
  82071. if (!this._effect.isReady() || !this._scene.activeCamera)
  82072. return false;
  82073. var engine = this._scene.getEngine();
  82074. var viewport = this._scene.activeCamera.viewport;
  82075. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  82076. // Position
  82077. if (!this.computeEffectivePosition(globalViewport)) {
  82078. return false;
  82079. }
  82080. // Visibility
  82081. if (!this._isVisible()) {
  82082. return false;
  82083. }
  82084. // Intensity
  82085. var awayX;
  82086. var awayY;
  82087. if (this._positionX < this.borderLimit + globalViewport.x) {
  82088. awayX = this.borderLimit + globalViewport.x - this._positionX;
  82089. }
  82090. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  82091. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  82092. }
  82093. else {
  82094. awayX = 0;
  82095. }
  82096. if (this._positionY < this.borderLimit + globalViewport.y) {
  82097. awayY = this.borderLimit + globalViewport.y - this._positionY;
  82098. }
  82099. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  82100. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  82101. }
  82102. else {
  82103. awayY = 0;
  82104. }
  82105. var away = (awayX > awayY) ? awayX : awayY;
  82106. away -= this.viewportBorder;
  82107. if (away > this.borderLimit) {
  82108. away = this.borderLimit;
  82109. }
  82110. var intensity = 1.0 - (away / this.borderLimit);
  82111. if (intensity < 0) {
  82112. return false;
  82113. }
  82114. if (intensity > 1.0) {
  82115. intensity = 1.0;
  82116. }
  82117. if (this.viewportBorder > 0) {
  82118. globalViewport.x += this.viewportBorder;
  82119. globalViewport.y += this.viewportBorder;
  82120. globalViewport.width -= this.viewportBorder * 2;
  82121. globalViewport.height -= this.viewportBorder * 2;
  82122. this._positionX -= this.viewportBorder;
  82123. this._positionY -= this.viewportBorder;
  82124. }
  82125. // Position
  82126. var centerX = globalViewport.x + globalViewport.width / 2;
  82127. var centerY = globalViewport.y + globalViewport.height / 2;
  82128. var distX = centerX - this._positionX;
  82129. var distY = centerY - this._positionY;
  82130. // Effects
  82131. engine.enableEffect(this._effect);
  82132. engine.setState(false);
  82133. engine.setDepthBuffer(false);
  82134. // VBOs
  82135. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  82136. // Flares
  82137. for (var index = 0; index < this.lensFlares.length; index++) {
  82138. var flare = this.lensFlares[index];
  82139. engine.setAlphaMode(flare.alphaMode);
  82140. var x = centerX - (distX * flare.position);
  82141. var y = centerY - (distY * flare.position);
  82142. var cw = flare.size;
  82143. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  82144. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  82145. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  82146. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  82147. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  82148. // Texture
  82149. this._effect.setTexture("textureSampler", flare.texture);
  82150. // Color
  82151. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  82152. // Draw order
  82153. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  82154. }
  82155. engine.setDepthBuffer(true);
  82156. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  82157. return true;
  82158. };
  82159. LensFlareSystem.prototype.dispose = function () {
  82160. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82161. if (vertexBuffer) {
  82162. vertexBuffer.dispose();
  82163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82164. }
  82165. if (this._indexBuffer) {
  82166. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82167. this._indexBuffer = null;
  82168. }
  82169. while (this.lensFlares.length) {
  82170. this.lensFlares[0].dispose();
  82171. }
  82172. // Remove from scene
  82173. var index = this._scene.lensFlareSystems.indexOf(this);
  82174. this._scene.lensFlareSystems.splice(index, 1);
  82175. };
  82176. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  82177. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  82178. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  82179. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  82180. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  82181. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  82182. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  82183. var parsedFlare = parsedLensFlareSystem.flares[index];
  82184. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  82185. }
  82186. return lensFlareSystem;
  82187. };
  82188. LensFlareSystem.prototype.serialize = function () {
  82189. var serializationObject = {};
  82190. serializationObject.id = this.id;
  82191. serializationObject.name = this.name;
  82192. serializationObject.emitterId = this.getEmitter().id;
  82193. serializationObject.borderLimit = this.borderLimit;
  82194. serializationObject.flares = [];
  82195. for (var index = 0; index < this.lensFlares.length; index++) {
  82196. var flare = this.lensFlares[index];
  82197. serializationObject.flares.push({
  82198. size: flare.size,
  82199. position: flare.position,
  82200. color: flare.color.asArray(),
  82201. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  82202. });
  82203. }
  82204. return serializationObject;
  82205. };
  82206. return LensFlareSystem;
  82207. }());
  82208. BABYLON.LensFlareSystem = LensFlareSystem;
  82209. })(BABYLON || (BABYLON = {}));
  82210. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  82211. var BABYLON;
  82212. (function (BABYLON) {
  82213. /**
  82214. * This is a holder class for the physics joint created by the physics plugin.
  82215. * It holds a set of functions to control the underlying joint.
  82216. */
  82217. var PhysicsJoint = /** @class */ (function () {
  82218. function PhysicsJoint(type, jointData) {
  82219. this.type = type;
  82220. this.jointData = jointData;
  82221. jointData.nativeParams = jointData.nativeParams || {};
  82222. }
  82223. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  82224. get: function () {
  82225. return this._physicsJoint;
  82226. },
  82227. set: function (newJoint) {
  82228. if (this._physicsJoint) {
  82229. //remove from the wolrd
  82230. }
  82231. this._physicsJoint = newJoint;
  82232. },
  82233. enumerable: true,
  82234. configurable: true
  82235. });
  82236. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  82237. set: function (physicsPlugin) {
  82238. this._physicsPlugin = physicsPlugin;
  82239. },
  82240. enumerable: true,
  82241. configurable: true
  82242. });
  82243. /**
  82244. * Execute a function that is physics-plugin specific.
  82245. * @param {Function} func the function that will be executed.
  82246. * It accepts two parameters: the physics world and the physics joint.
  82247. */
  82248. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  82249. func(this._physicsPlugin.world, this._physicsJoint);
  82250. };
  82251. //TODO check if the native joints are the same
  82252. //Joint Types
  82253. PhysicsJoint.DistanceJoint = 0;
  82254. PhysicsJoint.HingeJoint = 1;
  82255. PhysicsJoint.BallAndSocketJoint = 2;
  82256. PhysicsJoint.WheelJoint = 3;
  82257. PhysicsJoint.SliderJoint = 4;
  82258. //OIMO
  82259. PhysicsJoint.PrismaticJoint = 5;
  82260. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  82261. PhysicsJoint.UniversalJoint = 6;
  82262. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  82263. //Cannon
  82264. //Similar to a Ball-Joint. Different in params
  82265. PhysicsJoint.PointToPointJoint = 8;
  82266. //Cannon only at the moment
  82267. PhysicsJoint.SpringJoint = 9;
  82268. PhysicsJoint.LockJoint = 10;
  82269. return PhysicsJoint;
  82270. }());
  82271. BABYLON.PhysicsJoint = PhysicsJoint;
  82272. /**
  82273. * A class representing a physics distance joint.
  82274. */
  82275. var DistanceJoint = /** @class */ (function (_super) {
  82276. __extends(DistanceJoint, _super);
  82277. function DistanceJoint(jointData) {
  82278. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  82279. }
  82280. /**
  82281. * Update the predefined distance.
  82282. */
  82283. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  82284. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  82285. };
  82286. return DistanceJoint;
  82287. }(PhysicsJoint));
  82288. BABYLON.DistanceJoint = DistanceJoint;
  82289. var MotorEnabledJoint = /** @class */ (function (_super) {
  82290. __extends(MotorEnabledJoint, _super);
  82291. function MotorEnabledJoint(type, jointData) {
  82292. return _super.call(this, type, jointData) || this;
  82293. }
  82294. /**
  82295. * Set the motor values.
  82296. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82297. * @param {number} force the force to apply
  82298. * @param {number} maxForce max force for this motor.
  82299. */
  82300. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  82301. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82302. };
  82303. /**
  82304. * Set the motor's limits.
  82305. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82306. */
  82307. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82308. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82309. };
  82310. return MotorEnabledJoint;
  82311. }(PhysicsJoint));
  82312. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  82313. /**
  82314. * This class represents a single hinge physics joint
  82315. */
  82316. var HingeJoint = /** @class */ (function (_super) {
  82317. __extends(HingeJoint, _super);
  82318. function HingeJoint(jointData) {
  82319. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  82320. }
  82321. /**
  82322. * Set the motor values.
  82323. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82324. * @param {number} force the force to apply
  82325. * @param {number} maxForce max force for this motor.
  82326. */
  82327. HingeJoint.prototype.setMotor = function (force, maxForce) {
  82328. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  82329. };
  82330. /**
  82331. * Set the motor's limits.
  82332. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82333. */
  82334. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  82335. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  82336. };
  82337. return HingeJoint;
  82338. }(MotorEnabledJoint));
  82339. BABYLON.HingeJoint = HingeJoint;
  82340. /**
  82341. * This class represents a dual hinge physics joint (same as wheel joint)
  82342. */
  82343. var Hinge2Joint = /** @class */ (function (_super) {
  82344. __extends(Hinge2Joint, _super);
  82345. function Hinge2Joint(jointData) {
  82346. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  82347. }
  82348. /**
  82349. * Set the motor values.
  82350. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82351. * @param {number} force the force to apply
  82352. * @param {number} maxForce max force for this motor.
  82353. * @param {motorIndex} the motor's index, 0 or 1.
  82354. */
  82355. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  82356. if (motorIndex === void 0) { motorIndex = 0; }
  82357. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  82358. };
  82359. /**
  82360. * Set the motor limits.
  82361. * Attention, this function is plugin specific. Engines won't react 100% the same.
  82362. * @param {number} upperLimit the upper limit
  82363. * @param {number} lowerLimit lower limit
  82364. * @param {motorIndex} the motor's index, 0 or 1.
  82365. */
  82366. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  82367. if (motorIndex === void 0) { motorIndex = 0; }
  82368. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  82369. };
  82370. return Hinge2Joint;
  82371. }(MotorEnabledJoint));
  82372. BABYLON.Hinge2Joint = Hinge2Joint;
  82373. })(BABYLON || (BABYLON = {}));
  82374. //# sourceMappingURL=babylon.physicsJoint.js.map
  82375. var BABYLON;
  82376. (function (BABYLON) {
  82377. var PhysicsImpostor = /** @class */ (function () {
  82378. function PhysicsImpostor(object, type, _options, _scene) {
  82379. if (_options === void 0) { _options = { mass: 0 }; }
  82380. var _this = this;
  82381. this.object = object;
  82382. this.type = type;
  82383. this._options = _options;
  82384. this._scene = _scene;
  82385. this._bodyUpdateRequired = false;
  82386. this._onBeforePhysicsStepCallbacks = new Array();
  82387. this._onAfterPhysicsStepCallbacks = new Array();
  82388. this._onPhysicsCollideCallbacks = [];
  82389. this._deltaPosition = BABYLON.Vector3.Zero();
  82390. this._isDisposed = false;
  82391. //temp variables for parent rotation calculations
  82392. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  82393. this._tmpQuat = new BABYLON.Quaternion();
  82394. this._tmpQuat2 = new BABYLON.Quaternion();
  82395. /**
  82396. * this function is executed by the physics engine.
  82397. */
  82398. this.beforeStep = function () {
  82399. if (!_this._physicsEngine) {
  82400. return;
  82401. }
  82402. _this.object.translate(_this._deltaPosition, -1);
  82403. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  82404. _this.object.computeWorldMatrix(false);
  82405. if (_this.object.parent && _this.object.rotationQuaternion) {
  82406. _this.getParentsRotation();
  82407. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  82408. }
  82409. else {
  82410. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  82411. }
  82412. if (!_this._options.disableBidirectionalTransformation) {
  82413. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  82414. }
  82415. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  82416. func(_this);
  82417. });
  82418. };
  82419. /**
  82420. * this function is executed by the physics engine.
  82421. */
  82422. this.afterStep = function () {
  82423. if (!_this._physicsEngine) {
  82424. return;
  82425. }
  82426. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  82427. func(_this);
  82428. });
  82429. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  82430. // object has now its world rotation. needs to be converted to local.
  82431. if (_this.object.parent && _this.object.rotationQuaternion) {
  82432. _this.getParentsRotation();
  82433. _this._tmpQuat.conjugateInPlace();
  82434. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  82435. }
  82436. // take the position set and make it the absolute position of this object.
  82437. _this.object.setAbsolutePosition(_this.object.position);
  82438. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  82439. _this.object.translate(_this._deltaPosition, 1);
  82440. };
  82441. /**
  82442. * Legacy collision detection event support
  82443. */
  82444. this.onCollideEvent = null;
  82445. //event and body object due to cannon's event-based architecture.
  82446. this.onCollide = function (e) {
  82447. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  82448. return;
  82449. }
  82450. if (!_this._physicsEngine) {
  82451. return;
  82452. }
  82453. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  82454. if (otherImpostor) {
  82455. // Legacy collision detection event support
  82456. if (_this.onCollideEvent) {
  82457. _this.onCollideEvent(_this, otherImpostor);
  82458. }
  82459. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  82460. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  82461. }).forEach(function (obj) {
  82462. obj.callback(_this, otherImpostor);
  82463. });
  82464. }
  82465. };
  82466. //sanity check!
  82467. if (!this.object) {
  82468. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  82469. return;
  82470. }
  82471. //legacy support for old syntax.
  82472. if (!this._scene && object.getScene) {
  82473. this._scene = object.getScene();
  82474. }
  82475. if (!this._scene) {
  82476. return;
  82477. }
  82478. this._physicsEngine = this._scene.getPhysicsEngine();
  82479. if (!this._physicsEngine) {
  82480. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  82481. }
  82482. else {
  82483. //set the object's quaternion, if not set
  82484. if (!this.object.rotationQuaternion) {
  82485. if (this.object.rotation) {
  82486. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  82487. }
  82488. else {
  82489. this.object.rotationQuaternion = new BABYLON.Quaternion();
  82490. }
  82491. }
  82492. //default options params
  82493. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  82494. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  82495. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  82496. this._joints = [];
  82497. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  82498. if (!this.object.parent || this._options.ignoreParent) {
  82499. this._init();
  82500. }
  82501. else if (this.object.parent.physicsImpostor) {
  82502. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  82503. }
  82504. }
  82505. }
  82506. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  82507. get: function () {
  82508. return this._isDisposed;
  82509. },
  82510. enumerable: true,
  82511. configurable: true
  82512. });
  82513. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  82514. get: function () {
  82515. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  82516. },
  82517. set: function (value) {
  82518. this.setMass(value);
  82519. },
  82520. enumerable: true,
  82521. configurable: true
  82522. });
  82523. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  82524. get: function () {
  82525. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  82526. },
  82527. set: function (value) {
  82528. if (!this._physicsEngine) {
  82529. return;
  82530. }
  82531. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  82532. },
  82533. enumerable: true,
  82534. configurable: true
  82535. });
  82536. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  82537. get: function () {
  82538. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  82539. },
  82540. set: function (value) {
  82541. if (!this._physicsEngine) {
  82542. return;
  82543. }
  82544. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82545. },
  82546. enumerable: true,
  82547. configurable: true
  82548. });
  82549. /**
  82550. * This function will completly initialize this impostor.
  82551. * It will create a new body - but only if this mesh has no parent.
  82552. * If it has, this impostor will not be used other than to define the impostor
  82553. * of the child mesh.
  82554. */
  82555. PhysicsImpostor.prototype._init = function () {
  82556. if (!this._physicsEngine) {
  82557. return;
  82558. }
  82559. this._physicsEngine.removeImpostor(this);
  82560. this.physicsBody = null;
  82561. this._parent = this._parent || this._getPhysicsParent();
  82562. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82563. this._physicsEngine.addImpostor(this);
  82564. }
  82565. };
  82566. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82567. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82568. var parentMesh = this.object.parent;
  82569. return parentMesh.physicsImpostor;
  82570. }
  82571. return null;
  82572. };
  82573. /**
  82574. * Should a new body be generated.
  82575. */
  82576. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82577. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82578. };
  82579. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82580. this.forceUpdate();
  82581. };
  82582. /**
  82583. * Force a regeneration of this or the parent's impostor's body.
  82584. * Use under cautious - This will remove all joints already implemented.
  82585. */
  82586. PhysicsImpostor.prototype.forceUpdate = function () {
  82587. this._init();
  82588. if (this.parent && !this._options.ignoreParent) {
  82589. this.parent.forceUpdate();
  82590. }
  82591. };
  82592. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82593. /*public get mesh(): AbstractMesh {
  82594. return this._mesh;
  82595. }*/
  82596. /**
  82597. * Gets the body that holds this impostor. Either its own, or its parent.
  82598. */
  82599. get: function () {
  82600. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82601. },
  82602. /**
  82603. * Set the physics body. Used mainly by the physics engine/plugin
  82604. */
  82605. set: function (physicsBody) {
  82606. if (this._physicsBody && this._physicsEngine) {
  82607. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82608. }
  82609. this._physicsBody = physicsBody;
  82610. this.resetUpdateFlags();
  82611. },
  82612. enumerable: true,
  82613. configurable: true
  82614. });
  82615. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82616. get: function () {
  82617. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82618. },
  82619. set: function (value) {
  82620. this._parent = value;
  82621. },
  82622. enumerable: true,
  82623. configurable: true
  82624. });
  82625. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82626. this._bodyUpdateRequired = false;
  82627. };
  82628. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82629. if (this.object.getBoundingInfo) {
  82630. var q = this.object.rotationQuaternion;
  82631. //reset rotation
  82632. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82633. //calculate the world matrix with no rotation
  82634. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82635. var boundingInfo = this.object.getBoundingInfo();
  82636. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82637. //bring back the rotation
  82638. this.object.rotationQuaternion = q;
  82639. //calculate the world matrix with the new rotation
  82640. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82641. return size;
  82642. }
  82643. else {
  82644. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82645. }
  82646. };
  82647. PhysicsImpostor.prototype.getObjectCenter = function () {
  82648. if (this.object.getBoundingInfo) {
  82649. var boundingInfo = this.object.getBoundingInfo();
  82650. return boundingInfo.boundingBox.centerWorld;
  82651. }
  82652. else {
  82653. return this.object.position;
  82654. }
  82655. };
  82656. /**
  82657. * Get a specific parametes from the options parameter.
  82658. */
  82659. PhysicsImpostor.prototype.getParam = function (paramName) {
  82660. return this._options[paramName];
  82661. };
  82662. /**
  82663. * Sets a specific parameter in the options given to the physics plugin
  82664. */
  82665. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82666. this._options[paramName] = value;
  82667. this._bodyUpdateRequired = true;
  82668. };
  82669. /**
  82670. * Specifically change the body's mass option. Won't recreate the physics body object
  82671. */
  82672. PhysicsImpostor.prototype.setMass = function (mass) {
  82673. if (this.getParam("mass") !== mass) {
  82674. this.setParam("mass", mass);
  82675. }
  82676. if (this._physicsEngine) {
  82677. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82678. }
  82679. };
  82680. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82681. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82682. };
  82683. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82684. if (this._physicsEngine) {
  82685. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82686. }
  82687. };
  82688. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82689. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82690. };
  82691. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82692. if (this._physicsEngine) {
  82693. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82694. }
  82695. };
  82696. /**
  82697. * Execute a function with the physics plugin native code.
  82698. * Provide a function the will have two variables - the world object and the physics body object.
  82699. */
  82700. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82701. if (this._physicsEngine) {
  82702. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82703. }
  82704. };
  82705. /**
  82706. * Register a function that will be executed before the physics world is stepping forward.
  82707. */
  82708. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82709. this._onBeforePhysicsStepCallbacks.push(func);
  82710. };
  82711. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82712. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82713. if (index > -1) {
  82714. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82715. }
  82716. else {
  82717. BABYLON.Tools.Warn("Function to remove was not found");
  82718. }
  82719. };
  82720. /**
  82721. * Register a function that will be executed after the physics step
  82722. */
  82723. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82724. this._onAfterPhysicsStepCallbacks.push(func);
  82725. };
  82726. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82727. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82728. if (index > -1) {
  82729. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82730. }
  82731. else {
  82732. BABYLON.Tools.Warn("Function to remove was not found");
  82733. }
  82734. };
  82735. /**
  82736. * register a function that will be executed when this impostor collides against a different body.
  82737. */
  82738. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82739. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82740. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82741. };
  82742. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82743. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82744. var index = -1;
  82745. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  82746. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  82747. // chcek the arrays match
  82748. var sameList = cbDef.otherImpostors.every(function (impostor) {
  82749. return collidedAgainstList.indexOf(impostor) > -1;
  82750. });
  82751. if (sameList) {
  82752. index = idx;
  82753. }
  82754. return sameList;
  82755. }
  82756. return false;
  82757. });
  82758. if (found) {
  82759. this._onPhysicsCollideCallbacks.splice(index, 1);
  82760. }
  82761. else {
  82762. BABYLON.Tools.Warn("Function to remove was not found");
  82763. }
  82764. };
  82765. PhysicsImpostor.prototype.getParentsRotation = function () {
  82766. var parent = this.object.parent;
  82767. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82768. while (parent) {
  82769. if (parent.rotationQuaternion) {
  82770. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82771. }
  82772. else {
  82773. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82774. }
  82775. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82776. parent = parent.parent;
  82777. }
  82778. return this._tmpQuat;
  82779. };
  82780. /**
  82781. * Apply a force
  82782. */
  82783. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82784. if (this._physicsEngine) {
  82785. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82786. }
  82787. return this;
  82788. };
  82789. /**
  82790. * Apply an impulse
  82791. */
  82792. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82793. if (this._physicsEngine) {
  82794. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82795. }
  82796. return this;
  82797. };
  82798. /**
  82799. * A help function to create a joint.
  82800. */
  82801. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82802. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82803. this.addJoint(otherImpostor, joint);
  82804. return this;
  82805. };
  82806. /**
  82807. * Add a joint to this impostor with a different impostor.
  82808. */
  82809. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82810. this._joints.push({
  82811. otherImpostor: otherImpostor,
  82812. joint: joint
  82813. });
  82814. if (this._physicsEngine) {
  82815. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82816. }
  82817. return this;
  82818. };
  82819. /**
  82820. * Will keep this body still, in a sleep mode.
  82821. */
  82822. PhysicsImpostor.prototype.sleep = function () {
  82823. if (this._physicsEngine) {
  82824. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82825. }
  82826. return this;
  82827. };
  82828. /**
  82829. * Wake the body up.
  82830. */
  82831. PhysicsImpostor.prototype.wakeUp = function () {
  82832. if (this._physicsEngine) {
  82833. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82834. }
  82835. return this;
  82836. };
  82837. PhysicsImpostor.prototype.clone = function (newObject) {
  82838. if (!newObject)
  82839. return null;
  82840. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82841. };
  82842. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82843. var _this = this;
  82844. //no dispose if no physics engine is available.
  82845. if (!this._physicsEngine) {
  82846. return;
  82847. }
  82848. this._joints.forEach(function (j) {
  82849. if (_this._physicsEngine) {
  82850. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82851. }
  82852. });
  82853. //dispose the physics body
  82854. this._physicsEngine.removeImpostor(this);
  82855. if (this.parent) {
  82856. this.parent.forceUpdate();
  82857. }
  82858. else {
  82859. /*this._object.getChildMeshes().forEach(function(mesh) {
  82860. if (mesh.physicsImpostor) {
  82861. if (disposeChildren) {
  82862. mesh.physicsImpostor.dispose();
  82863. mesh.physicsImpostor = null;
  82864. }
  82865. }
  82866. })*/
  82867. }
  82868. this._isDisposed = true;
  82869. };
  82870. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82871. this._deltaPosition.copyFrom(position);
  82872. };
  82873. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82874. if (!this._deltaRotation) {
  82875. this._deltaRotation = new BABYLON.Quaternion();
  82876. }
  82877. this._deltaRotation.copyFrom(rotation);
  82878. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82879. };
  82880. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82881. if (this._physicsEngine) {
  82882. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82883. }
  82884. return this;
  82885. };
  82886. PhysicsImpostor.prototype.getRadius = function () {
  82887. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82888. };
  82889. /**
  82890. * Sync a bone with this impostor
  82891. * @param bone The bone to sync to the impostor.
  82892. * @param boneMesh The mesh that the bone is influencing.
  82893. * @param jointPivot The pivot of the joint / bone in local space.
  82894. * @param distToJoint Optional distance from the impostor to the joint.
  82895. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82896. */
  82897. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82898. var tempVec = PhysicsImpostor._tmpVecs[0];
  82899. var mesh = this.object;
  82900. if (mesh.rotationQuaternion) {
  82901. if (adjustRotation) {
  82902. var tempQuat = PhysicsImpostor._tmpQuat;
  82903. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82904. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82905. }
  82906. else {
  82907. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82908. }
  82909. }
  82910. tempVec.x = 0;
  82911. tempVec.y = 0;
  82912. tempVec.z = 0;
  82913. if (jointPivot) {
  82914. tempVec.x = jointPivot.x;
  82915. tempVec.y = jointPivot.y;
  82916. tempVec.z = jointPivot.z;
  82917. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82918. if (distToJoint === undefined || distToJoint === null) {
  82919. distToJoint = jointPivot.length();
  82920. }
  82921. tempVec.x *= distToJoint;
  82922. tempVec.y *= distToJoint;
  82923. tempVec.z *= distToJoint;
  82924. }
  82925. if (bone.getParent()) {
  82926. tempVec.addInPlace(mesh.getAbsolutePosition());
  82927. bone.setAbsolutePosition(tempVec, boneMesh);
  82928. }
  82929. else {
  82930. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82931. boneMesh.position.x -= tempVec.x;
  82932. boneMesh.position.y -= tempVec.y;
  82933. boneMesh.position.z -= tempVec.z;
  82934. }
  82935. };
  82936. /**
  82937. * Sync impostor to a bone
  82938. * @param bone The bone that the impostor will be synced to.
  82939. * @param boneMesh The mesh that the bone is influencing.
  82940. * @param jointPivot The pivot of the joint / bone in local space.
  82941. * @param distToJoint Optional distance from the impostor to the joint.
  82942. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82943. * @param boneAxis Optional vector3 axis the bone is aligned with
  82944. */
  82945. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82946. var mesh = this.object;
  82947. if (mesh.rotationQuaternion) {
  82948. if (adjustRotation) {
  82949. var tempQuat = PhysicsImpostor._tmpQuat;
  82950. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82951. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82952. }
  82953. else {
  82954. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82955. }
  82956. }
  82957. var pos = PhysicsImpostor._tmpVecs[0];
  82958. var boneDir = PhysicsImpostor._tmpVecs[1];
  82959. if (!boneAxis) {
  82960. boneAxis = PhysicsImpostor._tmpVecs[2];
  82961. boneAxis.x = 0;
  82962. boneAxis.y = 1;
  82963. boneAxis.z = 0;
  82964. }
  82965. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82966. bone.getAbsolutePositionToRef(boneMesh, pos);
  82967. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82968. distToJoint = jointPivot.length();
  82969. }
  82970. if (distToJoint !== undefined && distToJoint !== null) {
  82971. pos.x += boneDir.x * distToJoint;
  82972. pos.y += boneDir.y * distToJoint;
  82973. pos.z += boneDir.z * distToJoint;
  82974. }
  82975. mesh.setAbsolutePosition(pos);
  82976. };
  82977. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82978. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82979. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82980. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82981. //Impostor types
  82982. PhysicsImpostor.NoImpostor = 0;
  82983. PhysicsImpostor.SphereImpostor = 1;
  82984. PhysicsImpostor.BoxImpostor = 2;
  82985. PhysicsImpostor.PlaneImpostor = 3;
  82986. PhysicsImpostor.MeshImpostor = 4;
  82987. PhysicsImpostor.CylinderImpostor = 7;
  82988. PhysicsImpostor.ParticleImpostor = 8;
  82989. PhysicsImpostor.HeightmapImpostor = 9;
  82990. return PhysicsImpostor;
  82991. }());
  82992. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82993. })(BABYLON || (BABYLON = {}));
  82994. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82995. var BABYLON;
  82996. (function (BABYLON) {
  82997. var PhysicsEngine = /** @class */ (function () {
  82998. function PhysicsEngine(gravity, _physicsPlugin) {
  82999. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  83000. this._physicsPlugin = _physicsPlugin;
  83001. //new methods and parameters
  83002. this._impostors = [];
  83003. this._joints = [];
  83004. if (!this._physicsPlugin.isSupported()) {
  83005. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  83006. + "Please make sure it is included.");
  83007. }
  83008. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  83009. this.setGravity(gravity);
  83010. this.setTimeStep();
  83011. }
  83012. PhysicsEngine.prototype.setGravity = function (gravity) {
  83013. this.gravity = gravity;
  83014. this._physicsPlugin.setGravity(this.gravity);
  83015. };
  83016. /**
  83017. * Set the time step of the physics engine.
  83018. * default is 1/60.
  83019. * To slow it down, enter 1/600 for example.
  83020. * To speed it up, 1/30
  83021. * @param {number} newTimeStep the new timestep to apply to this world.
  83022. */
  83023. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  83024. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  83025. this._physicsPlugin.setTimeStep(newTimeStep);
  83026. };
  83027. /**
  83028. * Get the time step of the physics engine.
  83029. */
  83030. PhysicsEngine.prototype.getTimeStep = function () {
  83031. return this._physicsPlugin.getTimeStep();
  83032. };
  83033. PhysicsEngine.prototype.dispose = function () {
  83034. this._impostors.forEach(function (impostor) {
  83035. impostor.dispose();
  83036. });
  83037. this._physicsPlugin.dispose();
  83038. };
  83039. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  83040. return this._physicsPlugin.name;
  83041. };
  83042. /**
  83043. * Adding a new impostor for the impostor tracking.
  83044. * This will be done by the impostor itself.
  83045. * @param {PhysicsImpostor} impostor the impostor to add
  83046. */
  83047. PhysicsEngine.prototype.addImpostor = function (impostor) {
  83048. impostor.uniqueId = this._impostors.push(impostor);
  83049. //if no parent, generate the body
  83050. if (!impostor.parent) {
  83051. this._physicsPlugin.generatePhysicsBody(impostor);
  83052. }
  83053. };
  83054. /**
  83055. * Remove an impostor from the engine.
  83056. * This impostor and its mesh will not longer be updated by the physics engine.
  83057. * @param {PhysicsImpostor} impostor the impostor to remove
  83058. */
  83059. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  83060. var index = this._impostors.indexOf(impostor);
  83061. if (index > -1) {
  83062. var removed = this._impostors.splice(index, 1);
  83063. //Is it needed?
  83064. if (removed.length) {
  83065. //this will also remove it from the world.
  83066. removed[0].physicsBody = null;
  83067. }
  83068. }
  83069. };
  83070. /**
  83071. * Add a joint to the physics engine
  83072. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  83073. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  83074. * @param {PhysicsJoint} the joint that will connect both impostors.
  83075. */
  83076. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  83077. var impostorJoint = {
  83078. mainImpostor: mainImpostor,
  83079. connectedImpostor: connectedImpostor,
  83080. joint: joint
  83081. };
  83082. joint.physicsPlugin = this._physicsPlugin;
  83083. this._joints.push(impostorJoint);
  83084. this._physicsPlugin.generateJoint(impostorJoint);
  83085. };
  83086. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  83087. var matchingJoints = this._joints.filter(function (impostorJoint) {
  83088. return (impostorJoint.connectedImpostor === connectedImpostor
  83089. && impostorJoint.joint === joint
  83090. && impostorJoint.mainImpostor === mainImpostor);
  83091. });
  83092. if (matchingJoints.length) {
  83093. this._physicsPlugin.removeJoint(matchingJoints[0]);
  83094. //TODO remove it from the list as well
  83095. }
  83096. };
  83097. /**
  83098. * Called by the scene. no need to call it.
  83099. */
  83100. PhysicsEngine.prototype._step = function (delta) {
  83101. var _this = this;
  83102. //check if any mesh has no body / requires an update
  83103. this._impostors.forEach(function (impostor) {
  83104. if (impostor.isBodyInitRequired()) {
  83105. _this._physicsPlugin.generatePhysicsBody(impostor);
  83106. }
  83107. });
  83108. if (delta > 0.1) {
  83109. delta = 0.1;
  83110. }
  83111. else if (delta <= 0) {
  83112. delta = 1.0 / 60.0;
  83113. }
  83114. this._physicsPlugin.executeStep(delta, this._impostors);
  83115. };
  83116. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  83117. return this._physicsPlugin;
  83118. };
  83119. PhysicsEngine.prototype.getImpostors = function () {
  83120. return this._impostors;
  83121. };
  83122. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  83123. for (var i = 0; i < this._impostors.length; ++i) {
  83124. if (this._impostors[i].object === object) {
  83125. return this._impostors[i];
  83126. }
  83127. }
  83128. return null;
  83129. };
  83130. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  83131. for (var i = 0; i < this._impostors.length; ++i) {
  83132. if (this._impostors[i].physicsBody === body) {
  83133. return this._impostors[i];
  83134. }
  83135. }
  83136. return null;
  83137. };
  83138. // Statics
  83139. PhysicsEngine.Epsilon = 0.001;
  83140. return PhysicsEngine;
  83141. }());
  83142. BABYLON.PhysicsEngine = PhysicsEngine;
  83143. })(BABYLON || (BABYLON = {}));
  83144. //# sourceMappingURL=babylon.physicsEngine.js.map
  83145. var BABYLON;
  83146. (function (BABYLON) {
  83147. var PhysicsHelper = /** @class */ (function () {
  83148. function PhysicsHelper(scene) {
  83149. this._scene = scene;
  83150. this._physicsEngine = this._scene.getPhysicsEngine();
  83151. if (!this._physicsEngine) {
  83152. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  83153. }
  83154. }
  83155. /**
  83156. * @param {Vector3} origin the origin of the explosion
  83157. * @param {number} radius the explosion radius
  83158. * @param {number} strength the explosion strength
  83159. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83160. */
  83161. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  83162. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83163. if (!this._physicsEngine) {
  83164. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  83165. return null;
  83166. }
  83167. var impostors = this._physicsEngine.getImpostors();
  83168. if (impostors.length === 0) {
  83169. return null;
  83170. }
  83171. var event = new PhysicsRadialExplosionEvent(this._scene);
  83172. impostors.forEach(function (impostor) {
  83173. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83174. if (!impostorForceAndContactPoint) {
  83175. return;
  83176. }
  83177. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83178. });
  83179. event.dispose(false);
  83180. return event;
  83181. };
  83182. /**
  83183. * @param {Vector3} origin the origin of the explosion
  83184. * @param {number} radius the explosion radius
  83185. * @param {number} strength the explosion strength
  83186. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83187. */
  83188. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  83189. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83190. if (!this._physicsEngine) {
  83191. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83192. return null;
  83193. }
  83194. var impostors = this._physicsEngine.getImpostors();
  83195. if (impostors.length === 0) {
  83196. return null;
  83197. }
  83198. var event = new PhysicsRadialExplosionEvent(this._scene);
  83199. impostors.forEach(function (impostor) {
  83200. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  83201. if (!impostorForceAndContactPoint) {
  83202. return;
  83203. }
  83204. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83205. });
  83206. event.dispose(false);
  83207. return event;
  83208. };
  83209. /**
  83210. * @param {Vector3} origin the origin of the explosion
  83211. * @param {number} radius the explosion radius
  83212. * @param {number} strength the explosion strength
  83213. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  83214. */
  83215. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  83216. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83217. if (!this._physicsEngine) {
  83218. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83219. return null;
  83220. }
  83221. var impostors = this._physicsEngine.getImpostors();
  83222. if (impostors.length === 0) {
  83223. return null;
  83224. }
  83225. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  83226. event.dispose(false);
  83227. return event;
  83228. };
  83229. /**
  83230. * @param {Vector3} origin the origin of the updraft
  83231. * @param {number} radius the radius of the updraft
  83232. * @param {number} strength the strength of the updraft
  83233. * @param {number} height the height of the updraft
  83234. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  83235. */
  83236. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  83237. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  83238. if (!this._physicsEngine) {
  83239. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83240. return null;
  83241. }
  83242. if (this._physicsEngine.getImpostors().length === 0) {
  83243. return null;
  83244. }
  83245. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  83246. event.dispose(false);
  83247. return event;
  83248. };
  83249. /**
  83250. * @param {Vector3} origin the of the vortex
  83251. * @param {number} radius the radius of the vortex
  83252. * @param {number} strength the strength of the vortex
  83253. * @param {number} height the height of the vortex
  83254. */
  83255. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  83256. if (!this._physicsEngine) {
  83257. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  83258. return null;
  83259. }
  83260. if (this._physicsEngine.getImpostors().length === 0) {
  83261. return null;
  83262. }
  83263. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  83264. event.dispose(false);
  83265. return event;
  83266. };
  83267. return PhysicsHelper;
  83268. }());
  83269. BABYLON.PhysicsHelper = PhysicsHelper;
  83270. /***** Radial explosion *****/
  83271. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  83272. function PhysicsRadialExplosionEvent(scene) {
  83273. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  83274. this._rays = [];
  83275. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  83276. this._scene = scene;
  83277. }
  83278. /**
  83279. * Returns the data related to the radial explosion event (sphere & rays).
  83280. * @returns {PhysicsRadialExplosionEventData}
  83281. */
  83282. PhysicsRadialExplosionEvent.prototype.getData = function () {
  83283. this._dataFetched = true;
  83284. return {
  83285. sphere: this._sphere,
  83286. rays: this._rays,
  83287. };
  83288. };
  83289. /**
  83290. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  83291. * @param impostor
  83292. * @param {Vector3} origin the origin of the explosion
  83293. * @param {number} radius the explosion radius
  83294. * @param {number} strength the explosion strength
  83295. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  83296. * @returns {Nullable<PhysicsForceAndContactPoint>}
  83297. */
  83298. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  83299. if (impostor.mass === 0) {
  83300. return null;
  83301. }
  83302. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  83303. return null;
  83304. }
  83305. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83306. return null;
  83307. }
  83308. var impostorObjectCenter = impostor.getObjectCenter();
  83309. var direction = impostorObjectCenter.subtract(origin);
  83310. var ray = new BABYLON.Ray(origin, direction, radius);
  83311. this._rays.push(ray);
  83312. var hit = ray.intersectsMesh(impostor.object);
  83313. var contactPoint = hit.pickedPoint;
  83314. if (!contactPoint) {
  83315. return null;
  83316. }
  83317. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  83318. if (distanceFromOrigin > radius) {
  83319. return null;
  83320. }
  83321. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  83322. ? strength
  83323. : strength * (1 - (distanceFromOrigin / radius));
  83324. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83325. return { force: force, contactPoint: contactPoint };
  83326. };
  83327. /**
  83328. * Disposes the sphere.
  83329. * @param {bolean} force
  83330. */
  83331. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  83332. var _this = this;
  83333. if (force === void 0) { force = true; }
  83334. if (force) {
  83335. this._sphere.dispose();
  83336. }
  83337. else {
  83338. setTimeout(function () {
  83339. if (!_this._dataFetched) {
  83340. _this._sphere.dispose();
  83341. }
  83342. }, 0);
  83343. }
  83344. };
  83345. /*** Helpers ***/
  83346. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  83347. if (!this._sphere) {
  83348. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  83349. this._sphere.isVisible = false;
  83350. }
  83351. };
  83352. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  83353. var impostorObject = impostor.object;
  83354. this._prepareSphere();
  83355. this._sphere.position = origin;
  83356. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  83357. this._sphere._updateBoundingInfo();
  83358. this._sphere.computeWorldMatrix(true);
  83359. return this._sphere.intersectsMesh(impostorObject, true);
  83360. };
  83361. return PhysicsRadialExplosionEvent;
  83362. }());
  83363. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  83364. /***** Gravitational Field *****/
  83365. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  83366. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  83367. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  83368. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83369. this._physicsHelper = physicsHelper;
  83370. this._scene = scene;
  83371. this._origin = origin;
  83372. this._radius = radius;
  83373. this._strength = strength;
  83374. this._falloff = falloff;
  83375. this._tickCallback = this._tick.bind(this);
  83376. }
  83377. /**
  83378. * Returns the data related to the gravitational field event (sphere).
  83379. * @returns {PhysicsGravitationalFieldEventData}
  83380. */
  83381. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  83382. this._dataFetched = true;
  83383. return {
  83384. sphere: this._sphere,
  83385. };
  83386. };
  83387. /**
  83388. * Enables the gravitational field.
  83389. */
  83390. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  83391. this._tickCallback.call(this);
  83392. this._scene.registerBeforeRender(this._tickCallback);
  83393. };
  83394. /**
  83395. * Disables the gravitational field.
  83396. */
  83397. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  83398. this._scene.unregisterBeforeRender(this._tickCallback);
  83399. };
  83400. /**
  83401. * Disposes the sphere.
  83402. * @param {bolean} force
  83403. */
  83404. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  83405. var _this = this;
  83406. if (force === void 0) { force = true; }
  83407. if (force) {
  83408. this._sphere.dispose();
  83409. }
  83410. else {
  83411. setTimeout(function () {
  83412. if (!_this._dataFetched) {
  83413. _this._sphere.dispose();
  83414. }
  83415. }, 0);
  83416. }
  83417. };
  83418. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  83419. // Since the params won't change, we fetch the event only once
  83420. if (this._sphere) {
  83421. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83422. }
  83423. else {
  83424. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  83425. if (radialExplosionEvent) {
  83426. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  83427. }
  83428. }
  83429. };
  83430. return PhysicsGravitationalFieldEvent;
  83431. }());
  83432. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  83433. /***** Updraft *****/
  83434. var PhysicsUpdraftEvent = /** @class */ (function () {
  83435. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  83436. this._scene = _scene;
  83437. this._origin = _origin;
  83438. this._radius = _radius;
  83439. this._strength = _strength;
  83440. this._height = _height;
  83441. this._updraftMode = _updraftMode;
  83442. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83443. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  83444. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83445. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83446. this._physicsEngine = this._scene.getPhysicsEngine();
  83447. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83448. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83449. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83450. this._originDirection = this._origin.subtract(this._originTop).normalize();
  83451. }
  83452. this._tickCallback = this._tick.bind(this);
  83453. }
  83454. /**
  83455. * Returns the data related to the updraft event (cylinder).
  83456. * @returns {PhysicsUpdraftEventData}
  83457. */
  83458. PhysicsUpdraftEvent.prototype.getData = function () {
  83459. this._dataFetched = true;
  83460. return {
  83461. cylinder: this._cylinder,
  83462. };
  83463. };
  83464. /**
  83465. * Enables the updraft.
  83466. */
  83467. PhysicsUpdraftEvent.prototype.enable = function () {
  83468. this._tickCallback.call(this);
  83469. this._scene.registerBeforeRender(this._tickCallback);
  83470. };
  83471. /**
  83472. * Disables the cortex.
  83473. */
  83474. PhysicsUpdraftEvent.prototype.disable = function () {
  83475. this._scene.unregisterBeforeRender(this._tickCallback);
  83476. };
  83477. /**
  83478. * Disposes the sphere.
  83479. * @param {bolean} force
  83480. */
  83481. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  83482. var _this = this;
  83483. if (force === void 0) { force = true; }
  83484. if (force) {
  83485. this._cylinder.dispose();
  83486. }
  83487. else {
  83488. setTimeout(function () {
  83489. if (!_this._dataFetched) {
  83490. _this._cylinder.dispose();
  83491. }
  83492. }, 0);
  83493. }
  83494. };
  83495. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83496. if (impostor.mass === 0) {
  83497. return null;
  83498. }
  83499. if (!this._intersectsWithCylinder(impostor)) {
  83500. return null;
  83501. }
  83502. var impostorObjectCenter = impostor.getObjectCenter();
  83503. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  83504. var direction = this._originDirection;
  83505. }
  83506. else {
  83507. var direction = impostorObjectCenter.subtract(this._originTop);
  83508. }
  83509. var multiplier = this._strength * -1;
  83510. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  83511. return { force: force, contactPoint: impostorObjectCenter };
  83512. };
  83513. PhysicsUpdraftEvent.prototype._tick = function () {
  83514. var _this = this;
  83515. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83516. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83517. if (!impostorForceAndContactPoint) {
  83518. return;
  83519. }
  83520. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83521. });
  83522. };
  83523. /*** Helpers ***/
  83524. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  83525. if (!this._cylinder) {
  83526. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  83527. height: this._height,
  83528. diameter: this._radius * 2,
  83529. }, this._scene);
  83530. this._cylinder.isVisible = false;
  83531. }
  83532. };
  83533. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  83534. var impostorObject = impostor.object;
  83535. this._prepareCylinder();
  83536. this._cylinder.position = this._cylinderPosition;
  83537. return this._cylinder.intersectsMesh(impostorObject, true);
  83538. };
  83539. return PhysicsUpdraftEvent;
  83540. }());
  83541. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  83542. /***** Vortex *****/
  83543. var PhysicsVortexEvent = /** @class */ (function () {
  83544. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  83545. this._scene = _scene;
  83546. this._origin = _origin;
  83547. this._radius = _radius;
  83548. this._strength = _strength;
  83549. this._height = _height;
  83550. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  83551. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  83552. this._updraftMultiplier = 0.02;
  83553. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  83554. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  83555. this._physicsEngine = this._scene.getPhysicsEngine();
  83556. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83557. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83558. this._tickCallback = this._tick.bind(this);
  83559. }
  83560. /**
  83561. * Returns the data related to the vortex event (cylinder).
  83562. * @returns {PhysicsVortexEventData}
  83563. */
  83564. PhysicsVortexEvent.prototype.getData = function () {
  83565. this._dataFetched = true;
  83566. return {
  83567. cylinder: this._cylinder,
  83568. };
  83569. };
  83570. /**
  83571. * Enables the vortex.
  83572. */
  83573. PhysicsVortexEvent.prototype.enable = function () {
  83574. this._tickCallback.call(this);
  83575. this._scene.registerBeforeRender(this._tickCallback);
  83576. };
  83577. /**
  83578. * Disables the cortex.
  83579. */
  83580. PhysicsVortexEvent.prototype.disable = function () {
  83581. this._scene.unregisterBeforeRender(this._tickCallback);
  83582. };
  83583. /**
  83584. * Disposes the sphere.
  83585. * @param {bolean} force
  83586. */
  83587. PhysicsVortexEvent.prototype.dispose = function (force) {
  83588. var _this = this;
  83589. if (force === void 0) { force = true; }
  83590. if (force) {
  83591. this._cylinder.dispose();
  83592. }
  83593. else {
  83594. setTimeout(function () {
  83595. if (!_this._dataFetched) {
  83596. _this._cylinder.dispose();
  83597. }
  83598. }, 0);
  83599. }
  83600. };
  83601. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83602. if (impostor.mass === 0) {
  83603. return null;
  83604. }
  83605. if (!this._intersectsWithCylinder(impostor)) {
  83606. return null;
  83607. }
  83608. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83609. return null;
  83610. }
  83611. var impostorObjectCenter = impostor.getObjectCenter();
  83612. 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)
  83613. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83614. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83615. var hit = ray.intersectsMesh(impostor.object);
  83616. var contactPoint = hit.pickedPoint;
  83617. if (!contactPoint) {
  83618. return null;
  83619. }
  83620. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83621. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83622. var directionToOrigin = contactPoint.normalize();
  83623. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83624. directionToOrigin = directionToOrigin.negate();
  83625. }
  83626. // TODO: find a more physically based solution
  83627. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83628. var forceX = directionToOrigin.x * this._strength / 8;
  83629. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83630. var forceZ = directionToOrigin.z * this._strength / 8;
  83631. }
  83632. else {
  83633. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83634. var forceY = this._originTop.y * this._updraftMultiplier;
  83635. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83636. }
  83637. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83638. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83639. return { force: force, contactPoint: impostorObjectCenter };
  83640. };
  83641. PhysicsVortexEvent.prototype._tick = function () {
  83642. var _this = this;
  83643. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83644. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83645. if (!impostorForceAndContactPoint) {
  83646. return;
  83647. }
  83648. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83649. });
  83650. };
  83651. /*** Helpers ***/
  83652. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83653. if (!this._cylinder) {
  83654. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83655. height: this._height,
  83656. diameter: this._radius * 2,
  83657. }, this._scene);
  83658. this._cylinder.isVisible = false;
  83659. }
  83660. };
  83661. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83662. var impostorObject = impostor.object;
  83663. this._prepareCylinder();
  83664. this._cylinder.position = this._cylinderPosition;
  83665. return this._cylinder.intersectsMesh(impostorObject, true);
  83666. };
  83667. return PhysicsVortexEvent;
  83668. }());
  83669. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83670. /***** Enums *****/
  83671. /**
  83672. * The strenght of the force in correspondence to the distance of the affected object
  83673. */
  83674. var PhysicsRadialImpulseFalloff;
  83675. (function (PhysicsRadialImpulseFalloff) {
  83676. /** Defines that impulse is constant in strength across it's whole radius */
  83677. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83678. /** DEfines that impulse gets weaker if it's further from the origin */
  83679. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83680. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83681. /**
  83682. * The strenght of the force in correspondence to the distance of the affected object
  83683. */
  83684. var PhysicsUpdraftMode;
  83685. (function (PhysicsUpdraftMode) {
  83686. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83687. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83688. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83689. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83690. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83691. })(BABYLON || (BABYLON = {}));
  83692. //# sourceMappingURL=babylon.physicsHelper.js.map
  83693. var BABYLON;
  83694. (function (BABYLON) {
  83695. var CannonJSPlugin = /** @class */ (function () {
  83696. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83697. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83698. if (iterations === void 0) { iterations = 10; }
  83699. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83700. this.name = "CannonJSPlugin";
  83701. this._physicsMaterials = new Array();
  83702. this._fixedTimeStep = 1 / 60;
  83703. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83704. this.BJSCANNON = CANNON;
  83705. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83706. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83707. this._tmpPosition = BABYLON.Vector3.Zero();
  83708. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83709. this._tmpUnityRotation = new BABYLON.Quaternion();
  83710. if (!this.isSupported()) {
  83711. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83712. return;
  83713. }
  83714. this._extendNamespace();
  83715. this.world = new this.BJSCANNON.World();
  83716. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83717. this.world.solver.iterations = iterations;
  83718. }
  83719. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83720. this.world.gravity.copy(gravity);
  83721. };
  83722. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83723. this._fixedTimeStep = timeStep;
  83724. };
  83725. CannonJSPlugin.prototype.getTimeStep = function () {
  83726. return this._fixedTimeStep;
  83727. };
  83728. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83729. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83730. };
  83731. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83732. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83733. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83734. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83735. };
  83736. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83737. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83738. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83739. impostor.physicsBody.applyForce(impulse, worldPoint);
  83740. };
  83741. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83742. //parent-child relationship. Does this impostor has a parent impostor?
  83743. if (impostor.parent) {
  83744. if (impostor.physicsBody) {
  83745. this.removePhysicsBody(impostor);
  83746. //TODO is that needed?
  83747. impostor.forceUpdate();
  83748. }
  83749. return;
  83750. }
  83751. //should a new body be created for this impostor?
  83752. if (impostor.isBodyInitRequired()) {
  83753. var shape = this._createShape(impostor);
  83754. //unregister events, if body is being changed
  83755. var oldBody = impostor.physicsBody;
  83756. if (oldBody) {
  83757. this.removePhysicsBody(impostor);
  83758. }
  83759. //create the body and material
  83760. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83761. var bodyCreationObject = {
  83762. mass: impostor.getParam("mass"),
  83763. material: material
  83764. };
  83765. // A simple extend, in case native options were used.
  83766. var nativeOptions = impostor.getParam("nativeOptions");
  83767. for (var key in nativeOptions) {
  83768. if (nativeOptions.hasOwnProperty(key)) {
  83769. bodyCreationObject[key] = nativeOptions[key];
  83770. }
  83771. }
  83772. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83773. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83774. this.world.addEventListener("preStep", impostor.beforeStep);
  83775. this.world.addEventListener("postStep", impostor.afterStep);
  83776. impostor.physicsBody.addShape(shape);
  83777. this.world.add(impostor.physicsBody);
  83778. //try to keep the body moving in the right direction by taking old properties.
  83779. //Should be tested!
  83780. if (oldBody) {
  83781. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83782. impostor.physicsBody[param].copy(oldBody[param]);
  83783. });
  83784. }
  83785. this._processChildMeshes(impostor);
  83786. }
  83787. //now update the body's transformation
  83788. this._updatePhysicsBodyTransformation(impostor);
  83789. };
  83790. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83791. var _this = this;
  83792. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83793. var currentRotation = mainImpostor.object.rotationQuaternion;
  83794. if (meshChildren.length) {
  83795. var processMesh = function (localPosition, mesh) {
  83796. if (!currentRotation || !mesh.rotationQuaternion) {
  83797. return;
  83798. }
  83799. var childImpostor = mesh.getPhysicsImpostor();
  83800. if (childImpostor) {
  83801. var parent = childImpostor.parent;
  83802. if (parent !== mainImpostor) {
  83803. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83804. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83805. if (childImpostor.physicsBody) {
  83806. _this.removePhysicsBody(childImpostor);
  83807. childImpostor.physicsBody = null;
  83808. }
  83809. childImpostor.parent = mainImpostor;
  83810. childImpostor.resetUpdateFlags();
  83811. 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));
  83812. //Add the mass of the children.
  83813. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83814. }
  83815. }
  83816. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83817. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83818. };
  83819. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83820. }
  83821. };
  83822. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83823. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83824. this.world.removeEventListener("preStep", impostor.beforeStep);
  83825. this.world.removeEventListener("postStep", impostor.afterStep);
  83826. this.world.remove(impostor.physicsBody);
  83827. };
  83828. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83829. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83830. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83831. if (!mainBody || !connectedBody) {
  83832. return;
  83833. }
  83834. var constraint;
  83835. var jointData = impostorJoint.joint.jointData;
  83836. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83837. var constraintData = {
  83838. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83839. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83840. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83841. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83842. maxForce: jointData.nativeParams.maxForce,
  83843. collideConnected: !!jointData.collision
  83844. };
  83845. switch (impostorJoint.joint.type) {
  83846. case BABYLON.PhysicsJoint.HingeJoint:
  83847. case BABYLON.PhysicsJoint.Hinge2Joint:
  83848. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83849. break;
  83850. case BABYLON.PhysicsJoint.DistanceJoint:
  83851. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83852. break;
  83853. case BABYLON.PhysicsJoint.SpringJoint:
  83854. var springData = jointData;
  83855. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83856. restLength: springData.length,
  83857. stiffness: springData.stiffness,
  83858. damping: springData.damping,
  83859. localAnchorA: constraintData.pivotA,
  83860. localAnchorB: constraintData.pivotB
  83861. });
  83862. break;
  83863. case BABYLON.PhysicsJoint.LockJoint:
  83864. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83865. break;
  83866. case BABYLON.PhysicsJoint.PointToPointJoint:
  83867. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83868. default:
  83869. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83870. break;
  83871. }
  83872. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83873. constraint.collideConnected = !!jointData.collision;
  83874. impostorJoint.joint.physicsJoint = constraint;
  83875. //don't add spring as constraint, as it is not one.
  83876. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83877. this.world.addConstraint(constraint);
  83878. }
  83879. else {
  83880. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83881. constraint.applyForce();
  83882. });
  83883. }
  83884. };
  83885. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83886. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83887. };
  83888. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83889. var index;
  83890. var mat;
  83891. for (index = 0; index < this._physicsMaterials.length; index++) {
  83892. mat = this._physicsMaterials[index];
  83893. if (mat.friction === friction && mat.restitution === restitution) {
  83894. return mat;
  83895. }
  83896. }
  83897. var currentMat = new this.BJSCANNON.Material(name);
  83898. currentMat.friction = friction;
  83899. currentMat.restitution = restitution;
  83900. this._physicsMaterials.push(currentMat);
  83901. return currentMat;
  83902. };
  83903. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83904. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83905. };
  83906. CannonJSPlugin.prototype._createShape = function (impostor) {
  83907. var object = impostor.object;
  83908. var returnValue;
  83909. var extendSize = impostor.getObjectExtendSize();
  83910. switch (impostor.type) {
  83911. case BABYLON.PhysicsImpostor.SphereImpostor:
  83912. var radiusX = extendSize.x;
  83913. var radiusY = extendSize.y;
  83914. var radiusZ = extendSize.z;
  83915. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83916. break;
  83917. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83918. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83919. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83920. break;
  83921. case BABYLON.PhysicsImpostor.BoxImpostor:
  83922. var box = extendSize.scale(0.5);
  83923. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83924. break;
  83925. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83926. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83927. returnValue = new this.BJSCANNON.Plane();
  83928. break;
  83929. case BABYLON.PhysicsImpostor.MeshImpostor:
  83930. // should transform the vertex data to world coordinates!!
  83931. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83932. var rawFaces = object.getIndices ? object.getIndices() : [];
  83933. if (!rawVerts)
  83934. return;
  83935. // get only scale! so the object could transform correctly.
  83936. var oldPosition = object.position.clone();
  83937. var oldRotation = object.rotation && object.rotation.clone();
  83938. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83939. object.position.copyFromFloats(0, 0, 0);
  83940. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83941. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83942. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83943. var transform = object.computeWorldMatrix(true);
  83944. // convert rawVerts to object space
  83945. var temp = new Array();
  83946. var index;
  83947. for (index = 0; index < rawVerts.length; index += 3) {
  83948. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83949. }
  83950. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83951. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83952. //now set back the transformation!
  83953. object.position.copyFrom(oldPosition);
  83954. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83955. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83956. break;
  83957. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83958. var oldPosition2 = object.position.clone();
  83959. var oldRotation2 = object.rotation && object.rotation.clone();
  83960. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83961. object.position.copyFromFloats(0, 0, 0);
  83962. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83963. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83964. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83965. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83966. returnValue = this._createHeightmap(object);
  83967. object.position.copyFrom(oldPosition2);
  83968. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83969. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83970. object.computeWorldMatrix(true);
  83971. break;
  83972. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83973. returnValue = new this.BJSCANNON.Particle();
  83974. break;
  83975. }
  83976. return returnValue;
  83977. };
  83978. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83979. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83980. var transform = object.computeWorldMatrix(true);
  83981. // convert rawVerts to object space
  83982. var temp = new Array();
  83983. var index;
  83984. for (index = 0; index < pos.length; index += 3) {
  83985. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83986. }
  83987. pos = temp;
  83988. var matrix = new Array();
  83989. //For now pointDepth will not be used and will be automatically calculated.
  83990. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83991. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83992. var boundingInfo = object.getBoundingInfo();
  83993. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83994. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83995. var elementSize = dim * 2 / arraySize;
  83996. for (var i = 0; i < pos.length; i = i + 3) {
  83997. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83998. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83999. var y = -pos[i + 2] + minY;
  84000. if (!matrix[x]) {
  84001. matrix[x] = [];
  84002. }
  84003. if (!matrix[x][z]) {
  84004. matrix[x][z] = y;
  84005. }
  84006. matrix[x][z] = Math.max(y, matrix[x][z]);
  84007. }
  84008. for (var x = 0; x <= arraySize; ++x) {
  84009. if (!matrix[x]) {
  84010. var loc = 1;
  84011. while (!matrix[(x + loc) % arraySize]) {
  84012. loc++;
  84013. }
  84014. matrix[x] = matrix[(x + loc) % arraySize].slice();
  84015. //console.log("missing x", x);
  84016. }
  84017. for (var z = 0; z <= arraySize; ++z) {
  84018. if (!matrix[x][z]) {
  84019. var loc = 1;
  84020. var newValue;
  84021. while (newValue === undefined) {
  84022. newValue = matrix[x][(z + loc++) % arraySize];
  84023. }
  84024. matrix[x][z] = newValue;
  84025. }
  84026. }
  84027. }
  84028. var shape = new this.BJSCANNON.Heightfield(matrix, {
  84029. elementSize: elementSize
  84030. });
  84031. //For future reference, needed for body transformation
  84032. shape.minY = minY;
  84033. return shape;
  84034. };
  84035. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  84036. var object = impostor.object;
  84037. //make sure it is updated...
  84038. object.computeWorldMatrix && object.computeWorldMatrix(true);
  84039. // The delta between the mesh position and the mesh bounding box center
  84040. var bInfo = object.getBoundingInfo();
  84041. if (!bInfo)
  84042. return;
  84043. var center = impostor.getObjectCenter();
  84044. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  84045. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  84046. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  84047. this._tmpPosition.copyFrom(center);
  84048. var quaternion = object.rotationQuaternion;
  84049. if (!quaternion) {
  84050. return;
  84051. }
  84052. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  84053. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  84054. //-90 DEG in X, precalculated
  84055. quaternion = quaternion.multiply(this._minus90X);
  84056. //Invert! (Precalculated, 90 deg in X)
  84057. //No need to clone. this will never change.
  84058. impostor.setDeltaRotation(this._plus90X);
  84059. }
  84060. //If it is a heightfield, if should be centered.
  84061. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  84062. var mesh = object;
  84063. var boundingInfo = mesh.getBoundingInfo();
  84064. //calculate the correct body position:
  84065. var rotationQuaternion = mesh.rotationQuaternion;
  84066. mesh.rotationQuaternion = this._tmpUnityRotation;
  84067. mesh.computeWorldMatrix(true);
  84068. //get original center with no rotation
  84069. var c = center.clone();
  84070. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  84071. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  84072. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  84073. mesh.setPreTransformMatrix(p);
  84074. mesh.computeWorldMatrix(true);
  84075. //calculate the translation
  84076. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  84077. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  84078. //add it inverted to the delta
  84079. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  84080. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  84081. //rotation is back
  84082. mesh.rotationQuaternion = rotationQuaternion;
  84083. mesh.setPreTransformMatrix(oldPivot);
  84084. mesh.computeWorldMatrix(true);
  84085. }
  84086. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  84087. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  84088. //this._tmpPosition.copyFrom(object.position);
  84089. }
  84090. impostor.setDeltaPosition(this._tmpDeltaPosition);
  84091. //Now update the impostor object
  84092. impostor.physicsBody.position.copy(this._tmpPosition);
  84093. impostor.physicsBody.quaternion.copy(quaternion);
  84094. };
  84095. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84096. impostor.object.position.copyFrom(impostor.physicsBody.position);
  84097. if (impostor.object.rotationQuaternion) {
  84098. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  84099. }
  84100. };
  84101. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84102. impostor.physicsBody.position.copy(newPosition);
  84103. impostor.physicsBody.quaternion.copy(newRotation);
  84104. };
  84105. CannonJSPlugin.prototype.isSupported = function () {
  84106. return this.BJSCANNON !== undefined;
  84107. };
  84108. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84109. impostor.physicsBody.velocity.copy(velocity);
  84110. };
  84111. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84112. impostor.physicsBody.angularVelocity.copy(velocity);
  84113. };
  84114. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84115. var v = impostor.physicsBody.velocity;
  84116. if (!v) {
  84117. return null;
  84118. }
  84119. return new BABYLON.Vector3(v.x, v.y, v.z);
  84120. };
  84121. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84122. var v = impostor.physicsBody.angularVelocity;
  84123. if (!v) {
  84124. return null;
  84125. }
  84126. return new BABYLON.Vector3(v.x, v.y, v.z);
  84127. };
  84128. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84129. impostor.physicsBody.mass = mass;
  84130. impostor.physicsBody.updateMassProperties();
  84131. };
  84132. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  84133. return impostor.physicsBody.mass;
  84134. };
  84135. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  84136. return impostor.physicsBody.material.friction;
  84137. };
  84138. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84139. impostor.physicsBody.material.friction = friction;
  84140. };
  84141. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84142. return impostor.physicsBody.material.restitution;
  84143. };
  84144. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84145. impostor.physicsBody.material.restitution = restitution;
  84146. };
  84147. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  84148. impostor.physicsBody.sleep();
  84149. };
  84150. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  84151. impostor.physicsBody.wakeUp();
  84152. };
  84153. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84154. joint.physicsJoint.distance = maxDistance;
  84155. };
  84156. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84157. // if (!motorIndex) {
  84158. // joint.physicsJoint.enableMotor();
  84159. // }
  84160. // }
  84161. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  84162. // if (!motorIndex) {
  84163. // joint.physicsJoint.disableMotor();
  84164. // }
  84165. // }
  84166. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84167. if (!motorIndex) {
  84168. joint.physicsJoint.enableMotor();
  84169. joint.physicsJoint.setMotorSpeed(speed);
  84170. if (maxForce) {
  84171. this.setLimit(joint, maxForce);
  84172. }
  84173. }
  84174. };
  84175. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  84176. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  84177. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  84178. };
  84179. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84180. var body = impostor.physicsBody;
  84181. mesh.position.x = body.position.x;
  84182. mesh.position.y = body.position.y;
  84183. mesh.position.z = body.position.z;
  84184. if (mesh.rotationQuaternion) {
  84185. mesh.rotationQuaternion.x = body.quaternion.x;
  84186. mesh.rotationQuaternion.y = body.quaternion.y;
  84187. mesh.rotationQuaternion.z = body.quaternion.z;
  84188. mesh.rotationQuaternion.w = body.quaternion.w;
  84189. }
  84190. };
  84191. CannonJSPlugin.prototype.getRadius = function (impostor) {
  84192. var shape = impostor.physicsBody.shapes[0];
  84193. return shape.boundingSphereRadius;
  84194. };
  84195. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84196. var shape = impostor.physicsBody.shapes[0];
  84197. result.x = shape.halfExtents.x * 2;
  84198. result.y = shape.halfExtents.y * 2;
  84199. result.z = shape.halfExtents.z * 2;
  84200. };
  84201. CannonJSPlugin.prototype.dispose = function () {
  84202. };
  84203. CannonJSPlugin.prototype._extendNamespace = function () {
  84204. //this will force cannon to execute at least one step when using interpolation
  84205. var step_tmp1 = new this.BJSCANNON.Vec3();
  84206. var Engine = this.BJSCANNON;
  84207. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  84208. maxSubSteps = maxSubSteps || 10;
  84209. timeSinceLastCalled = timeSinceLastCalled || 0;
  84210. if (timeSinceLastCalled === 0) {
  84211. this.internalStep(dt);
  84212. this.time += dt;
  84213. }
  84214. else {
  84215. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  84216. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  84217. var t0 = performance.now();
  84218. for (var i = 0; i !== internalSteps; i++) {
  84219. this.internalStep(dt);
  84220. if (performance.now() - t0 > dt * 1000) {
  84221. break;
  84222. }
  84223. }
  84224. this.time += timeSinceLastCalled;
  84225. var h = this.time % dt;
  84226. var h_div_dt = h / dt;
  84227. var interpvelo = step_tmp1;
  84228. var bodies = this.bodies;
  84229. for (var j = 0; j !== bodies.length; j++) {
  84230. var b = bodies[j];
  84231. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  84232. b.position.vsub(b.previousPosition, interpvelo);
  84233. interpvelo.scale(h_div_dt, interpvelo);
  84234. b.position.vadd(interpvelo, b.interpolatedPosition);
  84235. }
  84236. else {
  84237. b.interpolatedPosition.copy(b.position);
  84238. b.interpolatedQuaternion.copy(b.quaternion);
  84239. }
  84240. }
  84241. }
  84242. };
  84243. };
  84244. return CannonJSPlugin;
  84245. }());
  84246. BABYLON.CannonJSPlugin = CannonJSPlugin;
  84247. })(BABYLON || (BABYLON = {}));
  84248. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  84249. var BABYLON;
  84250. (function (BABYLON) {
  84251. var OimoJSPlugin = /** @class */ (function () {
  84252. function OimoJSPlugin(iterations) {
  84253. this.name = "OimoJSPlugin";
  84254. this._tmpImpostorsArray = [];
  84255. this._tmpPositionVector = BABYLON.Vector3.Zero();
  84256. this.BJSOIMO = OIMO;
  84257. this.world = new this.BJSOIMO.World({
  84258. iterations: iterations
  84259. });
  84260. this.world.clear();
  84261. }
  84262. OimoJSPlugin.prototype.setGravity = function (gravity) {
  84263. this.world.gravity.copy(gravity);
  84264. };
  84265. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  84266. this.world.timeStep = timeStep;
  84267. };
  84268. OimoJSPlugin.prototype.getTimeStep = function () {
  84269. return this.world.timeStep;
  84270. };
  84271. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  84272. var _this = this;
  84273. impostors.forEach(function (impostor) {
  84274. impostor.beforeStep();
  84275. });
  84276. this.world.step();
  84277. impostors.forEach(function (impostor) {
  84278. impostor.afterStep();
  84279. //update the ordered impostors array
  84280. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  84281. });
  84282. //check for collisions
  84283. var contact = this.world.contacts;
  84284. while (contact !== null) {
  84285. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  84286. contact = contact.next;
  84287. continue;
  84288. }
  84289. //is this body colliding with any other? get the impostor
  84290. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  84291. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  84292. if (!mainImpostor || !collidingImpostor) {
  84293. contact = contact.next;
  84294. continue;
  84295. }
  84296. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  84297. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  84298. contact = contact.next;
  84299. }
  84300. };
  84301. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  84302. var mass = impostor.physicsBody.mass;
  84303. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  84304. };
  84305. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  84306. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  84307. this.applyImpulse(impostor, force, contactPoint);
  84308. };
  84309. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  84310. var _this = this;
  84311. //parent-child relationship. Does this impostor has a parent impostor?
  84312. if (impostor.parent) {
  84313. if (impostor.physicsBody) {
  84314. this.removePhysicsBody(impostor);
  84315. //TODO is that needed?
  84316. impostor.forceUpdate();
  84317. }
  84318. return;
  84319. }
  84320. if (impostor.isBodyInitRequired()) {
  84321. var bodyConfig = {
  84322. name: impostor.uniqueId,
  84323. //Oimo must have mass, also for static objects.
  84324. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  84325. size: [],
  84326. type: [],
  84327. pos: [],
  84328. posShape: [],
  84329. rot: [],
  84330. rotShape: [],
  84331. move: impostor.getParam("mass") !== 0,
  84332. density: impostor.getParam("mass"),
  84333. friction: impostor.getParam("friction"),
  84334. restitution: impostor.getParam("restitution"),
  84335. //Supporting older versions of Oimo
  84336. world: this.world
  84337. };
  84338. var impostors = [impostor];
  84339. var addToArray = function (parent) {
  84340. if (!parent.getChildMeshes)
  84341. return;
  84342. parent.getChildMeshes().forEach(function (m) {
  84343. if (m.physicsImpostor) {
  84344. impostors.push(m.physicsImpostor);
  84345. //m.physicsImpostor._init();
  84346. }
  84347. });
  84348. };
  84349. addToArray(impostor.object);
  84350. var checkWithEpsilon_1 = function (value) {
  84351. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  84352. };
  84353. impostors.forEach(function (i) {
  84354. if (!i.object.rotationQuaternion) {
  84355. return;
  84356. }
  84357. //get the correct bounding box
  84358. var oldQuaternion = i.object.rotationQuaternion;
  84359. var rot = oldQuaternion.toEulerAngles();
  84360. var extendSize = i.getObjectExtendSize();
  84361. var radToDeg = 57.295779513082320876;
  84362. if (i === impostor) {
  84363. var center = impostor.getObjectCenter();
  84364. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  84365. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  84366. //Can also use Array.prototype.push.apply
  84367. bodyConfig.pos.push(center.x);
  84368. bodyConfig.pos.push(center.y);
  84369. bodyConfig.pos.push(center.z);
  84370. bodyConfig.posShape.push(0, 0, 0);
  84371. //tmp solution
  84372. bodyConfig.rot.push(rot.x * radToDeg);
  84373. bodyConfig.rot.push(rot.y * radToDeg);
  84374. bodyConfig.rot.push(rot.z * radToDeg);
  84375. bodyConfig.rotShape.push(0, 0, 0);
  84376. }
  84377. else {
  84378. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  84379. bodyConfig.posShape.push(localPosition.x);
  84380. bodyConfig.posShape.push(localPosition.y);
  84381. bodyConfig.posShape.push(localPosition.z);
  84382. bodyConfig.pos.push(0, 0, 0);
  84383. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  84384. bodyConfig.rot.push(0);
  84385. bodyConfig.rot.push(0);
  84386. bodyConfig.rot.push(0);
  84387. bodyConfig.rotShape.push(rot.x * radToDeg);
  84388. bodyConfig.rotShape.push(rot.y * radToDeg);
  84389. bodyConfig.rotShape.push(rot.z * radToDeg);
  84390. }
  84391. // register mesh
  84392. switch (i.type) {
  84393. case BABYLON.PhysicsImpostor.ParticleImpostor:
  84394. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  84395. case BABYLON.PhysicsImpostor.SphereImpostor:
  84396. var radiusX = extendSize.x;
  84397. var radiusY = extendSize.y;
  84398. var radiusZ = extendSize.z;
  84399. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  84400. bodyConfig.type.push('sphere');
  84401. //due to the way oimo works with compounds, add 3 times
  84402. bodyConfig.size.push(size);
  84403. bodyConfig.size.push(size);
  84404. bodyConfig.size.push(size);
  84405. break;
  84406. case BABYLON.PhysicsImpostor.CylinderImpostor:
  84407. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  84408. var sizeY = checkWithEpsilon_1(extendSize.y);
  84409. bodyConfig.type.push('cylinder');
  84410. bodyConfig.size.push(sizeX);
  84411. bodyConfig.size.push(sizeY);
  84412. //due to the way oimo works with compounds, add one more value.
  84413. bodyConfig.size.push(sizeY);
  84414. break;
  84415. case BABYLON.PhysicsImpostor.PlaneImpostor:
  84416. case BABYLON.PhysicsImpostor.BoxImpostor:
  84417. default:
  84418. var sizeX = checkWithEpsilon_1(extendSize.x);
  84419. var sizeY = checkWithEpsilon_1(extendSize.y);
  84420. var sizeZ = checkWithEpsilon_1(extendSize.z);
  84421. bodyConfig.type.push('box');
  84422. //if (i === impostor) {
  84423. bodyConfig.size.push(sizeX);
  84424. bodyConfig.size.push(sizeY);
  84425. bodyConfig.size.push(sizeZ);
  84426. //} else {
  84427. // bodyConfig.size.push(0,0,0);
  84428. //}
  84429. break;
  84430. }
  84431. //actually not needed, but hey...
  84432. i.object.rotationQuaternion = oldQuaternion;
  84433. });
  84434. impostor.physicsBody = this.world.add(bodyConfig);
  84435. }
  84436. else {
  84437. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  84438. }
  84439. impostor.setDeltaPosition(this._tmpPositionVector);
  84440. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  84441. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  84442. };
  84443. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  84444. //impostor.physicsBody.dispose();
  84445. //Same as : (older oimo versions)
  84446. this.world.removeRigidBody(impostor.physicsBody);
  84447. };
  84448. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  84449. var mainBody = impostorJoint.mainImpostor.physicsBody;
  84450. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  84451. if (!mainBody || !connectedBody) {
  84452. return;
  84453. }
  84454. var jointData = impostorJoint.joint.jointData;
  84455. var options = jointData.nativeParams || {};
  84456. var type;
  84457. var nativeJointData = {
  84458. body1: mainBody,
  84459. body2: connectedBody,
  84460. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  84461. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  84462. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  84463. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  84464. min: options.min,
  84465. max: options.max,
  84466. collision: options.collision || jointData.collision,
  84467. spring: options.spring,
  84468. //supporting older version of Oimo
  84469. world: this.world
  84470. };
  84471. switch (impostorJoint.joint.type) {
  84472. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  84473. type = "jointBall";
  84474. break;
  84475. case BABYLON.PhysicsJoint.SpringJoint:
  84476. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  84477. var springData = jointData;
  84478. nativeJointData.min = springData.length || nativeJointData.min;
  84479. //Max should also be set, just make sure it is at least min
  84480. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  84481. case BABYLON.PhysicsJoint.DistanceJoint:
  84482. type = "jointDistance";
  84483. nativeJointData.max = jointData.maxDistance;
  84484. break;
  84485. case BABYLON.PhysicsJoint.PrismaticJoint:
  84486. type = "jointPrisme";
  84487. break;
  84488. case BABYLON.PhysicsJoint.SliderJoint:
  84489. type = "jointSlide";
  84490. break;
  84491. case BABYLON.PhysicsJoint.WheelJoint:
  84492. type = "jointWheel";
  84493. break;
  84494. case BABYLON.PhysicsJoint.HingeJoint:
  84495. default:
  84496. type = "jointHinge";
  84497. break;
  84498. }
  84499. nativeJointData.type = type;
  84500. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  84501. };
  84502. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  84503. //Bug in Oimo prevents us from disposing a joint in the playground
  84504. //joint.joint.physicsJoint.dispose();
  84505. //So we will bruteforce it!
  84506. try {
  84507. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  84508. }
  84509. catch (e) {
  84510. BABYLON.Tools.Warn(e);
  84511. }
  84512. };
  84513. OimoJSPlugin.prototype.isSupported = function () {
  84514. return this.BJSOIMO !== undefined;
  84515. };
  84516. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  84517. if (!impostor.physicsBody.sleeping) {
  84518. //TODO check that
  84519. /*if (impostor.physicsBody.shapes.next) {
  84520. var parentShape = this._getLastShape(impostor.physicsBody);
  84521. impostor.object.position.copyFrom(parentShape.position);
  84522. console.log(parentShape.position);
  84523. } else {*/
  84524. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  84525. //}
  84526. if (impostor.object.rotationQuaternion) {
  84527. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  84528. }
  84529. }
  84530. };
  84531. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  84532. var body = impostor.physicsBody;
  84533. body.position.copy(newPosition);
  84534. body.orientation.copy(newRotation);
  84535. body.syncShapes();
  84536. body.awake();
  84537. };
  84538. /*private _getLastShape(body: any): any {
  84539. var lastShape = body.shapes;
  84540. while (lastShape.next) {
  84541. lastShape = lastShape.next;
  84542. }
  84543. return lastShape;
  84544. }*/
  84545. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  84546. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  84547. };
  84548. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  84549. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  84550. };
  84551. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  84552. var v = impostor.physicsBody.linearVelocity;
  84553. if (!v) {
  84554. return null;
  84555. }
  84556. return new BABYLON.Vector3(v.x, v.y, v.z);
  84557. };
  84558. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84559. var v = impostor.physicsBody.angularVelocity;
  84560. if (!v) {
  84561. return null;
  84562. }
  84563. return new BABYLON.Vector3(v.x, v.y, v.z);
  84564. };
  84565. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84566. var staticBody = mass === 0;
  84567. //this will actually set the body's density and not its mass.
  84568. //But this is how oimo treats the mass variable.
  84569. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84570. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84571. };
  84572. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84573. return impostor.physicsBody.shapes.density;
  84574. };
  84575. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84576. return impostor.physicsBody.shapes.friction;
  84577. };
  84578. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84579. impostor.physicsBody.shapes.friction = friction;
  84580. };
  84581. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84582. return impostor.physicsBody.shapes.restitution;
  84583. };
  84584. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84585. impostor.physicsBody.shapes.restitution = restitution;
  84586. };
  84587. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84588. impostor.physicsBody.sleep();
  84589. };
  84590. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84591. impostor.physicsBody.awake();
  84592. };
  84593. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84594. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84595. if (minDistance !== void 0) {
  84596. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84597. }
  84598. };
  84599. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84600. //TODO separate rotational and transational motors.
  84601. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84602. if (motor) {
  84603. motor.setMotor(speed, maxForce);
  84604. }
  84605. };
  84606. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84607. //TODO separate rotational and transational motors.
  84608. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84609. if (motor) {
  84610. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84611. }
  84612. };
  84613. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84614. var body = impostor.physicsBody;
  84615. mesh.position.x = body.position.x;
  84616. mesh.position.y = body.position.y;
  84617. mesh.position.z = body.position.z;
  84618. if (mesh.rotationQuaternion) {
  84619. mesh.rotationQuaternion.x = body.orientation.x;
  84620. mesh.rotationQuaternion.y = body.orientation.y;
  84621. mesh.rotationQuaternion.z = body.orientation.z;
  84622. mesh.rotationQuaternion.w = body.orientation.s;
  84623. }
  84624. };
  84625. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84626. return impostor.physicsBody.shapes.radius;
  84627. };
  84628. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84629. var shape = impostor.physicsBody.shapes;
  84630. result.x = shape.halfWidth * 2;
  84631. result.y = shape.halfHeight * 2;
  84632. result.z = shape.halfDepth * 2;
  84633. };
  84634. OimoJSPlugin.prototype.dispose = function () {
  84635. this.world.clear();
  84636. };
  84637. return OimoJSPlugin;
  84638. }());
  84639. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84640. })(BABYLON || (BABYLON = {}));
  84641. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84642. var BABYLON;
  84643. (function (BABYLON) {
  84644. /*
  84645. * Based on jsTGALoader - Javascript loader for TGA file
  84646. * By Vincent Thibault
  84647. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84648. */
  84649. var TGATools = /** @class */ (function () {
  84650. function TGATools() {
  84651. }
  84652. TGATools.GetTGAHeader = function (data) {
  84653. var offset = 0;
  84654. var header = {
  84655. id_length: data[offset++],
  84656. colormap_type: data[offset++],
  84657. image_type: data[offset++],
  84658. colormap_index: data[offset++] | data[offset++] << 8,
  84659. colormap_length: data[offset++] | data[offset++] << 8,
  84660. colormap_size: data[offset++],
  84661. origin: [
  84662. data[offset++] | data[offset++] << 8,
  84663. data[offset++] | data[offset++] << 8
  84664. ],
  84665. width: data[offset++] | data[offset++] << 8,
  84666. height: data[offset++] | data[offset++] << 8,
  84667. pixel_size: data[offset++],
  84668. flags: data[offset++]
  84669. };
  84670. return header;
  84671. };
  84672. TGATools.UploadContent = function (gl, data) {
  84673. // Not enough data to contain header ?
  84674. if (data.length < 19) {
  84675. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84676. return;
  84677. }
  84678. // Read Header
  84679. var offset = 18;
  84680. var header = TGATools.GetTGAHeader(data);
  84681. // Assume it's a valid Targa file.
  84682. if (header.id_length + offset > data.length) {
  84683. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84684. return;
  84685. }
  84686. // Skip not needed data
  84687. offset += header.id_length;
  84688. var use_rle = false;
  84689. var use_pal = false;
  84690. var use_grey = false;
  84691. // Get some informations.
  84692. switch (header.image_type) {
  84693. case TGATools._TYPE_RLE_INDEXED:
  84694. use_rle = true;
  84695. case TGATools._TYPE_INDEXED:
  84696. use_pal = true;
  84697. break;
  84698. case TGATools._TYPE_RLE_RGB:
  84699. use_rle = true;
  84700. case TGATools._TYPE_RGB:
  84701. // use_rgb = true;
  84702. break;
  84703. case TGATools._TYPE_RLE_GREY:
  84704. use_rle = true;
  84705. case TGATools._TYPE_GREY:
  84706. use_grey = true;
  84707. break;
  84708. }
  84709. var pixel_data;
  84710. // var numAlphaBits = header.flags & 0xf;
  84711. var pixel_size = header.pixel_size >> 3;
  84712. var pixel_total = header.width * header.height * pixel_size;
  84713. // Read palettes
  84714. var palettes;
  84715. if (use_pal) {
  84716. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84717. }
  84718. // Read LRE
  84719. if (use_rle) {
  84720. pixel_data = new Uint8Array(pixel_total);
  84721. var c, count, i;
  84722. var localOffset = 0;
  84723. var pixels = new Uint8Array(pixel_size);
  84724. while (offset < pixel_total && localOffset < pixel_total) {
  84725. c = data[offset++];
  84726. count = (c & 0x7f) + 1;
  84727. // RLE pixels
  84728. if (c & 0x80) {
  84729. // Bind pixel tmp array
  84730. for (i = 0; i < pixel_size; ++i) {
  84731. pixels[i] = data[offset++];
  84732. }
  84733. // Copy pixel array
  84734. for (i = 0; i < count; ++i) {
  84735. pixel_data.set(pixels, localOffset + i * pixel_size);
  84736. }
  84737. localOffset += pixel_size * count;
  84738. }
  84739. // Raw pixels
  84740. else {
  84741. count *= pixel_size;
  84742. for (i = 0; i < count; ++i) {
  84743. pixel_data[localOffset + i] = data[offset++];
  84744. }
  84745. localOffset += count;
  84746. }
  84747. }
  84748. }
  84749. // RAW Pixels
  84750. else {
  84751. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84752. }
  84753. // Load to texture
  84754. var x_start, y_start, x_step, y_step, y_end, x_end;
  84755. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84756. default:
  84757. case TGATools._ORIGIN_UL:
  84758. x_start = 0;
  84759. x_step = 1;
  84760. x_end = header.width;
  84761. y_start = 0;
  84762. y_step = 1;
  84763. y_end = header.height;
  84764. break;
  84765. case TGATools._ORIGIN_BL:
  84766. x_start = 0;
  84767. x_step = 1;
  84768. x_end = header.width;
  84769. y_start = header.height - 1;
  84770. y_step = -1;
  84771. y_end = -1;
  84772. break;
  84773. case TGATools._ORIGIN_UR:
  84774. x_start = header.width - 1;
  84775. x_step = -1;
  84776. x_end = -1;
  84777. y_start = 0;
  84778. y_step = 1;
  84779. y_end = header.height;
  84780. break;
  84781. case TGATools._ORIGIN_BR:
  84782. x_start = header.width - 1;
  84783. x_step = -1;
  84784. x_end = -1;
  84785. y_start = header.height - 1;
  84786. y_step = -1;
  84787. y_end = -1;
  84788. break;
  84789. }
  84790. // Load the specify method
  84791. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84792. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84793. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84794. };
  84795. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84796. var image = pixel_data, colormap = palettes;
  84797. var width = header.width, height = header.height;
  84798. var color, i = 0, x, y;
  84799. var imageData = new Uint8Array(width * height * 4);
  84800. for (y = y_start; y !== y_end; y += y_step) {
  84801. for (x = x_start; x !== x_end; x += x_step, i++) {
  84802. color = image[i];
  84803. imageData[(x + width * y) * 4 + 3] = 255;
  84804. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84805. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84806. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84807. }
  84808. }
  84809. return imageData;
  84810. };
  84811. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84812. var image = pixel_data;
  84813. var width = header.width, height = header.height;
  84814. var color, i = 0, x, y;
  84815. var imageData = new Uint8Array(width * height * 4);
  84816. for (y = y_start; y !== y_end; y += y_step) {
  84817. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84818. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84819. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84820. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84821. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84822. imageData[(x + width * y) * 4 + 0] = r;
  84823. imageData[(x + width * y) * 4 + 1] = g;
  84824. imageData[(x + width * y) * 4 + 2] = b;
  84825. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84826. }
  84827. }
  84828. return imageData;
  84829. };
  84830. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84831. var image = pixel_data;
  84832. var width = header.width, height = header.height;
  84833. var i = 0, x, y;
  84834. var imageData = new Uint8Array(width * height * 4);
  84835. for (y = y_start; y !== y_end; y += y_step) {
  84836. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84837. imageData[(x + width * y) * 4 + 3] = 255;
  84838. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84839. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84840. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84841. }
  84842. }
  84843. return imageData;
  84844. };
  84845. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84846. var image = pixel_data;
  84847. var width = header.width, height = header.height;
  84848. var i = 0, x, y;
  84849. var imageData = new Uint8Array(width * height * 4);
  84850. for (y = y_start; y !== y_end; y += y_step) {
  84851. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84852. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84853. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84854. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84855. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84856. }
  84857. }
  84858. return imageData;
  84859. };
  84860. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84861. var image = pixel_data;
  84862. var width = header.width, height = header.height;
  84863. var color, i = 0, x, y;
  84864. var imageData = new Uint8Array(width * height * 4);
  84865. for (y = y_start; y !== y_end; y += y_step) {
  84866. for (x = x_start; x !== x_end; x += x_step, i++) {
  84867. color = image[i];
  84868. imageData[(x + width * y) * 4 + 0] = color;
  84869. imageData[(x + width * y) * 4 + 1] = color;
  84870. imageData[(x + width * y) * 4 + 2] = color;
  84871. imageData[(x + width * y) * 4 + 3] = 255;
  84872. }
  84873. }
  84874. return imageData;
  84875. };
  84876. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84877. var image = pixel_data;
  84878. var width = header.width, height = header.height;
  84879. var i = 0, x, y;
  84880. var imageData = new Uint8Array(width * height * 4);
  84881. for (y = y_start; y !== y_end; y += y_step) {
  84882. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84883. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84884. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84885. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84886. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84887. }
  84888. }
  84889. return imageData;
  84890. };
  84891. //private static _TYPE_NO_DATA = 0;
  84892. TGATools._TYPE_INDEXED = 1;
  84893. TGATools._TYPE_RGB = 2;
  84894. TGATools._TYPE_GREY = 3;
  84895. TGATools._TYPE_RLE_INDEXED = 9;
  84896. TGATools._TYPE_RLE_RGB = 10;
  84897. TGATools._TYPE_RLE_GREY = 11;
  84898. TGATools._ORIGIN_MASK = 0x30;
  84899. TGATools._ORIGIN_SHIFT = 0x04;
  84900. TGATools._ORIGIN_BL = 0x00;
  84901. TGATools._ORIGIN_BR = 0x01;
  84902. TGATools._ORIGIN_UL = 0x02;
  84903. TGATools._ORIGIN_UR = 0x03;
  84904. return TGATools;
  84905. }());
  84906. BABYLON.TGATools = TGATools;
  84907. })(BABYLON || (BABYLON = {}));
  84908. //# sourceMappingURL=babylon.tga.js.map
  84909. var BABYLON;
  84910. (function (BABYLON) {
  84911. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84912. // All values and structures referenced from:
  84913. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84914. var DDS_MAGIC = 0x20534444;
  84915. var
  84916. //DDSD_CAPS = 0x1,
  84917. //DDSD_HEIGHT = 0x2,
  84918. //DDSD_WIDTH = 0x4,
  84919. //DDSD_PITCH = 0x8,
  84920. //DDSD_PIXELFORMAT = 0x1000,
  84921. DDSD_MIPMAPCOUNT = 0x20000;
  84922. //DDSD_LINEARSIZE = 0x80000,
  84923. //DDSD_DEPTH = 0x800000;
  84924. // var DDSCAPS_COMPLEX = 0x8,
  84925. // DDSCAPS_MIPMAP = 0x400000,
  84926. // DDSCAPS_TEXTURE = 0x1000;
  84927. var DDSCAPS2_CUBEMAP = 0x200;
  84928. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84929. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84930. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84931. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84932. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84933. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84934. // DDSCAPS2_VOLUME = 0x200000;
  84935. var
  84936. //DDPF_ALPHAPIXELS = 0x1,
  84937. //DDPF_ALPHA = 0x2,
  84938. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84939. //DDPF_YUV = 0x200,
  84940. DDPF_LUMINANCE = 0x20000;
  84941. function FourCCToInt32(value) {
  84942. return value.charCodeAt(0) +
  84943. (value.charCodeAt(1) << 8) +
  84944. (value.charCodeAt(2) << 16) +
  84945. (value.charCodeAt(3) << 24);
  84946. }
  84947. function Int32ToFourCC(value) {
  84948. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84949. }
  84950. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84951. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84952. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84953. var FOURCC_DX10 = FourCCToInt32("DX10");
  84954. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84955. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84956. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84957. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84958. var headerLengthInt = 31; // The header length in 32 bit ints
  84959. // Offsets into the header array
  84960. var off_magic = 0;
  84961. var off_size = 1;
  84962. var off_flags = 2;
  84963. var off_height = 3;
  84964. var off_width = 4;
  84965. var off_mipmapCount = 7;
  84966. var off_pfFlags = 20;
  84967. var off_pfFourCC = 21;
  84968. var off_RGBbpp = 22;
  84969. var off_RMask = 23;
  84970. var off_GMask = 24;
  84971. var off_BMask = 25;
  84972. var off_AMask = 26;
  84973. // var off_caps1 = 27;
  84974. var off_caps2 = 28;
  84975. // var off_caps3 = 29;
  84976. // var off_caps4 = 30;
  84977. var off_dxgiFormat = 32;
  84978. ;
  84979. var DDSTools = /** @class */ (function () {
  84980. function DDSTools() {
  84981. }
  84982. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84983. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84984. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84985. var mipmapCount = 1;
  84986. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84987. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84988. }
  84989. var fourCC = header[off_pfFourCC];
  84990. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84991. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84992. switch (fourCC) {
  84993. case FOURCC_D3DFMT_R16G16B16A16F:
  84994. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84995. break;
  84996. case FOURCC_D3DFMT_R32G32B32A32F:
  84997. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84998. break;
  84999. case FOURCC_DX10:
  85000. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  85001. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  85002. break;
  85003. }
  85004. }
  85005. return {
  85006. width: header[off_width],
  85007. height: header[off_height],
  85008. mipmapCount: mipmapCount,
  85009. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  85010. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  85011. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  85012. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  85013. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  85014. dxgiFormat: dxgiFormat,
  85015. textureType: textureType
  85016. };
  85017. };
  85018. DDSTools._ToHalfFloat = function (value) {
  85019. if (!DDSTools._FloatView) {
  85020. DDSTools._FloatView = new Float32Array(1);
  85021. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  85022. }
  85023. DDSTools._FloatView[0] = value;
  85024. var x = DDSTools._Int32View[0];
  85025. var bits = (x >> 16) & 0x8000; /* Get the sign */
  85026. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  85027. var e = (x >> 23) & 0xff; /* Using int is faster here */
  85028. /* If zero, or denormal, or exponent underflows too much for a denormal
  85029. * half, return signed zero. */
  85030. if (e < 103) {
  85031. return bits;
  85032. }
  85033. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  85034. if (e > 142) {
  85035. bits |= 0x7c00;
  85036. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  85037. * not Inf, so make sure we set one mantissa bit too. */
  85038. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  85039. return bits;
  85040. }
  85041. /* If exponent underflows but not too much, return a denormal */
  85042. if (e < 113) {
  85043. m |= 0x0800;
  85044. /* Extra rounding may overflow and set mantissa to 0 and exponent
  85045. * to 1, which is OK. */
  85046. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  85047. return bits;
  85048. }
  85049. bits |= ((e - 112) << 10) | (m >> 1);
  85050. bits += m & 1;
  85051. return bits;
  85052. };
  85053. DDSTools._FromHalfFloat = function (value) {
  85054. var s = (value & 0x8000) >> 15;
  85055. var e = (value & 0x7C00) >> 10;
  85056. var f = value & 0x03FF;
  85057. if (e === 0) {
  85058. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  85059. }
  85060. else if (e == 0x1F) {
  85061. return f ? NaN : ((s ? -1 : 1) * Infinity);
  85062. }
  85063. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  85064. };
  85065. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85066. var destArray = new Float32Array(dataLength);
  85067. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85068. var index = 0;
  85069. for (var y = 0; y < height; y++) {
  85070. for (var x = 0; x < width; x++) {
  85071. var srcPos = (x + y * width) * 4;
  85072. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  85073. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  85074. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  85075. if (DDSTools.StoreLODInAlphaChannel) {
  85076. destArray[index + 3] = lod;
  85077. }
  85078. else {
  85079. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  85080. }
  85081. index += 4;
  85082. }
  85083. }
  85084. return destArray;
  85085. };
  85086. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85087. if (DDSTools.StoreLODInAlphaChannel) {
  85088. var destArray = new Uint16Array(dataLength);
  85089. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85090. var index = 0;
  85091. for (var y = 0; y < height; y++) {
  85092. for (var x = 0; x < width; x++) {
  85093. var srcPos = (x + y * width) * 4;
  85094. destArray[index] = srcData[srcPos];
  85095. destArray[index + 1] = srcData[srcPos + 1];
  85096. destArray[index + 2] = srcData[srcPos + 2];
  85097. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  85098. index += 4;
  85099. }
  85100. }
  85101. return destArray;
  85102. }
  85103. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  85104. };
  85105. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85106. if (DDSTools.StoreLODInAlphaChannel) {
  85107. var destArray = new Float32Array(dataLength);
  85108. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85109. var index = 0;
  85110. for (var y = 0; y < height; y++) {
  85111. for (var x = 0; x < width; x++) {
  85112. var srcPos = (x + y * width) * 4;
  85113. destArray[index] = srcData[srcPos];
  85114. destArray[index + 1] = srcData[srcPos + 1];
  85115. destArray[index + 2] = srcData[srcPos + 2];
  85116. destArray[index + 3] = lod;
  85117. index += 4;
  85118. }
  85119. }
  85120. return destArray;
  85121. }
  85122. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  85123. };
  85124. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85125. var destArray = new Uint8Array(dataLength);
  85126. var srcData = new Float32Array(arrayBuffer, dataOffset);
  85127. var index = 0;
  85128. for (var y = 0; y < height; y++) {
  85129. for (var x = 0; x < width; x++) {
  85130. var srcPos = (x + y * width) * 4;
  85131. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  85132. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  85133. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  85134. if (DDSTools.StoreLODInAlphaChannel) {
  85135. destArray[index + 3] = lod;
  85136. }
  85137. else {
  85138. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  85139. }
  85140. index += 4;
  85141. }
  85142. }
  85143. return destArray;
  85144. };
  85145. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  85146. var destArray = new Uint8Array(dataLength);
  85147. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  85148. var index = 0;
  85149. for (var y = 0; y < height; y++) {
  85150. for (var x = 0; x < width; x++) {
  85151. var srcPos = (x + y * width) * 4;
  85152. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  85153. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  85154. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  85155. if (DDSTools.StoreLODInAlphaChannel) {
  85156. destArray[index + 3] = lod;
  85157. }
  85158. else {
  85159. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  85160. }
  85161. index += 4;
  85162. }
  85163. }
  85164. return destArray;
  85165. };
  85166. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  85167. var byteArray = new Uint8Array(dataLength);
  85168. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85169. var index = 0;
  85170. for (var y = 0; y < height; y++) {
  85171. for (var x = 0; x < width; x++) {
  85172. var srcPos = (x + y * width) * 4;
  85173. byteArray[index] = srcData[srcPos + rOffset];
  85174. byteArray[index + 1] = srcData[srcPos + gOffset];
  85175. byteArray[index + 2] = srcData[srcPos + bOffset];
  85176. byteArray[index + 3] = srcData[srcPos + aOffset];
  85177. index += 4;
  85178. }
  85179. }
  85180. return byteArray;
  85181. };
  85182. DDSTools._ExtractLongWordOrder = function (value) {
  85183. if (value === 0 || value === 255 || value === -16777216) {
  85184. return 0;
  85185. }
  85186. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  85187. };
  85188. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  85189. var byteArray = new Uint8Array(dataLength);
  85190. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85191. var index = 0;
  85192. for (var y = 0; y < height; y++) {
  85193. for (var x = 0; x < width; x++) {
  85194. var srcPos = (x + y * width) * 3;
  85195. byteArray[index] = srcData[srcPos + rOffset];
  85196. byteArray[index + 1] = srcData[srcPos + gOffset];
  85197. byteArray[index + 2] = srcData[srcPos + bOffset];
  85198. index += 3;
  85199. }
  85200. }
  85201. return byteArray;
  85202. };
  85203. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  85204. var byteArray = new Uint8Array(dataLength);
  85205. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  85206. var index = 0;
  85207. for (var y = 0; y < height; y++) {
  85208. for (var x = 0; x < width; x++) {
  85209. var srcPos = (x + y * width);
  85210. byteArray[index] = srcData[srcPos];
  85211. index++;
  85212. }
  85213. }
  85214. return byteArray;
  85215. };
  85216. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  85217. if (lodIndex === void 0) { lodIndex = -1; }
  85218. var sphericalPolynomialFaces = null;
  85219. if (info.sphericalPolynomial) {
  85220. sphericalPolynomialFaces = new Array();
  85221. }
  85222. var ext = engine.getCaps().s3tc;
  85223. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  85224. var fourCC, width, height, dataLength = 0, dataOffset;
  85225. var byteArray, mipmapCount, mip;
  85226. var internalFormat = 0;
  85227. var format = 0;
  85228. var blockBytes = 1;
  85229. if (header[off_magic] !== DDS_MAGIC) {
  85230. BABYLON.Tools.Error("Invalid magic number in DDS header");
  85231. return;
  85232. }
  85233. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  85234. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  85235. return;
  85236. }
  85237. if (info.isCompressed && !ext) {
  85238. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  85239. return;
  85240. }
  85241. var bpp = header[off_RGBbpp];
  85242. dataOffset = header[off_size] + 4;
  85243. var computeFormats = false;
  85244. if (info.isFourCC) {
  85245. fourCC = header[off_pfFourCC];
  85246. switch (fourCC) {
  85247. case FOURCC_DXT1:
  85248. blockBytes = 8;
  85249. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  85250. break;
  85251. case FOURCC_DXT3:
  85252. blockBytes = 16;
  85253. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  85254. break;
  85255. case FOURCC_DXT5:
  85256. blockBytes = 16;
  85257. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  85258. break;
  85259. case FOURCC_D3DFMT_R16G16B16A16F:
  85260. computeFormats = true;
  85261. break;
  85262. case FOURCC_D3DFMT_R32G32B32A32F:
  85263. computeFormats = true;
  85264. break;
  85265. case FOURCC_DX10:
  85266. // There is an additionnal header so dataOffset need to be changed
  85267. dataOffset += 5 * 4; // 5 uints
  85268. var supported = false;
  85269. switch (info.dxgiFormat) {
  85270. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  85271. computeFormats = true;
  85272. supported = true;
  85273. break;
  85274. case DXGI_FORMAT_B8G8R8X8_UNORM:
  85275. info.isRGB = true;
  85276. info.isFourCC = false;
  85277. bpp = 32;
  85278. supported = true;
  85279. break;
  85280. }
  85281. if (supported) {
  85282. break;
  85283. }
  85284. default:
  85285. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  85286. return;
  85287. }
  85288. }
  85289. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  85290. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  85291. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  85292. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  85293. if (computeFormats) {
  85294. format = engine._getWebGLTextureType(info.textureType);
  85295. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85296. }
  85297. mipmapCount = 1;
  85298. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  85299. mipmapCount = Math.max(1, header[off_mipmapCount]);
  85300. }
  85301. for (var face = 0; face < faces; face++) {
  85302. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  85303. width = header[off_width];
  85304. height = header[off_height];
  85305. for (mip = 0; mip < mipmapCount; ++mip) {
  85306. if (lodIndex === -1 || lodIndex === mip) {
  85307. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  85308. var i = (lodIndex === -1) ? mip : 0;
  85309. if (!info.isCompressed && info.isFourCC) {
  85310. dataLength = width * height * 4;
  85311. var floatArray = null;
  85312. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  85313. if (bpp === 128) {
  85314. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85315. if (sphericalPolynomialFaces && i == 0) {
  85316. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85317. }
  85318. }
  85319. else if (bpp === 64) {
  85320. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85321. if (sphericalPolynomialFaces && i == 0) {
  85322. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85323. }
  85324. }
  85325. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  85326. format = engine._getWebGLTextureType(info.textureType);
  85327. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85328. }
  85329. else {
  85330. if (bpp === 128) {
  85331. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85332. if (sphericalPolynomialFaces && i == 0) {
  85333. sphericalPolynomialFaces.push(floatArray);
  85334. }
  85335. }
  85336. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  85337. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85338. if (sphericalPolynomialFaces && i == 0) {
  85339. sphericalPolynomialFaces.push(floatArray);
  85340. }
  85341. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  85342. format = engine._getWebGLTextureType(info.textureType);
  85343. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  85344. }
  85345. else { // 64
  85346. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  85347. if (sphericalPolynomialFaces && i == 0) {
  85348. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  85349. }
  85350. }
  85351. }
  85352. if (floatArray) {
  85353. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  85354. }
  85355. }
  85356. else if (info.isRGB) {
  85357. if (bpp === 24) {
  85358. dataLength = width * height * 3;
  85359. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  85360. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  85361. }
  85362. else { // 32
  85363. dataLength = width * height * 4;
  85364. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  85365. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  85366. }
  85367. }
  85368. else if (info.isLuminance) {
  85369. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  85370. var unpaddedRowSize = width;
  85371. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  85372. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  85373. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  85374. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  85375. }
  85376. else {
  85377. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  85378. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  85379. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  85380. }
  85381. }
  85382. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  85383. width *= 0.5;
  85384. height *= 0.5;
  85385. width = Math.max(1.0, width);
  85386. height = Math.max(1.0, height);
  85387. }
  85388. if (currentFace !== undefined) {
  85389. // Loading a single face
  85390. break;
  85391. }
  85392. }
  85393. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  85394. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  85395. size: header[off_width],
  85396. right: sphericalPolynomialFaces[0],
  85397. left: sphericalPolynomialFaces[1],
  85398. up: sphericalPolynomialFaces[2],
  85399. down: sphericalPolynomialFaces[3],
  85400. front: sphericalPolynomialFaces[4],
  85401. back: sphericalPolynomialFaces[5],
  85402. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  85403. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  85404. gammaSpace: false,
  85405. });
  85406. }
  85407. else {
  85408. info.sphericalPolynomial = undefined;
  85409. }
  85410. };
  85411. DDSTools.StoreLODInAlphaChannel = false;
  85412. return DDSTools;
  85413. }());
  85414. BABYLON.DDSTools = DDSTools;
  85415. })(BABYLON || (BABYLON = {}));
  85416. //# sourceMappingURL=babylon.dds.js.map
  85417. var BABYLON;
  85418. (function (BABYLON) {
  85419. /**
  85420. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  85421. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  85422. */
  85423. var KhronosTextureContainer = /** @class */ (function () {
  85424. /**
  85425. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  85426. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  85427. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  85428. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  85429. */
  85430. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  85431. this.arrayBuffer = arrayBuffer;
  85432. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  85433. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  85434. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  85435. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  85436. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  85437. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  85438. BABYLON.Tools.Error("texture missing KTX identifier");
  85439. return;
  85440. }
  85441. // load the reset of the header in native 32 bit int
  85442. var header = new Int32Array(this.arrayBuffer, 12, 13);
  85443. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  85444. var oppositeEndianess = header[0] === 0x01020304;
  85445. // read all the header elements in order they exist in the file, without modification (sans endainness)
  85446. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  85447. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  85448. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  85449. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  85450. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  85451. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  85452. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  85453. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  85454. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  85455. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  85456. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  85457. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  85458. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  85459. if (this.glType !== 0) {
  85460. BABYLON.Tools.Error("only compressed formats currently supported");
  85461. return;
  85462. }
  85463. else {
  85464. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  85465. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  85466. }
  85467. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  85468. BABYLON.Tools.Error("only 2D textures currently supported");
  85469. return;
  85470. }
  85471. if (this.numberOfArrayElements !== 0) {
  85472. BABYLON.Tools.Error("texture arrays not currently supported");
  85473. return;
  85474. }
  85475. if (this.numberOfFaces !== facesExpected) {
  85476. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  85477. return;
  85478. }
  85479. // we now have a completely validated file, so could use existence of loadType as success
  85480. // would need to make this more elaborate & adjust checks above to support more than one load type
  85481. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  85482. }
  85483. // not as fast hardware based, but will probably never need to use
  85484. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  85485. return ((val & 0xFF) << 24)
  85486. | ((val & 0xFF00) << 8)
  85487. | ((val >> 8) & 0xFF00)
  85488. | ((val >> 24) & 0xFF);
  85489. };
  85490. /**
  85491. * It is assumed that the texture has already been created & is currently bound
  85492. */
  85493. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  85494. switch (this.loadType) {
  85495. case KhronosTextureContainer.COMPRESSED_2D:
  85496. this._upload2DCompressedLevels(gl, loadMipmaps);
  85497. break;
  85498. case KhronosTextureContainer.TEX_2D:
  85499. case KhronosTextureContainer.COMPRESSED_3D:
  85500. case KhronosTextureContainer.TEX_3D:
  85501. }
  85502. };
  85503. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  85504. // initialize width & height for level 1
  85505. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  85506. var width = this.pixelWidth;
  85507. var height = this.pixelHeight;
  85508. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  85509. for (var level = 0; level < mipmapCount; level++) {
  85510. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  85511. for (var face = 0; face < this.numberOfFaces; face++) {
  85512. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  85513. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  85514. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  85515. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  85516. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  85517. }
  85518. width = Math.max(1.0, width * 0.5);
  85519. height = Math.max(1.0, height * 0.5);
  85520. }
  85521. };
  85522. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  85523. // load types
  85524. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  85525. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  85526. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  85527. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  85528. return KhronosTextureContainer;
  85529. }());
  85530. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  85531. })(BABYLON || (BABYLON = {}));
  85532. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  85533. var BABYLON;
  85534. (function (BABYLON) {
  85535. var Debug;
  85536. (function (Debug) {
  85537. /**
  85538. * Class used to render a debug view of a given skeleton
  85539. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  85540. */
  85541. var SkeletonViewer = /** @class */ (function () {
  85542. /**
  85543. * Creates a new SkeletonViewer
  85544. * @param skeleton defines the skeleton to render
  85545. * @param mesh defines the mesh attached to the skeleton
  85546. * @param scene defines the hosting scene
  85547. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  85548. * @param renderingGroupId defines the rendering group id to use with the viewer
  85549. */
  85550. function SkeletonViewer(
  85551. /** defines the skeleton to render */
  85552. skeleton,
  85553. /** defines the mesh attached to the skeleton */
  85554. mesh, scene,
  85555. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  85556. autoUpdateBonesMatrices,
  85557. /** defines the rendering group id to use with the viewer */
  85558. renderingGroupId) {
  85559. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  85560. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  85561. this.skeleton = skeleton;
  85562. this.mesh = mesh;
  85563. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  85564. this.renderingGroupId = renderingGroupId;
  85565. /** Gets or sets the color used to render the skeleton */
  85566. this.color = BABYLON.Color3.White();
  85567. this._debugLines = new Array();
  85568. this._isEnabled = false;
  85569. this._scene = scene;
  85570. this.update();
  85571. this._renderFunction = this.update.bind(this);
  85572. }
  85573. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  85574. get: function () {
  85575. return this._isEnabled;
  85576. },
  85577. /** Gets or sets a boolean indicating if the viewer is enabled */
  85578. set: function (value) {
  85579. if (this._isEnabled === value) {
  85580. return;
  85581. }
  85582. this._isEnabled = value;
  85583. if (value) {
  85584. this._scene.registerBeforeRender(this._renderFunction);
  85585. }
  85586. else {
  85587. this._scene.unregisterBeforeRender(this._renderFunction);
  85588. }
  85589. },
  85590. enumerable: true,
  85591. configurable: true
  85592. });
  85593. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85594. if (x === void 0) { x = 0; }
  85595. if (y === void 0) { y = 0; }
  85596. if (z === void 0) { z = 0; }
  85597. var tmat = BABYLON.Tmp.Matrix[0];
  85598. var parentBone = bone.getParent();
  85599. tmat.copyFrom(bone.getLocalMatrix());
  85600. if (x !== 0 || y !== 0 || z !== 0) {
  85601. var tmat2 = BABYLON.Tmp.Matrix[1];
  85602. BABYLON.Matrix.IdentityToRef(tmat2);
  85603. tmat2.m[12] = x;
  85604. tmat2.m[13] = y;
  85605. tmat2.m[14] = z;
  85606. tmat2.multiplyToRef(tmat, tmat);
  85607. }
  85608. if (parentBone) {
  85609. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85610. }
  85611. tmat.multiplyToRef(meshMat, tmat);
  85612. position.x = tmat.m[12];
  85613. position.y = tmat.m[13];
  85614. position.z = tmat.m[14];
  85615. };
  85616. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85617. var len = bones.length;
  85618. var meshPos = this.mesh.position;
  85619. for (var i = 0; i < len; i++) {
  85620. var bone = bones[i];
  85621. var points = this._debugLines[i];
  85622. if (!points) {
  85623. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85624. this._debugLines[i] = points;
  85625. }
  85626. this._getBonePosition(points[0], bone, meshMat);
  85627. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85628. points[0].subtractInPlace(meshPos);
  85629. points[1].subtractInPlace(meshPos);
  85630. }
  85631. };
  85632. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85633. var len = bones.length;
  85634. var boneNum = 0;
  85635. var meshPos = this.mesh.position;
  85636. for (var i = len - 1; i >= 0; i--) {
  85637. var childBone = bones[i];
  85638. var parentBone = childBone.getParent();
  85639. if (!parentBone) {
  85640. continue;
  85641. }
  85642. var points = this._debugLines[boneNum];
  85643. if (!points) {
  85644. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85645. this._debugLines[boneNum] = points;
  85646. }
  85647. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85648. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85649. points[0].subtractInPlace(meshPos);
  85650. points[1].subtractInPlace(meshPos);
  85651. boneNum++;
  85652. }
  85653. };
  85654. /** Update the viewer to sync with current skeleton state */
  85655. SkeletonViewer.prototype.update = function () {
  85656. if (this.autoUpdateBonesMatrices) {
  85657. this.skeleton.computeAbsoluteTransforms();
  85658. }
  85659. if (this.skeleton.bones[0].length === undefined) {
  85660. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85661. }
  85662. else {
  85663. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85664. }
  85665. if (!this._debugMesh) {
  85666. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85667. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85668. }
  85669. else {
  85670. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85671. }
  85672. this._debugMesh.position.copyFrom(this.mesh.position);
  85673. this._debugMesh.color = this.color;
  85674. };
  85675. /** Release associated resources */
  85676. SkeletonViewer.prototype.dispose = function () {
  85677. if (this._debugMesh) {
  85678. this.isEnabled = false;
  85679. this._debugMesh.dispose();
  85680. this._debugMesh = null;
  85681. }
  85682. };
  85683. return SkeletonViewer;
  85684. }());
  85685. Debug.SkeletonViewer = SkeletonViewer;
  85686. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85687. })(BABYLON || (BABYLON = {}));
  85688. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85689. /**
  85690. * Module Debug contains the (visual) components to debug a scene correctly
  85691. */
  85692. var BABYLON;
  85693. (function (BABYLON) {
  85694. var Debug;
  85695. (function (Debug) {
  85696. /**
  85697. * The Axes viewer will show 3 axes in a specific point in space
  85698. */
  85699. var AxesViewer = /** @class */ (function () {
  85700. /**
  85701. * Creates a new AxesViewer
  85702. * @param scene defines the hosting scene
  85703. * @param scaleLines defines a number used to scale line length (1 by default)
  85704. */
  85705. function AxesViewer(scene, scaleLines) {
  85706. if (scaleLines === void 0) { scaleLines = 1; }
  85707. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85708. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85709. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85710. /**
  85711. * Gets or sets a number used to scale line length
  85712. */
  85713. this.scaleLines = 1;
  85714. this.scaleLines = scaleLines;
  85715. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85716. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85717. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85718. this._xmesh.renderingGroupId = 2;
  85719. this._ymesh.renderingGroupId = 2;
  85720. this._zmesh.renderingGroupId = 2;
  85721. this._xmesh.material.checkReadyOnlyOnce = true;
  85722. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85723. this._ymesh.material.checkReadyOnlyOnce = true;
  85724. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85725. this._zmesh.material.checkReadyOnlyOnce = true;
  85726. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85727. this.scene = scene;
  85728. }
  85729. /**
  85730. * Force the viewer to update
  85731. * @param position defines the position of the viewer
  85732. * @param xaxis defines the x axis of the viewer
  85733. * @param yaxis defines the y axis of the viewer
  85734. * @param zaxis defines the z axis of the viewer
  85735. */
  85736. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85737. var scaleLines = this.scaleLines;
  85738. if (this._xmesh) {
  85739. this._xmesh.position.copyFrom(position);
  85740. }
  85741. if (this._ymesh) {
  85742. this._ymesh.position.copyFrom(position);
  85743. }
  85744. if (this._zmesh) {
  85745. this._zmesh.position.copyFrom(position);
  85746. }
  85747. var point2 = this._xline[1];
  85748. point2.x = xaxis.x * scaleLines;
  85749. point2.y = xaxis.y * scaleLines;
  85750. point2.z = xaxis.z * scaleLines;
  85751. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85752. point2 = this._yline[1];
  85753. point2.x = yaxis.x * scaleLines;
  85754. point2.y = yaxis.y * scaleLines;
  85755. point2.z = yaxis.z * scaleLines;
  85756. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85757. point2 = this._zline[1];
  85758. point2.x = zaxis.x * scaleLines;
  85759. point2.y = zaxis.y * scaleLines;
  85760. point2.z = zaxis.z * scaleLines;
  85761. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85762. };
  85763. /** Releases resources */
  85764. AxesViewer.prototype.dispose = function () {
  85765. if (this._xmesh) {
  85766. this._xmesh.dispose();
  85767. }
  85768. if (this._ymesh) {
  85769. this._ymesh.dispose();
  85770. }
  85771. if (this._zmesh) {
  85772. this._zmesh.dispose();
  85773. }
  85774. this._xmesh = null;
  85775. this._ymesh = null;
  85776. this._zmesh = null;
  85777. this.scene = null;
  85778. };
  85779. return AxesViewer;
  85780. }());
  85781. Debug.AxesViewer = AxesViewer;
  85782. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85783. })(BABYLON || (BABYLON = {}));
  85784. //# sourceMappingURL=babylon.axesViewer.js.map
  85785. var BABYLON;
  85786. (function (BABYLON) {
  85787. var Debug;
  85788. (function (Debug) {
  85789. /**
  85790. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85791. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  85792. */
  85793. var BoneAxesViewer = /** @class */ (function (_super) {
  85794. __extends(BoneAxesViewer, _super);
  85795. /**
  85796. * Creates a new BoneAxesViewer
  85797. * @param scene defines the hosting scene
  85798. * @param bone defines the target bone
  85799. * @param mesh defines the target mesh
  85800. * @param scaleLines defines a scaling factor for line length (1 by default)
  85801. */
  85802. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85803. if (scaleLines === void 0) { scaleLines = 1; }
  85804. var _this = _super.call(this, scene, scaleLines) || this;
  85805. /** Gets current position */
  85806. _this.pos = BABYLON.Vector3.Zero();
  85807. /** Gets direction of X axis */
  85808. _this.xaxis = BABYLON.Vector3.Zero();
  85809. /** Gets direction of Y axis */
  85810. _this.yaxis = BABYLON.Vector3.Zero();
  85811. /** Gets direction of Z axis */
  85812. _this.zaxis = BABYLON.Vector3.Zero();
  85813. _this.mesh = mesh;
  85814. _this.bone = bone;
  85815. return _this;
  85816. }
  85817. /**
  85818. * Force the viewer to update
  85819. */
  85820. BoneAxesViewer.prototype.update = function () {
  85821. if (!this.mesh || !this.bone) {
  85822. return;
  85823. }
  85824. var bone = this.bone;
  85825. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85826. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85827. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85828. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85829. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85830. };
  85831. /** Releases resources */
  85832. BoneAxesViewer.prototype.dispose = function () {
  85833. if (this.mesh) {
  85834. this.mesh = null;
  85835. this.bone = null;
  85836. _super.prototype.dispose.call(this);
  85837. }
  85838. };
  85839. return BoneAxesViewer;
  85840. }(Debug.AxesViewer));
  85841. Debug.BoneAxesViewer = BoneAxesViewer;
  85842. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85843. })(BABYLON || (BABYLON = {}));
  85844. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85845. var BABYLON;
  85846. (function (BABYLON) {
  85847. var RayHelper = /** @class */ (function () {
  85848. function RayHelper(ray) {
  85849. this.ray = ray;
  85850. }
  85851. RayHelper.CreateAndShow = function (ray, scene, color) {
  85852. var helper = new RayHelper(ray);
  85853. helper.show(scene, color);
  85854. return helper;
  85855. };
  85856. RayHelper.prototype.show = function (scene, color) {
  85857. if (!this._renderFunction && this.ray) {
  85858. var ray = this.ray;
  85859. this._renderFunction = this._render.bind(this);
  85860. this._scene = scene;
  85861. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85862. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85863. if (this._renderFunction) {
  85864. this._scene.registerBeforeRender(this._renderFunction);
  85865. }
  85866. }
  85867. if (color && this._renderLine) {
  85868. this._renderLine.color.copyFrom(color);
  85869. }
  85870. };
  85871. RayHelper.prototype.hide = function () {
  85872. if (this._renderFunction && this._scene) {
  85873. this._scene.unregisterBeforeRender(this._renderFunction);
  85874. this._scene = null;
  85875. this._renderFunction = null;
  85876. if (this._renderLine) {
  85877. this._renderLine.dispose();
  85878. this._renderLine = null;
  85879. }
  85880. this._renderPoints = [];
  85881. }
  85882. };
  85883. RayHelper.prototype._render = function () {
  85884. var ray = this.ray;
  85885. if (!ray) {
  85886. return;
  85887. }
  85888. var point = this._renderPoints[1];
  85889. var len = Math.min(ray.length, 1000000);
  85890. point.copyFrom(ray.direction);
  85891. point.scaleInPlace(len);
  85892. point.addInPlace(ray.origin);
  85893. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85894. };
  85895. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85896. this._attachedToMesh = mesh;
  85897. var ray = this.ray;
  85898. if (!ray) {
  85899. return;
  85900. }
  85901. if (!ray.direction) {
  85902. ray.direction = BABYLON.Vector3.Zero();
  85903. }
  85904. if (!ray.origin) {
  85905. ray.origin = BABYLON.Vector3.Zero();
  85906. }
  85907. if (length) {
  85908. ray.length = length;
  85909. }
  85910. if (!meshSpaceOrigin) {
  85911. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85912. }
  85913. if (!meshSpaceDirection) {
  85914. // -1 so that this will work with Mesh.lookAt
  85915. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85916. }
  85917. if (!this._meshSpaceDirection) {
  85918. this._meshSpaceDirection = meshSpaceDirection.clone();
  85919. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85920. }
  85921. else {
  85922. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85923. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85924. }
  85925. if (!this._updateToMeshFunction) {
  85926. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85927. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85928. }
  85929. this._updateToMesh();
  85930. };
  85931. RayHelper.prototype.detachFromMesh = function () {
  85932. if (this._attachedToMesh) {
  85933. if (this._updateToMeshFunction) {
  85934. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85935. }
  85936. this._attachedToMesh = null;
  85937. this._updateToMeshFunction = null;
  85938. }
  85939. };
  85940. RayHelper.prototype._updateToMesh = function () {
  85941. var ray = this.ray;
  85942. if (!this._attachedToMesh || !ray) {
  85943. return;
  85944. }
  85945. if (this._attachedToMesh._isDisposed) {
  85946. this.detachFromMesh();
  85947. return;
  85948. }
  85949. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85950. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85951. };
  85952. RayHelper.prototype.dispose = function () {
  85953. this.hide();
  85954. this.detachFromMesh();
  85955. this.ray = null;
  85956. };
  85957. return RayHelper;
  85958. }());
  85959. BABYLON.RayHelper = RayHelper;
  85960. })(BABYLON || (BABYLON = {}));
  85961. //# sourceMappingURL=babylon.rayHelper.js.map
  85962. var BABYLON;
  85963. (function (BABYLON) {
  85964. // load the inspector using require, if not present in the global namespace.
  85965. var DebugLayer = /** @class */ (function () {
  85966. function DebugLayer(scene) {
  85967. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85968. this._scene = scene;
  85969. // load inspector using require, if it doesn't exist on the global namespace.
  85970. }
  85971. /** Creates the inspector window. */
  85972. DebugLayer.prototype._createInspector = function (config) {
  85973. if (config === void 0) { config = {}; }
  85974. var popup = config.popup || false;
  85975. var initialTab = config.initialTab || 0;
  85976. var parentElement = config.parentElement || null;
  85977. if (!this._inspector) {
  85978. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85979. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85980. } // else nothing to do,; instance is already existing
  85981. };
  85982. DebugLayer.prototype.isVisible = function () {
  85983. if (!this._inspector) {
  85984. return false;
  85985. }
  85986. return true;
  85987. };
  85988. DebugLayer.prototype.hide = function () {
  85989. if (this._inspector) {
  85990. try {
  85991. this._inspector.dispose();
  85992. }
  85993. catch (e) {
  85994. // If the inspector has been removed directly from the inspector tool
  85995. }
  85996. this._inspector = null;
  85997. }
  85998. };
  85999. DebugLayer.prototype.show = function (config) {
  86000. if (config === void 0) { config = {}; }
  86001. if (typeof this.BJSINSPECTOR == 'undefined') {
  86002. // Load inspector and add it to the DOM
  86003. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  86004. }
  86005. else {
  86006. // Otherwise creates the inspector
  86007. this._createInspector(config);
  86008. }
  86009. };
  86010. /**
  86011. * Gets the active tab
  86012. * @return the index of the active tab or -1 if the inspector is hidden
  86013. */
  86014. DebugLayer.prototype.getActiveTab = function () {
  86015. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  86016. };
  86017. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  86018. return DebugLayer;
  86019. }());
  86020. BABYLON.DebugLayer = DebugLayer;
  86021. })(BABYLON || (BABYLON = {}));
  86022. //# sourceMappingURL=babylon.debugLayer.js.map
  86023. var BABYLON;
  86024. (function (BABYLON) {
  86025. var Debug;
  86026. (function (Debug) {
  86027. /**
  86028. * Used to show the physics impostor around the specific mesh
  86029. */
  86030. var PhysicsViewer = /** @class */ (function () {
  86031. /**
  86032. * Creates a new PhysicsViewer
  86033. * @param scene defines the hosting scene
  86034. */
  86035. function PhysicsViewer(scene) {
  86036. /** @hidden */
  86037. this._impostors = [];
  86038. /** @hidden */
  86039. this._meshes = [];
  86040. /** @hidden */
  86041. this._numMeshes = 0;
  86042. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86043. var physicEngine = this._scene.getPhysicsEngine();
  86044. if (physicEngine) {
  86045. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  86046. }
  86047. }
  86048. /** @hidden */
  86049. PhysicsViewer.prototype._updateDebugMeshes = function () {
  86050. var plugin = this._physicsEnginePlugin;
  86051. for (var i = 0; i < this._numMeshes; i++) {
  86052. var impostor = this._impostors[i];
  86053. if (!impostor) {
  86054. continue;
  86055. }
  86056. if (impostor.isDisposed) {
  86057. this.hideImpostor(this._impostors[i--]);
  86058. }
  86059. else {
  86060. var mesh = this._meshes[i];
  86061. if (mesh && plugin) {
  86062. plugin.syncMeshWithImpostor(mesh, impostor);
  86063. }
  86064. }
  86065. }
  86066. };
  86067. /**
  86068. * Renders a specified physic impostor
  86069. * @param impostor defines the impostor to render
  86070. */
  86071. PhysicsViewer.prototype.showImpostor = function (impostor) {
  86072. if (!this._scene) {
  86073. return;
  86074. }
  86075. for (var i = 0; i < this._numMeshes; i++) {
  86076. if (this._impostors[i] == impostor) {
  86077. return;
  86078. }
  86079. }
  86080. var debugMesh = this._getDebugMesh(impostor, this._scene);
  86081. if (debugMesh) {
  86082. this._impostors[this._numMeshes] = impostor;
  86083. this._meshes[this._numMeshes] = debugMesh;
  86084. if (this._numMeshes === 0) {
  86085. this._renderFunction = this._updateDebugMeshes.bind(this);
  86086. this._scene.registerBeforeRender(this._renderFunction);
  86087. }
  86088. this._numMeshes++;
  86089. }
  86090. };
  86091. /**
  86092. * Hides a specified physic impostor
  86093. * @param impostor defines the impostor to hide
  86094. */
  86095. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  86096. if (!impostor || !this._scene) {
  86097. return;
  86098. }
  86099. var removed = false;
  86100. for (var i = 0; i < this._numMeshes; i++) {
  86101. if (this._impostors[i] == impostor) {
  86102. var mesh = this._meshes[i];
  86103. if (!mesh) {
  86104. continue;
  86105. }
  86106. this._scene.removeMesh(mesh);
  86107. mesh.dispose();
  86108. this._numMeshes--;
  86109. if (this._numMeshes > 0) {
  86110. this._meshes[i] = this._meshes[this._numMeshes];
  86111. this._impostors[i] = this._impostors[this._numMeshes];
  86112. this._meshes[this._numMeshes] = null;
  86113. this._impostors[this._numMeshes] = null;
  86114. }
  86115. else {
  86116. this._meshes[0] = null;
  86117. this._impostors[0] = null;
  86118. }
  86119. removed = true;
  86120. break;
  86121. }
  86122. }
  86123. if (removed && this._numMeshes === 0) {
  86124. this._scene.unregisterBeforeRender(this._renderFunction);
  86125. }
  86126. };
  86127. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  86128. if (!this._debugMaterial) {
  86129. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  86130. this._debugMaterial.wireframe = true;
  86131. }
  86132. return this._debugMaterial;
  86133. };
  86134. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  86135. if (!this._debugBoxMesh) {
  86136. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  86137. this._debugBoxMesh.renderingGroupId = 1;
  86138. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86139. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  86140. scene.removeMesh(this._debugBoxMesh);
  86141. }
  86142. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  86143. };
  86144. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  86145. if (!this._debugSphereMesh) {
  86146. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  86147. this._debugSphereMesh.renderingGroupId = 1;
  86148. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86149. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  86150. scene.removeMesh(this._debugSphereMesh);
  86151. }
  86152. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  86153. };
  86154. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  86155. var mesh = null;
  86156. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  86157. mesh = this._getDebugBoxMesh(scene);
  86158. impostor.getBoxSizeToRef(mesh.scaling);
  86159. }
  86160. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  86161. mesh = this._getDebugSphereMesh(scene);
  86162. var radius = impostor.getRadius();
  86163. mesh.scaling.x = radius * 2;
  86164. mesh.scaling.y = radius * 2;
  86165. mesh.scaling.z = radius * 2;
  86166. }
  86167. return mesh;
  86168. };
  86169. /** Releases all resources */
  86170. PhysicsViewer.prototype.dispose = function () {
  86171. for (var i = 0; i < this._numMeshes; i++) {
  86172. this.hideImpostor(this._impostors[i]);
  86173. }
  86174. if (this._debugBoxMesh) {
  86175. this._debugBoxMesh.dispose();
  86176. }
  86177. if (this._debugSphereMesh) {
  86178. this._debugSphereMesh.dispose();
  86179. }
  86180. if (this._debugMaterial) {
  86181. this._debugMaterial.dispose();
  86182. }
  86183. this._impostors.length = 0;
  86184. this._scene = null;
  86185. this._physicsEnginePlugin = null;
  86186. };
  86187. return PhysicsViewer;
  86188. }());
  86189. Debug.PhysicsViewer = PhysicsViewer;
  86190. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  86191. })(BABYLON || (BABYLON = {}));
  86192. //# sourceMappingURL=babylon.physicsViewer.js.map
  86193. var BABYLON;
  86194. (function (BABYLON) {
  86195. var BoundingBoxRenderer = /** @class */ (function () {
  86196. function BoundingBoxRenderer(scene) {
  86197. this.frontColor = new BABYLON.Color3(1, 1, 1);
  86198. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  86199. this.showBackLines = true;
  86200. this.renderList = new BABYLON.SmartArray(32);
  86201. this._vertexBuffers = {};
  86202. this._scene = scene;
  86203. }
  86204. BoundingBoxRenderer.prototype._prepareRessources = function () {
  86205. if (this._colorShader) {
  86206. return;
  86207. }
  86208. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  86209. attributes: [BABYLON.VertexBuffer.PositionKind],
  86210. uniforms: ["world", "viewProjection", "color"]
  86211. });
  86212. var engine = this._scene.getEngine();
  86213. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  86214. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  86215. this._createIndexBuffer();
  86216. };
  86217. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  86218. var engine = this._scene.getEngine();
  86219. 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]);
  86220. };
  86221. BoundingBoxRenderer.prototype._rebuild = function () {
  86222. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86223. if (vb) {
  86224. vb._rebuild();
  86225. }
  86226. this._createIndexBuffer();
  86227. };
  86228. BoundingBoxRenderer.prototype.reset = function () {
  86229. this.renderList.reset();
  86230. };
  86231. BoundingBoxRenderer.prototype.render = function () {
  86232. if (this.renderList.length === 0) {
  86233. return;
  86234. }
  86235. this._prepareRessources();
  86236. if (!this._colorShader.isReady()) {
  86237. return;
  86238. }
  86239. var engine = this._scene.getEngine();
  86240. engine.setDepthWrite(false);
  86241. this._colorShader._preBind();
  86242. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  86243. var boundingBox = this.renderList.data[boundingBoxIndex];
  86244. var min = boundingBox.minimum;
  86245. var max = boundingBox.maximum;
  86246. var diff = max.subtract(min);
  86247. var median = min.add(diff.scale(0.5));
  86248. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86249. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86250. .multiply(boundingBox.getWorldMatrix());
  86251. // VBOs
  86252. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86253. if (this.showBackLines) {
  86254. // Back
  86255. engine.setDepthFunctionToGreaterOrEqual();
  86256. this._scene.resetCachedMaterial();
  86257. this._colorShader.setColor4("color", this.backColor.toColor4());
  86258. this._colorShader.bind(worldMatrix);
  86259. // Draw order
  86260. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86261. }
  86262. // Front
  86263. engine.setDepthFunctionToLess();
  86264. this._scene.resetCachedMaterial();
  86265. this._colorShader.setColor4("color", this.frontColor.toColor4());
  86266. this._colorShader.bind(worldMatrix);
  86267. // Draw order
  86268. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86269. }
  86270. this._colorShader.unbind();
  86271. engine.setDepthFunctionToLessOrEqual();
  86272. engine.setDepthWrite(true);
  86273. };
  86274. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  86275. this._prepareRessources();
  86276. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  86277. return;
  86278. }
  86279. var engine = this._scene.getEngine();
  86280. engine.setDepthWrite(false);
  86281. engine.setColorWrite(false);
  86282. this._colorShader._preBind();
  86283. var boundingBox = mesh._boundingInfo.boundingBox;
  86284. var min = boundingBox.minimum;
  86285. var max = boundingBox.maximum;
  86286. var diff = max.subtract(min);
  86287. var median = min.add(diff.scale(0.5));
  86288. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  86289. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  86290. .multiply(boundingBox.getWorldMatrix());
  86291. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  86292. engine.setDepthFunctionToLess();
  86293. this._scene.resetCachedMaterial();
  86294. this._colorShader.bind(worldMatrix);
  86295. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  86296. this._colorShader.unbind();
  86297. engine.setDepthFunctionToLessOrEqual();
  86298. engine.setDepthWrite(true);
  86299. engine.setColorWrite(true);
  86300. };
  86301. BoundingBoxRenderer.prototype.dispose = function () {
  86302. if (!this._colorShader) {
  86303. return;
  86304. }
  86305. this.renderList.dispose();
  86306. this._colorShader.dispose();
  86307. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86308. if (buffer) {
  86309. buffer.dispose();
  86310. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86311. }
  86312. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86313. };
  86314. return BoundingBoxRenderer;
  86315. }());
  86316. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  86317. })(BABYLON || (BABYLON = {}));
  86318. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  86319. var BABYLON;
  86320. (function (BABYLON) {
  86321. /**
  86322. * Renders a layer on top of an existing scene
  86323. */
  86324. var UtilityLayerRenderer = /** @class */ (function () {
  86325. /**
  86326. * Instantiates a UtilityLayerRenderer
  86327. * @param originalScene the original scene that will be rendered on top of
  86328. */
  86329. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  86330. var _this = this;
  86331. this.originalScene = originalScene;
  86332. /**
  86333. * If the utility layer should automatically be rendered on top of existing scene
  86334. */
  86335. this.shouldRender = true;
  86336. /**
  86337. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  86338. */
  86339. this.onlyCheckPointerDownEvents = true;
  86340. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  86341. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  86342. originalScene.getEngine().scenes.pop();
  86343. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  86344. this.utilityLayerScene.detachControl();
  86345. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  86346. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  86347. if (!prePointerInfo.ray && utilityScenePick) {
  86348. prePointerInfo.ray = utilityScenePick.ray;
  86349. }
  86350. // always fire the prepointer oversvable
  86351. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  86352. // allow every non pointer down event to flow to the utility layer
  86353. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  86354. if (!prePointerInfo.skipOnPointerObservable) {
  86355. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  86356. }
  86357. return;
  86358. }
  86359. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  86360. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  86361. if (utilityScenePick && utilityScenePick.hit) {
  86362. if (!prePointerInfo.skipOnPointerObservable) {
  86363. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  86364. }
  86365. prePointerInfo.skipOnPointerObservable = true;
  86366. }
  86367. }
  86368. else {
  86369. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  86370. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  86371. if (originalScenePick && utilityScenePick) {
  86372. if (utilityScenePick.distance < originalScenePick.distance) {
  86373. if (!prePointerInfo.skipOnPointerObservable) {
  86374. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  86375. }
  86376. prePointerInfo.skipOnPointerObservable = true;
  86377. }
  86378. }
  86379. }
  86380. });
  86381. // Render directly on top of existing scene without clearing
  86382. this.utilityLayerScene.autoClear = false;
  86383. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  86384. if (_this.shouldRender) {
  86385. _this.render();
  86386. }
  86387. });
  86388. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  86389. _this.dispose();
  86390. });
  86391. this._updateCamera();
  86392. }
  86393. /**
  86394. * Renders the utility layers scene on top of the original scene
  86395. */
  86396. UtilityLayerRenderer.prototype.render = function () {
  86397. this._updateCamera();
  86398. this.utilityLayerScene.render(false);
  86399. };
  86400. /**
  86401. * Disposes of the renderer
  86402. */
  86403. UtilityLayerRenderer.prototype.dispose = function () {
  86404. if (this._afterRenderObserver) {
  86405. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  86406. }
  86407. if (this._sceneDisposeObserver) {
  86408. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86409. }
  86410. if (this._originalPointerObserver) {
  86411. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  86412. }
  86413. this.utilityLayerScene.dispose();
  86414. };
  86415. UtilityLayerRenderer.prototype._updateCamera = function () {
  86416. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  86417. };
  86418. return UtilityLayerRenderer;
  86419. }());
  86420. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  86421. })(BABYLON || (BABYLON = {}));
  86422. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  86423. var BABYLON;
  86424. (function (BABYLON) {
  86425. /**
  86426. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  86427. */
  86428. var PointerDragBehavior = /** @class */ (function () {
  86429. /**
  86430. * Creates a pointer drag behavior that can be attached to a mesh
  86431. * @param options The drag axis or normal of the plane that will be dragged across.
  86432. */
  86433. function PointerDragBehavior(options) {
  86434. this.options = options;
  86435. this._draggingID = -1;
  86436. /**
  86437. * Fires each time the attached mesh is dragged with the pointer
  86438. */
  86439. this.onDragObservable = new BABYLON.Observable();
  86440. /**
  86441. * Fires each time a drag begins (eg. mouse down on mesh)
  86442. */
  86443. this.onDragStartObservable = new BABYLON.Observable();
  86444. /**
  86445. * Fires each time a drag ends (eg. mouse release after drag)
  86446. */
  86447. this.onDragEndObservable = new BABYLON.Observable();
  86448. /**
  86449. * If the attached mesh should be moved when dragged
  86450. */
  86451. this.moveAttached = true;
  86452. /**
  86453. * Mesh with the position where the drag plane should be placed
  86454. */
  86455. this._dragPlaneParent = null;
  86456. /**
  86457. * If the drag behavior will react to drag events
  86458. */
  86459. this.enabled = true;
  86460. var optionCount = 0;
  86461. if (options.dragAxis) {
  86462. optionCount++;
  86463. }
  86464. if (options.dragPlaneNormal) {
  86465. optionCount++;
  86466. }
  86467. if (optionCount > 1) {
  86468. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  86469. }
  86470. if (optionCount < 1) {
  86471. throw "At least one drag mode option must be specified";
  86472. }
  86473. }
  86474. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  86475. /**
  86476. * The name of the behavior
  86477. */
  86478. get: function () {
  86479. return "PointerDrag";
  86480. },
  86481. enumerable: true,
  86482. configurable: true
  86483. });
  86484. /**
  86485. * Initializes the behavior
  86486. */
  86487. PointerDragBehavior.prototype.init = function () { };
  86488. /**
  86489. * Attaches the drag behavior the passed in mesh
  86490. * @param ownerNode The mesh that will be dragged around once attached
  86491. */
  86492. PointerDragBehavior.prototype.attach = function (ownerNode) {
  86493. var _this = this;
  86494. this._scene = ownerNode.getScene();
  86495. this._attachedNode = ownerNode;
  86496. // Initialize drag plane to not interfere with existing scene
  86497. if (!PointerDragBehavior._planeScene) {
  86498. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  86499. this._scene.getEngine().scenes.pop();
  86500. }
  86501. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", 1000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  86502. // State of the drag
  86503. var dragging = false;
  86504. var lastPosition = new BABYLON.Vector3(0, 0, 0);
  86505. var delta = new BABYLON.Vector3(0, 0, 0);
  86506. var pickPredicate = function (m) {
  86507. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  86508. };
  86509. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  86510. if (!_this.enabled) {
  86511. return;
  86512. }
  86513. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  86514. if (!dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  86515. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  86516. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  86517. if (pickedPoint) {
  86518. dragging = true;
  86519. _this._draggingID = pointerInfo.event.pointerId;
  86520. lastPosition.copyFrom(pickedPoint);
  86521. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint });
  86522. }
  86523. }
  86524. }
  86525. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  86526. if (_this._draggingID == pointerInfo.event.pointerId) {
  86527. dragging = false;
  86528. _this._draggingID = -1;
  86529. _this.onDragEndObservable.notifyObservers({ dragPlanePoint: lastPosition });
  86530. }
  86531. }
  86532. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  86533. if (_this._draggingID == pointerInfo.event.pointerId && dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  86534. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  86535. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray);
  86536. if (pickedPoint) {
  86537. // depending on the drag mode option drag accordingly
  86538. if (_this.options.dragAxis) {
  86539. //get the closest point on the dragaxis from the selected mesh to the picked point location
  86540. // https://www.opengl.org/discussion_boards/showthread.php/159717-Closest-point-on-a-Vector-to-a-point
  86541. _this.options.dragAxis.scaleToRef(BABYLON.Vector3.Dot(pickedPoint.subtract(lastPosition), _this.options.dragAxis), delta);
  86542. }
  86543. else {
  86544. pickedPoint.subtractToRef(lastPosition, delta);
  86545. }
  86546. if (_this.moveAttached) {
  86547. _this._attachedNode.position.addInPlace(delta);
  86548. }
  86549. _this.onDragObservable.notifyObservers({ delta: delta, dragPlanePoint: pickedPoint });
  86550. lastPosition.copyFrom(pickedPoint);
  86551. }
  86552. }
  86553. }
  86554. });
  86555. };
  86556. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  86557. var _this = this;
  86558. if (!ray) {
  86559. return null;
  86560. }
  86561. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  86562. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  86563. return pickResult.pickedPoint;
  86564. }
  86565. else {
  86566. return null;
  86567. }
  86568. };
  86569. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  86570. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray) {
  86571. var pointA = this._dragPlaneParent ? this._dragPlaneParent.position : this._attachedNode.position; // center
  86572. if (this.options.dragAxis) {
  86573. var camPos = ray.origin;
  86574. // Calculate plane normal in direction of camera but perpendicular to drag axis
  86575. var pointB = pointA.add(this.options.dragAxis); // towards drag axis
  86576. var pointC = pointA.add(camPos.subtract(pointA).normalize()); // towards camera
  86577. // Get perpendicular line from direction to camera and drag axis
  86578. var lineA = pointB.subtract(pointA);
  86579. var lineB = pointC.subtract(pointA);
  86580. var perpLine = BABYLON.Vector3.Cross(lineA, lineB);
  86581. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  86582. var norm = BABYLON.Vector3.Cross(lineA, perpLine).normalize();
  86583. this._dragPlane.position.copyFrom(pointA);
  86584. this._dragPlane.lookAt(pointA.add(norm));
  86585. }
  86586. else if (this.options.dragPlaneNormal) {
  86587. this._dragPlane.position.copyFrom(pointA);
  86588. this._dragPlane.lookAt(pointA.add(this.options.dragPlaneNormal));
  86589. }
  86590. this._dragPlane.computeWorldMatrix(true);
  86591. };
  86592. /**
  86593. * Detaches the behavior from the mesh
  86594. */
  86595. PointerDragBehavior.prototype.detach = function () {
  86596. if (this._pointerObserver) {
  86597. this._scene.onPointerObservable.remove(this._pointerObserver);
  86598. }
  86599. };
  86600. return PointerDragBehavior;
  86601. }());
  86602. BABYLON.PointerDragBehavior = PointerDragBehavior;
  86603. })(BABYLON || (BABYLON = {}));
  86604. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  86605. var BABYLON;
  86606. (function (BABYLON) {
  86607. /**
  86608. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  86609. */
  86610. var Gizmo = /** @class */ (function () {
  86611. /**
  86612. * Creates a gizmo
  86613. * @param gizmoLayer The utility layer the gizmo will be added to
  86614. */
  86615. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  86616. var _this = this;
  86617. this.gizmoLayer = gizmoLayer;
  86618. this._interactionsEnabled = true;
  86619. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  86620. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  86621. if (_this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  86622. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  86623. _this._rootMesh.scaling.set(dist, dist, dist);
  86624. }
  86625. if (_this.attachedMesh) {
  86626. _this._rootMesh.position.copyFrom(_this.attachedMesh.position);
  86627. }
  86628. });
  86629. }
  86630. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86631. };
  86632. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  86633. get: function () {
  86634. return this._interactionsEnabled;
  86635. },
  86636. /**
  86637. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  86638. */
  86639. set: function (value) {
  86640. this._interactionsEnabled = value;
  86641. this._onInteractionsEnabledChanged(value);
  86642. },
  86643. enumerable: true,
  86644. configurable: true
  86645. });
  86646. /**
  86647. * Disposes of the gizmo
  86648. */
  86649. Gizmo.prototype.dispose = function () {
  86650. this._rootMesh.dispose();
  86651. if (this._beforeRenderObserver) {
  86652. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  86653. }
  86654. };
  86655. return Gizmo;
  86656. }());
  86657. BABYLON.Gizmo = Gizmo;
  86658. })(BABYLON || (BABYLON = {}));
  86659. //# sourceMappingURL=babylon.gizmo.js.map
  86660. var BABYLON;
  86661. (function (BABYLON) {
  86662. /**
  86663. * Single axis drag gizmo
  86664. */
  86665. var AxisDragGizmo = /** @class */ (function (_super) {
  86666. __extends(AxisDragGizmo, _super);
  86667. /**
  86668. * Creates an AxisDragGizmo
  86669. * @param gizmoLayer The utility layer the gizmo will be added to
  86670. * @param dragAxis The axis which the gizmo will be able to drag on
  86671. * @param color The color of the gizmo
  86672. */
  86673. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  86674. var _this = _super.call(this, gizmoLayer) || this;
  86675. // Create Material
  86676. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86677. coloredMaterial.disableLighting = true;
  86678. coloredMaterial.emissiveColor = color;
  86679. // Build mesh on root node
  86680. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86681. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86682. _this._rootMesh.addChild(arrowMesh);
  86683. _this._rootMesh.addChild(arrowTail);
  86684. // Position arrow pointing in its drag axis
  86685. arrowMesh.scaling.scaleInPlace(0.1);
  86686. arrowMesh.material = coloredMaterial;
  86687. arrowMesh.rotation.x = Math.PI / 2;
  86688. arrowMesh.position.z += 0.3;
  86689. arrowTail.rotation.x = Math.PI / 2;
  86690. arrowTail.material = coloredMaterial;
  86691. arrowTail.position.z += 0.2;
  86692. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86693. // Add drag behavior to handle events when the gizmo is dragged
  86694. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  86695. _this._dragBehavior.moveAttached = false;
  86696. _this._rootMesh.addBehavior(_this._dragBehavior);
  86697. _this._dragBehavior.onDragObservable.add(function (event) {
  86698. if (!_this.interactionsEnabled) {
  86699. return;
  86700. }
  86701. if (_this.attachedMesh) {
  86702. _this.attachedMesh.position.addInPlace(event.delta);
  86703. }
  86704. });
  86705. return _this;
  86706. }
  86707. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86708. this._dragBehavior.enabled = value;
  86709. };
  86710. /**
  86711. * Disposes of the gizmo
  86712. */
  86713. AxisDragGizmo.prototype.dispose = function () {
  86714. this._dragBehavior.detach();
  86715. _super.prototype.dispose.call(this);
  86716. };
  86717. return AxisDragGizmo;
  86718. }(BABYLON.Gizmo));
  86719. BABYLON.AxisDragGizmo = AxisDragGizmo;
  86720. })(BABYLON || (BABYLON = {}));
  86721. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  86722. var BABYLON;
  86723. (function (BABYLON) {
  86724. /**
  86725. * Single axis scale gizmo
  86726. */
  86727. var AxisScaleGizmo = /** @class */ (function (_super) {
  86728. __extends(AxisScaleGizmo, _super);
  86729. /**
  86730. * Creates an AxisScaleGizmo
  86731. * @param gizmoLayer The utility layer the gizmo will be added to
  86732. * @param dragAxis The axis which the gizmo will be able to scale on
  86733. * @param color The color of the gizmo
  86734. */
  86735. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  86736. var _this = _super.call(this, gizmoLayer) || this;
  86737. // Create Material
  86738. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86739. coloredMaterial.disableLighting = true;
  86740. coloredMaterial.emissiveColor = color;
  86741. // Build mesh on root node
  86742. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  86743. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  86744. _this._rootMesh.addChild(arrowMesh);
  86745. _this._rootMesh.addChild(arrowTail);
  86746. // Position arrow pointing in its drag axis
  86747. arrowMesh.scaling.scaleInPlace(0.1);
  86748. arrowMesh.material = coloredMaterial;
  86749. arrowMesh.rotation.x = Math.PI / 2;
  86750. arrowMesh.position.z += 0.3;
  86751. arrowTail.rotation.x = Math.PI / 2;
  86752. arrowTail.material = coloredMaterial;
  86753. arrowTail.position.z += 0.2;
  86754. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  86755. // Add drag behavior to handle events when the gizmo is dragged
  86756. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  86757. _this._dragBehavior.moveAttached = false;
  86758. _this._rootMesh.addBehavior(_this._dragBehavior);
  86759. _this._dragBehavior.onDragObservable.add(function (event) {
  86760. if (!_this.interactionsEnabled) {
  86761. return;
  86762. }
  86763. if (_this.attachedMesh) {
  86764. _this.attachedMesh.scaling.addInPlace(event.delta);
  86765. }
  86766. });
  86767. return _this;
  86768. }
  86769. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86770. this._dragBehavior.enabled = value;
  86771. };
  86772. /**
  86773. * Disposes of the gizmo
  86774. */
  86775. AxisScaleGizmo.prototype.dispose = function () {
  86776. this._dragBehavior.detach();
  86777. _super.prototype.dispose.call(this);
  86778. };
  86779. return AxisScaleGizmo;
  86780. }(BABYLON.Gizmo));
  86781. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  86782. })(BABYLON || (BABYLON = {}));
  86783. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  86784. var BABYLON;
  86785. (function (BABYLON) {
  86786. /**
  86787. * Single plane rotation gizmo
  86788. */
  86789. var PlaneRotationGizmo = /** @class */ (function (_super) {
  86790. __extends(PlaneRotationGizmo, _super);
  86791. /**
  86792. * Creates a PlaneRotationGizmo
  86793. * @param gizmoLayer The utility layer the gizmo will be added to
  86794. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  86795. * @param color The color of the gizmo
  86796. */
  86797. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  86798. var _this = _super.call(this, gizmoLayer) || this;
  86799. // Create Material
  86800. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  86801. coloredMaterial.disableLighting = true;
  86802. coloredMaterial.emissiveColor = color;
  86803. // Build mesh on root node
  86804. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  86805. _this._rootMesh.addChild(rotationMesh);
  86806. // Position arrow pointing in its drag axis
  86807. rotationMesh.scaling.scaleInPlace(0.1);
  86808. rotationMesh.material = coloredMaterial;
  86809. rotationMesh.rotation.x = Math.PI / 2;
  86810. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  86811. // Add drag behavior to handle events when the gizmo is dragged
  86812. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  86813. _this._dragBehavior.moveAttached = false;
  86814. _this._rootMesh.addBehavior(_this._dragBehavior);
  86815. var lastDragPosition = null;
  86816. _this._dragBehavior.onDragStartObservable.add(function (e) {
  86817. if (!_this.interactionsEnabled) {
  86818. return;
  86819. }
  86820. lastDragPosition = e.dragPlanePoint;
  86821. });
  86822. _this._dragBehavior.onDragObservable.add(function (event) {
  86823. if (!_this.interactionsEnabled) {
  86824. return;
  86825. }
  86826. if (_this.attachedMesh && lastDragPosition) {
  86827. if (!_this.attachedMesh.rotationQuaternion) {
  86828. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  86829. }
  86830. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  86831. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  86832. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  86833. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  86834. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  86835. var angle = Math.atan2(cross.length(), dot);
  86836. var up = planeNormal.clone();
  86837. // Flip up vector depending on which side the camera is on
  86838. if (gizmoLayer.utilityLayerScene.activeCamera) {
  86839. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  86840. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  86841. up.scaleInPlace(-1);
  86842. }
  86843. }
  86844. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  86845. if (halfCircleSide)
  86846. angle = -angle;
  86847. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  86848. var quaternionCoefficient = Math.sin(angle / 2);
  86849. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  86850. // Rotate selected mesh quaternion over fixed axis
  86851. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  86852. lastDragPosition = event.dragPlanePoint;
  86853. }
  86854. });
  86855. return _this;
  86856. }
  86857. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86858. this._dragBehavior.enabled = value;
  86859. };
  86860. /**
  86861. * Disposes of the gizmo
  86862. */
  86863. PlaneRotationGizmo.prototype.dispose = function () {
  86864. this._dragBehavior.detach();
  86865. _super.prototype.dispose.call(this);
  86866. };
  86867. return PlaneRotationGizmo;
  86868. }(BABYLON.Gizmo));
  86869. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  86870. })(BABYLON || (BABYLON = {}));
  86871. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  86872. var BABYLON;
  86873. (function (BABYLON) {
  86874. /**
  86875. * Gizmo that enables dragging a mesh along 3 axis
  86876. */
  86877. var PositionGizmo = /** @class */ (function (_super) {
  86878. __extends(PositionGizmo, _super);
  86879. /**
  86880. * Creates a PositionGizmo
  86881. * @param gizmoLayer The utility layer the gizmo will be added to
  86882. */
  86883. function PositionGizmo(gizmoLayer) {
  86884. var _this = _super.call(this, gizmoLayer) || this;
  86885. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86886. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86887. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86888. return _this;
  86889. }
  86890. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  86891. set: function (mesh) {
  86892. this._xDrag.attachedMesh = mesh;
  86893. this._yDrag.attachedMesh = mesh;
  86894. this._zDrag.attachedMesh = mesh;
  86895. },
  86896. enumerable: true,
  86897. configurable: true
  86898. });
  86899. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86900. this._xDrag.interactionsEnabled = value;
  86901. this._yDrag.interactionsEnabled = value;
  86902. this._zDrag.interactionsEnabled = value;
  86903. };
  86904. /**
  86905. * Disposes of the gizmo
  86906. */
  86907. PositionGizmo.prototype.dispose = function () {
  86908. this._xDrag.dispose();
  86909. this._yDrag.dispose();
  86910. this._zDrag.dispose();
  86911. };
  86912. return PositionGizmo;
  86913. }(BABYLON.Gizmo));
  86914. BABYLON.PositionGizmo = PositionGizmo;
  86915. })(BABYLON || (BABYLON = {}));
  86916. //# sourceMappingURL=babylon.positionGizmo.js.map
  86917. var BABYLON;
  86918. (function (BABYLON) {
  86919. /**
  86920. * Gizmo that enables rotating a mesh along 3 axis
  86921. */
  86922. var RotationGizmo = /** @class */ (function (_super) {
  86923. __extends(RotationGizmo, _super);
  86924. /**
  86925. * Creates a RotationGizmo
  86926. * @param gizmoLayer The utility layer the gizmo will be added to
  86927. */
  86928. function RotationGizmo(gizmoLayer) {
  86929. var _this = _super.call(this, gizmoLayer) || this;
  86930. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86931. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86932. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86933. return _this;
  86934. }
  86935. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  86936. set: function (mesh) {
  86937. this._xDrag.attachedMesh = mesh;
  86938. this._yDrag.attachedMesh = mesh;
  86939. this._zDrag.attachedMesh = mesh;
  86940. },
  86941. enumerable: true,
  86942. configurable: true
  86943. });
  86944. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86945. this._xDrag.interactionsEnabled = value;
  86946. this._yDrag.interactionsEnabled = value;
  86947. this._zDrag.interactionsEnabled = value;
  86948. };
  86949. /**
  86950. * Disposes of the gizmo
  86951. */
  86952. RotationGizmo.prototype.dispose = function () {
  86953. this._xDrag.dispose();
  86954. this._yDrag.dispose();
  86955. this._zDrag.dispose();
  86956. };
  86957. return RotationGizmo;
  86958. }(BABYLON.Gizmo));
  86959. BABYLON.RotationGizmo = RotationGizmo;
  86960. })(BABYLON || (BABYLON = {}));
  86961. //# sourceMappingURL=babylon.rotationGizmo.js.map
  86962. var BABYLON;
  86963. (function (BABYLON) {
  86964. /**
  86965. * Gizmo that enables scaling a mesh along 3 axis
  86966. */
  86967. var ScaleGizmo = /** @class */ (function (_super) {
  86968. __extends(ScaleGizmo, _super);
  86969. /**
  86970. * Creates a ScaleGizmo
  86971. * @param gizmoLayer The utility layer the gizmo will be added to
  86972. */
  86973. function ScaleGizmo(gizmoLayer) {
  86974. var _this = _super.call(this, gizmoLayer) || this;
  86975. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  86976. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  86977. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  86978. return _this;
  86979. }
  86980. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  86981. set: function (mesh) {
  86982. this._xDrag.attachedMesh = mesh;
  86983. this._yDrag.attachedMesh = mesh;
  86984. this._zDrag.attachedMesh = mesh;
  86985. },
  86986. enumerable: true,
  86987. configurable: true
  86988. });
  86989. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  86990. this._xDrag.interactionsEnabled = value;
  86991. this._yDrag.interactionsEnabled = value;
  86992. this._zDrag.interactionsEnabled = value;
  86993. };
  86994. /**
  86995. * Disposes of the gizmo
  86996. */
  86997. ScaleGizmo.prototype.dispose = function () {
  86998. this._xDrag.dispose();
  86999. this._yDrag.dispose();
  87000. this._zDrag.dispose();
  87001. };
  87002. return ScaleGizmo;
  87003. }(BABYLON.Gizmo));
  87004. BABYLON.ScaleGizmo = ScaleGizmo;
  87005. })(BABYLON || (BABYLON = {}));
  87006. //# sourceMappingURL=babylon.scaleGizmo.js.map
  87007. var BABYLON;
  87008. (function (BABYLON) {
  87009. /**
  87010. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  87011. */
  87012. var GizmoManager = /** @class */ (function () {
  87013. /**
  87014. * Instatiates a gizmo manager
  87015. * @param scene the scene to overlay the gizmos on top of
  87016. * @param options If only a single gizmo should exist at one time
  87017. */
  87018. function GizmoManager(scene, options) {
  87019. var _this = this;
  87020. this.scene = scene;
  87021. // Set of gizmos that are currently in the scene for each mesh
  87022. this._gizmoSet = {};
  87023. this._pointerObserver = null;
  87024. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  87025. // Options parsing
  87026. if (!options) {
  87027. options = {};
  87028. }
  87029. if (options.singleGizmo === undefined) {
  87030. options.singleGizmo = true;
  87031. }
  87032. // Instatiate/dispose gizmos based on pointer actions
  87033. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  87034. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  87035. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  87036. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  87037. if (options.singleGizmo) {
  87038. _this._clearGizmos();
  87039. }
  87040. // Enable gizmo when mesh is selected
  87041. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  87042. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87043. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  87044. }
  87045. else {
  87046. if (!options.singleGizmo) {
  87047. // Disable gizmo when clicked again
  87048. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  87049. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  87050. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  87051. }
  87052. }
  87053. }
  87054. else {
  87055. if (options.singleGizmo) {
  87056. // Disable gizmo when clicked away
  87057. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  87058. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  87059. if (gizmoPick && !gizmoPick.hit) {
  87060. _this._clearGizmos();
  87061. }
  87062. }
  87063. }
  87064. }
  87065. }
  87066. });
  87067. }
  87068. /**
  87069. * Disposes of the gizmo manager
  87070. */
  87071. GizmoManager.prototype.dispose = function () {
  87072. this.scene.onPointerObservable.remove(this._pointerObserver);
  87073. this._clearGizmos();
  87074. this._gizmoLayer.dispose();
  87075. };
  87076. GizmoManager.prototype._clearGizmos = function () {
  87077. for (var key in this._gizmoSet) {
  87078. if (this._gizmoSet.hasOwnProperty(key)) {
  87079. this._gizmoSet[key].positionGizmo.dispose();
  87080. this._gizmoSet[key].rotationGizmo.dispose();
  87081. delete this._gizmoSet[key];
  87082. }
  87083. }
  87084. };
  87085. return GizmoManager;
  87086. }());
  87087. BABYLON.GizmoManager = GizmoManager;
  87088. })(BABYLON || (BABYLON = {}));
  87089. //# sourceMappingURL=babylon.gizmoManager.js.map
  87090. var BABYLON;
  87091. (function (BABYLON) {
  87092. /**
  87093. * Defines a target to use with MorphTargetManager
  87094. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87095. */
  87096. var MorphTarget = /** @class */ (function () {
  87097. /**
  87098. * Creates a new MorphTarget
  87099. * @param name defines the name of the target
  87100. * @param influence defines the influence to use
  87101. */
  87102. function MorphTarget(
  87103. /** defines the name of the target */
  87104. name, influence, scene) {
  87105. if (influence === void 0) { influence = 0; }
  87106. if (scene === void 0) { scene = null; }
  87107. this.name = name;
  87108. /**
  87109. * Gets or sets the list of animations
  87110. */
  87111. this.animations = new Array();
  87112. this._positions = null;
  87113. this._normals = null;
  87114. this._tangents = null;
  87115. /**
  87116. * Observable raised when the influence changes
  87117. */
  87118. this.onInfluenceChanged = new BABYLON.Observable();
  87119. this._animationPropertiesOverride = null;
  87120. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87121. this.influence = influence;
  87122. }
  87123. Object.defineProperty(MorphTarget.prototype, "influence", {
  87124. /**
  87125. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  87126. */
  87127. get: function () {
  87128. return this._influence;
  87129. },
  87130. set: function (influence) {
  87131. if (this._influence === influence) {
  87132. return;
  87133. }
  87134. var previous = this._influence;
  87135. this._influence = influence;
  87136. if (this.onInfluenceChanged.hasObservers) {
  87137. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  87138. }
  87139. },
  87140. enumerable: true,
  87141. configurable: true
  87142. });
  87143. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  87144. /**
  87145. * Gets or sets the animation properties override
  87146. */
  87147. get: function () {
  87148. if (!this._animationPropertiesOverride && this._scene) {
  87149. return this._scene.animationPropertiesOverride;
  87150. }
  87151. return this._animationPropertiesOverride;
  87152. },
  87153. set: function (value) {
  87154. this._animationPropertiesOverride = value;
  87155. },
  87156. enumerable: true,
  87157. configurable: true
  87158. });
  87159. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  87160. /**
  87161. * Gets a boolean defining if the target contains position data
  87162. */
  87163. get: function () {
  87164. return !!this._positions;
  87165. },
  87166. enumerable: true,
  87167. configurable: true
  87168. });
  87169. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  87170. /**
  87171. * Gets a boolean defining if the target contains normal data
  87172. */
  87173. get: function () {
  87174. return !!this._normals;
  87175. },
  87176. enumerable: true,
  87177. configurable: true
  87178. });
  87179. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  87180. /**
  87181. * Gets a boolean defining if the target contains tangent data
  87182. */
  87183. get: function () {
  87184. return !!this._tangents;
  87185. },
  87186. enumerable: true,
  87187. configurable: true
  87188. });
  87189. /**
  87190. * Affects position data to this target
  87191. * @param data defines the position data to use
  87192. */
  87193. MorphTarget.prototype.setPositions = function (data) {
  87194. this._positions = data;
  87195. };
  87196. /**
  87197. * Gets the position data stored in this target
  87198. * @returns a FloatArray containing the position data (or null if not present)
  87199. */
  87200. MorphTarget.prototype.getPositions = function () {
  87201. return this._positions;
  87202. };
  87203. /**
  87204. * Affects normal data to this target
  87205. * @param data defines the normal data to use
  87206. */
  87207. MorphTarget.prototype.setNormals = function (data) {
  87208. this._normals = data;
  87209. };
  87210. /**
  87211. * Gets the normal data stored in this target
  87212. * @returns a FloatArray containing the normal data (or null if not present)
  87213. */
  87214. MorphTarget.prototype.getNormals = function () {
  87215. return this._normals;
  87216. };
  87217. /**
  87218. * Affects tangent data to this target
  87219. * @param data defines the tangent data to use
  87220. */
  87221. MorphTarget.prototype.setTangents = function (data) {
  87222. this._tangents = data;
  87223. };
  87224. /**
  87225. * Gets the tangent data stored in this target
  87226. * @returns a FloatArray containing the tangent data (or null if not present)
  87227. */
  87228. MorphTarget.prototype.getTangents = function () {
  87229. return this._tangents;
  87230. };
  87231. /**
  87232. * Serializes the current target into a Serialization object
  87233. * @returns the serialized object
  87234. */
  87235. MorphTarget.prototype.serialize = function () {
  87236. var serializationObject = {};
  87237. serializationObject.name = this.name;
  87238. serializationObject.influence = this.influence;
  87239. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  87240. if (this.hasNormals) {
  87241. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  87242. }
  87243. if (this.hasTangents) {
  87244. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  87245. }
  87246. // Animations
  87247. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  87248. return serializationObject;
  87249. };
  87250. // Statics
  87251. /**
  87252. * Creates a new target from serialized data
  87253. * @param serializationObject defines the serialized data to use
  87254. * @returns a new MorphTarget
  87255. */
  87256. MorphTarget.Parse = function (serializationObject) {
  87257. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  87258. result.setPositions(serializationObject.positions);
  87259. if (serializationObject.normals) {
  87260. result.setNormals(serializationObject.normals);
  87261. }
  87262. if (serializationObject.tangents) {
  87263. result.setTangents(serializationObject.tangents);
  87264. }
  87265. // Animations
  87266. if (serializationObject.animations) {
  87267. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  87268. var parsedAnimation = serializationObject.animations[animationIndex];
  87269. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  87270. }
  87271. }
  87272. return result;
  87273. };
  87274. /**
  87275. * Creates a MorphTarget from mesh data
  87276. * @param mesh defines the source mesh
  87277. * @param name defines the name to use for the new target
  87278. * @param influence defines the influence to attach to the target
  87279. * @returns a new MorphTarget
  87280. */
  87281. MorphTarget.FromMesh = function (mesh, name, influence) {
  87282. if (!name) {
  87283. name = mesh.name;
  87284. }
  87285. var result = new MorphTarget(name, influence, mesh.getScene());
  87286. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87287. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87288. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  87289. }
  87290. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  87291. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  87292. }
  87293. return result;
  87294. };
  87295. return MorphTarget;
  87296. }());
  87297. BABYLON.MorphTarget = MorphTarget;
  87298. })(BABYLON || (BABYLON = {}));
  87299. //# sourceMappingURL=babylon.morphTarget.js.map
  87300. var BABYLON;
  87301. (function (BABYLON) {
  87302. /**
  87303. * This class is used to deform meshes using morphing between different targets
  87304. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  87305. */
  87306. var MorphTargetManager = /** @class */ (function () {
  87307. /**
  87308. * Creates a new MorphTargetManager
  87309. * @param scene defines the current scene
  87310. */
  87311. function MorphTargetManager(scene) {
  87312. if (scene === void 0) { scene = null; }
  87313. this._targets = new Array();
  87314. this._targetObservable = new Array();
  87315. this._activeTargets = new BABYLON.SmartArray(16);
  87316. this._supportsNormals = false;
  87317. this._supportsTangents = false;
  87318. this._vertexCount = 0;
  87319. this._uniqueId = 0;
  87320. this._tempInfluences = new Array();
  87321. if (!scene) {
  87322. scene = BABYLON.Engine.LastCreatedScene;
  87323. }
  87324. this._scene = scene;
  87325. if (this._scene) {
  87326. this._scene.morphTargetManagers.push(this);
  87327. this._uniqueId = this._scene.getUniqueId();
  87328. }
  87329. }
  87330. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  87331. /**
  87332. * Gets the unique ID of this manager
  87333. */
  87334. get: function () {
  87335. return this._uniqueId;
  87336. },
  87337. enumerable: true,
  87338. configurable: true
  87339. });
  87340. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  87341. /**
  87342. * Gets the number of vertices handled by this manager
  87343. */
  87344. get: function () {
  87345. return this._vertexCount;
  87346. },
  87347. enumerable: true,
  87348. configurable: true
  87349. });
  87350. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  87351. /**
  87352. * Gets a boolean indicating if this manager supports morphing of normals
  87353. */
  87354. get: function () {
  87355. return this._supportsNormals;
  87356. },
  87357. enumerable: true,
  87358. configurable: true
  87359. });
  87360. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  87361. /**
  87362. * Gets a boolean indicating if this manager supports morphing of tangents
  87363. */
  87364. get: function () {
  87365. return this._supportsTangents;
  87366. },
  87367. enumerable: true,
  87368. configurable: true
  87369. });
  87370. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  87371. /**
  87372. * Gets the number of targets stored in this manager
  87373. */
  87374. get: function () {
  87375. return this._targets.length;
  87376. },
  87377. enumerable: true,
  87378. configurable: true
  87379. });
  87380. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  87381. /**
  87382. * Gets the number of influencers (ie. the number of targets with influences > 0)
  87383. */
  87384. get: function () {
  87385. return this._activeTargets.length;
  87386. },
  87387. enumerable: true,
  87388. configurable: true
  87389. });
  87390. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  87391. /**
  87392. * Gets the list of influences (one per target)
  87393. */
  87394. get: function () {
  87395. return this._influences;
  87396. },
  87397. enumerable: true,
  87398. configurable: true
  87399. });
  87400. /**
  87401. * Gets the active target at specified index. An active target is a target with an influence > 0
  87402. * @param index defines the index to check
  87403. * @returns the requested target
  87404. */
  87405. MorphTargetManager.prototype.getActiveTarget = function (index) {
  87406. return this._activeTargets.data[index];
  87407. };
  87408. /**
  87409. * Gets the target at specified index
  87410. * @param index defines the index to check
  87411. * @returns the requested target
  87412. */
  87413. MorphTargetManager.prototype.getTarget = function (index) {
  87414. return this._targets[index];
  87415. };
  87416. /**
  87417. * Add a new target to this manager
  87418. * @param target defines the target to add
  87419. */
  87420. MorphTargetManager.prototype.addTarget = function (target) {
  87421. var _this = this;
  87422. this._targets.push(target);
  87423. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  87424. _this._syncActiveTargets(needUpdate);
  87425. }));
  87426. this._syncActiveTargets(true);
  87427. };
  87428. /**
  87429. * Removes a target from the manager
  87430. * @param target defines the target to remove
  87431. */
  87432. MorphTargetManager.prototype.removeTarget = function (target) {
  87433. var index = this._targets.indexOf(target);
  87434. if (index >= 0) {
  87435. this._targets.splice(index, 1);
  87436. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  87437. this._syncActiveTargets(true);
  87438. }
  87439. };
  87440. /**
  87441. * Serializes the current manager into a Serialization object
  87442. * @returns the serialized object
  87443. */
  87444. MorphTargetManager.prototype.serialize = function () {
  87445. var serializationObject = {};
  87446. serializationObject.id = this.uniqueId;
  87447. serializationObject.targets = [];
  87448. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  87449. var target = _a[_i];
  87450. serializationObject.targets.push(target.serialize());
  87451. }
  87452. return serializationObject;
  87453. };
  87454. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  87455. var influenceCount = 0;
  87456. this._activeTargets.reset();
  87457. this._supportsNormals = true;
  87458. this._supportsTangents = true;
  87459. this._vertexCount = 0;
  87460. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  87461. var target = _a[_i];
  87462. this._activeTargets.push(target);
  87463. this._tempInfluences[influenceCount++] = target.influence;
  87464. var positions = target.getPositions();
  87465. if (positions) {
  87466. this._supportsNormals = this._supportsNormals && target.hasNormals;
  87467. this._supportsTangents = this._supportsTangents && target.hasTangents;
  87468. var vertexCount = positions.length / 3;
  87469. if (this._vertexCount === 0) {
  87470. this._vertexCount = vertexCount;
  87471. }
  87472. else if (this._vertexCount !== vertexCount) {
  87473. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  87474. return;
  87475. }
  87476. }
  87477. }
  87478. if (!this._influences || this._influences.length !== influenceCount) {
  87479. this._influences = new Float32Array(influenceCount);
  87480. }
  87481. for (var index = 0; index < influenceCount; index++) {
  87482. this._influences[index] = this._tempInfluences[index];
  87483. }
  87484. if (needUpdate) {
  87485. this.synchronize();
  87486. }
  87487. };
  87488. /**
  87489. * Syncrhonize the targets with all the meshes using this morph target manager
  87490. */
  87491. MorphTargetManager.prototype.synchronize = function () {
  87492. if (!this._scene) {
  87493. return;
  87494. }
  87495. // Flag meshes as dirty to resync with the active targets
  87496. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  87497. var mesh = _a[_i];
  87498. if (mesh.morphTargetManager === this) {
  87499. mesh._syncGeometryWithMorphTargetManager();
  87500. }
  87501. }
  87502. };
  87503. // Statics
  87504. /**
  87505. * Creates a new MorphTargetManager from serialized data
  87506. * @param serializationObject defines the serialized data
  87507. * @param scene defines the hosting scene
  87508. * @returns the new MorphTargetManager
  87509. */
  87510. MorphTargetManager.Parse = function (serializationObject, scene) {
  87511. var result = new MorphTargetManager(scene);
  87512. result._uniqueId = serializationObject.id;
  87513. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  87514. var targetData = _a[_i];
  87515. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  87516. }
  87517. return result;
  87518. };
  87519. return MorphTargetManager;
  87520. }());
  87521. BABYLON.MorphTargetManager = MorphTargetManager;
  87522. })(BABYLON || (BABYLON = {}));
  87523. //# sourceMappingURL=babylon.morphTargetManager.js.map
  87524. var BABYLON;
  87525. (function (BABYLON) {
  87526. var Octree = /** @class */ (function () {
  87527. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  87528. if (maxDepth === void 0) { maxDepth = 2; }
  87529. this.maxDepth = maxDepth;
  87530. this.dynamicContent = new Array();
  87531. this._maxBlockCapacity = maxBlockCapacity || 64;
  87532. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  87533. this._creationFunc = creationFunc;
  87534. }
  87535. // Methods
  87536. Octree.prototype.update = function (worldMin, worldMax, entries) {
  87537. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  87538. };
  87539. Octree.prototype.addMesh = function (entry) {
  87540. for (var index = 0; index < this.blocks.length; index++) {
  87541. var block = this.blocks[index];
  87542. block.addEntry(entry);
  87543. }
  87544. };
  87545. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  87546. this._selectionContent.reset();
  87547. for (var index = 0; index < this.blocks.length; index++) {
  87548. var block = this.blocks[index];
  87549. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  87550. }
  87551. if (allowDuplicate) {
  87552. this._selectionContent.concat(this.dynamicContent);
  87553. }
  87554. else {
  87555. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  87556. }
  87557. return this._selectionContent;
  87558. };
  87559. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  87560. this._selectionContent.reset();
  87561. for (var index = 0; index < this.blocks.length; index++) {
  87562. var block = this.blocks[index];
  87563. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  87564. }
  87565. if (allowDuplicate) {
  87566. this._selectionContent.concat(this.dynamicContent);
  87567. }
  87568. else {
  87569. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  87570. }
  87571. return this._selectionContent;
  87572. };
  87573. Octree.prototype.intersectsRay = function (ray) {
  87574. this._selectionContent.reset();
  87575. for (var index = 0; index < this.blocks.length; index++) {
  87576. var block = this.blocks[index];
  87577. block.intersectsRay(ray, this._selectionContent);
  87578. }
  87579. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  87580. return this._selectionContent;
  87581. };
  87582. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  87583. target.blocks = new Array();
  87584. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  87585. // Segmenting space
  87586. for (var x = 0; x < 2; x++) {
  87587. for (var y = 0; y < 2; y++) {
  87588. for (var z = 0; z < 2; z++) {
  87589. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  87590. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  87591. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  87592. block.addEntries(entries);
  87593. target.blocks.push(block);
  87594. }
  87595. }
  87596. }
  87597. };
  87598. Octree.CreationFuncForMeshes = function (entry, block) {
  87599. var boundingInfo = entry.getBoundingInfo();
  87600. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  87601. block.entries.push(entry);
  87602. }
  87603. };
  87604. Octree.CreationFuncForSubMeshes = function (entry, block) {
  87605. var boundingInfo = entry.getBoundingInfo();
  87606. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  87607. block.entries.push(entry);
  87608. }
  87609. };
  87610. return Octree;
  87611. }());
  87612. BABYLON.Octree = Octree;
  87613. })(BABYLON || (BABYLON = {}));
  87614. //# sourceMappingURL=babylon.octree.js.map
  87615. var BABYLON;
  87616. (function (BABYLON) {
  87617. var OctreeBlock = /** @class */ (function () {
  87618. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  87619. this.entries = new Array();
  87620. this._boundingVectors = new Array();
  87621. this._capacity = capacity;
  87622. this._depth = depth;
  87623. this._maxDepth = maxDepth;
  87624. this._creationFunc = creationFunc;
  87625. this._minPoint = minPoint;
  87626. this._maxPoint = maxPoint;
  87627. this._boundingVectors.push(minPoint.clone());
  87628. this._boundingVectors.push(maxPoint.clone());
  87629. this._boundingVectors.push(minPoint.clone());
  87630. this._boundingVectors[2].x = maxPoint.x;
  87631. this._boundingVectors.push(minPoint.clone());
  87632. this._boundingVectors[3].y = maxPoint.y;
  87633. this._boundingVectors.push(minPoint.clone());
  87634. this._boundingVectors[4].z = maxPoint.z;
  87635. this._boundingVectors.push(maxPoint.clone());
  87636. this._boundingVectors[5].z = minPoint.z;
  87637. this._boundingVectors.push(maxPoint.clone());
  87638. this._boundingVectors[6].x = minPoint.x;
  87639. this._boundingVectors.push(maxPoint.clone());
  87640. this._boundingVectors[7].y = minPoint.y;
  87641. }
  87642. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  87643. // Property
  87644. get: function () {
  87645. return this._capacity;
  87646. },
  87647. enumerable: true,
  87648. configurable: true
  87649. });
  87650. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  87651. get: function () {
  87652. return this._minPoint;
  87653. },
  87654. enumerable: true,
  87655. configurable: true
  87656. });
  87657. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  87658. get: function () {
  87659. return this._maxPoint;
  87660. },
  87661. enumerable: true,
  87662. configurable: true
  87663. });
  87664. // Methods
  87665. OctreeBlock.prototype.addEntry = function (entry) {
  87666. if (this.blocks) {
  87667. for (var index = 0; index < this.blocks.length; index++) {
  87668. var block = this.blocks[index];
  87669. block.addEntry(entry);
  87670. }
  87671. return;
  87672. }
  87673. this._creationFunc(entry, this);
  87674. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  87675. this.createInnerBlocks();
  87676. }
  87677. };
  87678. OctreeBlock.prototype.addEntries = function (entries) {
  87679. for (var index = 0; index < entries.length; index++) {
  87680. var mesh = entries[index];
  87681. this.addEntry(mesh);
  87682. }
  87683. };
  87684. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  87685. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  87686. if (this.blocks) {
  87687. for (var index = 0; index < this.blocks.length; index++) {
  87688. var block = this.blocks[index];
  87689. block.select(frustumPlanes, selection, allowDuplicate);
  87690. }
  87691. return;
  87692. }
  87693. if (allowDuplicate) {
  87694. selection.concat(this.entries);
  87695. }
  87696. else {
  87697. selection.concatWithNoDuplicate(this.entries);
  87698. }
  87699. }
  87700. };
  87701. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  87702. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  87703. if (this.blocks) {
  87704. for (var index = 0; index < this.blocks.length; index++) {
  87705. var block = this.blocks[index];
  87706. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  87707. }
  87708. return;
  87709. }
  87710. if (allowDuplicate) {
  87711. selection.concat(this.entries);
  87712. }
  87713. else {
  87714. selection.concatWithNoDuplicate(this.entries);
  87715. }
  87716. }
  87717. };
  87718. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  87719. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  87720. if (this.blocks) {
  87721. for (var index = 0; index < this.blocks.length; index++) {
  87722. var block = this.blocks[index];
  87723. block.intersectsRay(ray, selection);
  87724. }
  87725. return;
  87726. }
  87727. selection.concatWithNoDuplicate(this.entries);
  87728. }
  87729. };
  87730. OctreeBlock.prototype.createInnerBlocks = function () {
  87731. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  87732. };
  87733. return OctreeBlock;
  87734. }());
  87735. BABYLON.OctreeBlock = OctreeBlock;
  87736. })(BABYLON || (BABYLON = {}));
  87737. //# sourceMappingURL=babylon.octreeBlock.js.map
  87738. var BABYLON;
  87739. (function (BABYLON) {
  87740. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  87741. __extends(VRDistortionCorrectionPostProcess, _super);
  87742. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  87743. var _this = _super.call(this, name, "vrDistortionCorrection", [
  87744. 'LensCenter',
  87745. 'Scale',
  87746. 'ScaleIn',
  87747. 'HmdWarpParam'
  87748. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  87749. _this._isRightEye = isRightEye;
  87750. _this._distortionFactors = vrMetrics.distortionK;
  87751. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  87752. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  87753. _this.adaptScaleToCurrentViewport = true;
  87754. _this.onSizeChangedObservable.add(function () {
  87755. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  87756. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  87757. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  87758. });
  87759. _this.onApplyObservable.add(function (effect) {
  87760. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  87761. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  87762. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  87763. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  87764. });
  87765. return _this;
  87766. }
  87767. return VRDistortionCorrectionPostProcess;
  87768. }(BABYLON.PostProcess));
  87769. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  87770. })(BABYLON || (BABYLON = {}));
  87771. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  87772. var BABYLON;
  87773. (function (BABYLON) {
  87774. /**
  87775. * Postprocess used to generate anaglyphic rendering
  87776. */
  87777. var AnaglyphPostProcess = /** @class */ (function (_super) {
  87778. __extends(AnaglyphPostProcess, _super);
  87779. /**
  87780. * Creates a new AnaglyphPostProcess
  87781. * @param name defines postprocess name
  87782. * @param options defines creation options or target ratio scale
  87783. * @param rigCameras defines cameras using this postprocess
  87784. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  87785. * @param engine defines hosting engine
  87786. * @param reusable defines if the postprocess will be reused multiple times per frame
  87787. */
  87788. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  87789. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  87790. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87791. _this.onApplyObservable.add(function (effect) {
  87792. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  87793. });
  87794. return _this;
  87795. }
  87796. return AnaglyphPostProcess;
  87797. }(BABYLON.PostProcess));
  87798. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  87799. })(BABYLON || (BABYLON = {}));
  87800. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  87801. var BABYLON;
  87802. (function (BABYLON) {
  87803. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  87804. __extends(StereoscopicInterlacePostProcess, _super);
  87805. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  87806. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  87807. _this._passedProcess = rigCameras[0]._rigPostProcess;
  87808. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87809. _this.onSizeChangedObservable.add(function () {
  87810. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  87811. });
  87812. _this.onApplyObservable.add(function (effect) {
  87813. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  87814. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  87815. });
  87816. return _this;
  87817. }
  87818. return StereoscopicInterlacePostProcess;
  87819. }(BABYLON.PostProcess));
  87820. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  87821. })(BABYLON || (BABYLON = {}));
  87822. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  87823. var BABYLON;
  87824. (function (BABYLON) {
  87825. /**
  87826. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  87827. * Screen rotation is taken into account.
  87828. */
  87829. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  87830. function FreeCameraDeviceOrientationInput() {
  87831. var _this = this;
  87832. this._screenOrientationAngle = 0;
  87833. this._screenQuaternion = new BABYLON.Quaternion();
  87834. this._alpha = 0;
  87835. this._beta = 0;
  87836. this._gamma = 0;
  87837. this._orientationChanged = function () {
  87838. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  87839. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  87840. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  87841. };
  87842. this._deviceOrientation = function (evt) {
  87843. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  87844. _this._beta = evt.beta !== null ? evt.beta : 0;
  87845. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  87846. };
  87847. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  87848. this._orientationChanged();
  87849. }
  87850. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  87851. get: function () {
  87852. return this._camera;
  87853. },
  87854. set: function (camera) {
  87855. this._camera = camera;
  87856. if (this._camera != null && !this._camera.rotationQuaternion) {
  87857. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  87858. }
  87859. },
  87860. enumerable: true,
  87861. configurable: true
  87862. });
  87863. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87864. window.addEventListener("orientationchange", this._orientationChanged);
  87865. window.addEventListener("deviceorientation", this._deviceOrientation);
  87866. //In certain cases, the attach control is called AFTER orientation was changed,
  87867. //So this is needed.
  87868. this._orientationChanged();
  87869. };
  87870. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  87871. window.removeEventListener("orientationchange", this._orientationChanged);
  87872. window.removeEventListener("deviceorientation", this._deviceOrientation);
  87873. };
  87874. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  87875. //if no device orientation provided, don't update the rotation.
  87876. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  87877. if (!this._alpha)
  87878. return;
  87879. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  87880. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  87881. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  87882. //Mirror on XY Plane
  87883. this._camera.rotationQuaternion.z *= -1;
  87884. this._camera.rotationQuaternion.w *= -1;
  87885. };
  87886. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  87887. return "FreeCameraDeviceOrientationInput";
  87888. };
  87889. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  87890. return "deviceOrientation";
  87891. };
  87892. return FreeCameraDeviceOrientationInput;
  87893. }());
  87894. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  87895. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  87896. })(BABYLON || (BABYLON = {}));
  87897. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  87898. var BABYLON;
  87899. (function (BABYLON) {
  87900. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  87901. function ArcRotateCameraVRDeviceOrientationInput() {
  87902. this.alphaCorrection = 1;
  87903. this.betaCorrection = 1;
  87904. this.gammaCorrection = 1;
  87905. this._alpha = 0;
  87906. this._gamma = 0;
  87907. this._dirty = false;
  87908. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  87909. }
  87910. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  87911. this.camera.attachControl(element, noPreventDefault);
  87912. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  87913. };
  87914. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  87915. if (evt.alpha !== null) {
  87916. this._alpha = +evt.alpha | 0;
  87917. }
  87918. if (evt.gamma !== null) {
  87919. this._gamma = +evt.gamma | 0;
  87920. }
  87921. this._dirty = true;
  87922. };
  87923. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  87924. if (this._dirty) {
  87925. this._dirty = false;
  87926. if (this._gamma < 0) {
  87927. this._gamma = 180 + this._gamma;
  87928. }
  87929. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  87930. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  87931. }
  87932. };
  87933. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  87934. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  87935. };
  87936. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  87937. return "ArcRotateCameraVRDeviceOrientationInput";
  87938. };
  87939. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  87940. return "VRDeviceOrientation";
  87941. };
  87942. return ArcRotateCameraVRDeviceOrientationInput;
  87943. }());
  87944. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  87945. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  87946. })(BABYLON || (BABYLON = {}));
  87947. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  87948. var BABYLON;
  87949. (function (BABYLON) {
  87950. var VRCameraMetrics = /** @class */ (function () {
  87951. function VRCameraMetrics() {
  87952. this.compensateDistortion = true;
  87953. }
  87954. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  87955. get: function () {
  87956. return this.hResolution / (2 * this.vResolution);
  87957. },
  87958. enumerable: true,
  87959. configurable: true
  87960. });
  87961. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  87962. get: function () {
  87963. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  87964. },
  87965. enumerable: true,
  87966. configurable: true
  87967. });
  87968. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  87969. get: function () {
  87970. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87971. var h = (4 * meters) / this.hScreenSize;
  87972. return BABYLON.Matrix.Translation(h, 0, 0);
  87973. },
  87974. enumerable: true,
  87975. configurable: true
  87976. });
  87977. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  87978. get: function () {
  87979. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  87980. var h = (4 * meters) / this.hScreenSize;
  87981. return BABYLON.Matrix.Translation(-h, 0, 0);
  87982. },
  87983. enumerable: true,
  87984. configurable: true
  87985. });
  87986. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  87987. get: function () {
  87988. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  87989. },
  87990. enumerable: true,
  87991. configurable: true
  87992. });
  87993. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  87994. get: function () {
  87995. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  87996. },
  87997. enumerable: true,
  87998. configurable: true
  87999. });
  88000. VRCameraMetrics.GetDefault = function () {
  88001. var result = new VRCameraMetrics();
  88002. result.hResolution = 1280;
  88003. result.vResolution = 800;
  88004. result.hScreenSize = 0.149759993;
  88005. result.vScreenSize = 0.0935999975;
  88006. result.vScreenCenter = 0.0467999987;
  88007. result.eyeToScreenDistance = 0.0410000011;
  88008. result.lensSeparationDistance = 0.0635000020;
  88009. result.interpupillaryDistance = 0.0640000030;
  88010. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  88011. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  88012. result.postProcessScaleFactor = 1.714605507808412;
  88013. result.lensCenterOffset = 0.151976421;
  88014. return result;
  88015. };
  88016. return VRCameraMetrics;
  88017. }());
  88018. BABYLON.VRCameraMetrics = VRCameraMetrics;
  88019. })(BABYLON || (BABYLON = {}));
  88020. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  88021. var BABYLON;
  88022. (function (BABYLON) {
  88023. /**
  88024. * This represents a WebVR camera.
  88025. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  88026. * @example http://doc.babylonjs.com/how_to/webvr_camera
  88027. */
  88028. var WebVRFreeCamera = /** @class */ (function (_super) {
  88029. __extends(WebVRFreeCamera, _super);
  88030. /**
  88031. * Instantiates a WebVRFreeCamera.
  88032. * @param name The name of the WebVRFreeCamera
  88033. * @param position The starting anchor position for the camera
  88034. * @param scene The scene the camera belongs to
  88035. * @param webVROptions a set of customizable options for the webVRCamera
  88036. */
  88037. function WebVRFreeCamera(name, position, scene, webVROptions) {
  88038. if (webVROptions === void 0) { webVROptions = {}; }
  88039. var _this = _super.call(this, name, position, scene) || this;
  88040. _this.webVROptions = webVROptions;
  88041. /**
  88042. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  88043. */
  88044. _this._vrDevice = null;
  88045. /**
  88046. * The rawPose of the vrDevice.
  88047. */
  88048. _this.rawPose = null;
  88049. _this._specsVersion = "1.1";
  88050. _this._attached = false;
  88051. _this._descendants = [];
  88052. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  88053. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  88054. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  88055. _this._standingMatrix = null;
  88056. /**
  88057. * Represents device position in babylon space.
  88058. */
  88059. _this.devicePosition = BABYLON.Vector3.Zero();
  88060. /**
  88061. * Represents device rotation in babylon space.
  88062. */
  88063. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  88064. /**
  88065. * The scale of the device to be used when translating from device space to babylon space.
  88066. */
  88067. _this.deviceScaleFactor = 1;
  88068. _this._deviceToWorld = BABYLON.Matrix.Identity();
  88069. _this._worldToDevice = BABYLON.Matrix.Identity();
  88070. /**
  88071. * References to the webVR controllers for the vrDevice.
  88072. */
  88073. _this.controllers = [];
  88074. /**
  88075. * Emits an event when a controller is attached.
  88076. */
  88077. _this.onControllersAttachedObservable = new BABYLON.Observable();
  88078. /**
  88079. * Emits an event when a controller's mesh has been loaded;
  88080. */
  88081. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  88082. /**
  88083. * If the rig cameras be used as parent instead of this camera.
  88084. */
  88085. _this.rigParenting = true;
  88086. _this._defaultHeight = undefined;
  88087. _this._workingVector = BABYLON.Vector3.Zero();
  88088. _this._oneVector = BABYLON.Vector3.One();
  88089. _this._workingMatrix = BABYLON.Matrix.Identity();
  88090. _this._cache.position = BABYLON.Vector3.Zero();
  88091. if (webVROptions.defaultHeight) {
  88092. _this._defaultHeight = webVROptions.defaultHeight;
  88093. _this.position.y = _this._defaultHeight;
  88094. }
  88095. _this.minZ = 0.1;
  88096. //legacy support - the compensation boolean was removed.
  88097. if (arguments.length === 5) {
  88098. _this.webVROptions = arguments[4];
  88099. }
  88100. // default webVR options
  88101. if (_this.webVROptions.trackPosition == undefined) {
  88102. _this.webVROptions.trackPosition = true;
  88103. }
  88104. if (_this.webVROptions.controllerMeshes == undefined) {
  88105. _this.webVROptions.controllerMeshes = true;
  88106. }
  88107. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  88108. _this.webVROptions.defaultLightingOnControllers = true;
  88109. }
  88110. _this.rotationQuaternion = new BABYLON.Quaternion();
  88111. if (_this.webVROptions && _this.webVROptions.positionScale) {
  88112. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  88113. }
  88114. //enable VR
  88115. var engine = _this.getEngine();
  88116. _this._onVREnabled = function (success) { if (success) {
  88117. _this.initControllers();
  88118. } };
  88119. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  88120. engine.initWebVR().add(function (event) {
  88121. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  88122. return;
  88123. }
  88124. _this._vrDevice = event.vrDisplay;
  88125. //reset the rig parameters.
  88126. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  88127. if (_this._attached) {
  88128. _this.getEngine().enableVR();
  88129. }
  88130. });
  88131. if (typeof (VRFrameData) !== "undefined")
  88132. _this._frameData = new VRFrameData();
  88133. /**
  88134. * The idea behind the following lines:
  88135. * objects that have the camera as parent should actually have the rig cameras as a parent.
  88136. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  88137. * the second will not show it correctly.
  88138. *
  88139. * To solve this - each object that has the camera as parent will be added to a protected array.
  88140. * When the rig camera renders, it will take this array and set all of those to be its children.
  88141. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  88142. * Amazing!
  88143. */
  88144. scene.onBeforeCameraRenderObservable.add(function (camera) {
  88145. if (camera.parent === _this && _this.rigParenting) {
  88146. _this._descendants = _this.getDescendants(true, function (n) {
  88147. // don't take the cameras or the controllers!
  88148. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  88149. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  88150. return !isController && !isRigCamera;
  88151. });
  88152. _this._descendants.forEach(function (node) {
  88153. node.parent = camera;
  88154. });
  88155. }
  88156. });
  88157. scene.onAfterCameraRenderObservable.add(function (camera) {
  88158. if (camera.parent === _this && _this.rigParenting) {
  88159. _this._descendants.forEach(function (node) {
  88160. node.parent = _this;
  88161. });
  88162. }
  88163. });
  88164. return _this;
  88165. }
  88166. /**
  88167. * Gets the device distance from the ground in meters.
  88168. * @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.
  88169. */
  88170. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  88171. if (this._standingMatrix) {
  88172. // Add standing matrix offset to get real offset from ground in room
  88173. this._standingMatrix.getTranslationToRef(this._workingVector);
  88174. return this._deviceRoomPosition.y + this._workingVector.y;
  88175. }
  88176. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  88177. return this._defaultHeight || 0;
  88178. };
  88179. /**
  88180. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88181. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  88182. */
  88183. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  88184. var _this = this;
  88185. if (callback === void 0) { callback = function (bool) { }; }
  88186. // Use standing matrix if available
  88187. this.getEngine().initWebVRAsync().then(function (result) {
  88188. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  88189. callback(false);
  88190. }
  88191. else {
  88192. _this._standingMatrix = new BABYLON.Matrix();
  88193. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  88194. if (!_this.getScene().useRightHandedSystem) {
  88195. [2, 6, 8, 9, 14].forEach(function (num) {
  88196. if (_this._standingMatrix) {
  88197. _this._standingMatrix.m[num] *= -1;
  88198. }
  88199. });
  88200. }
  88201. callback(true);
  88202. }
  88203. });
  88204. };
  88205. /**
  88206. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  88207. * @returns A promise with a boolean set to if the standing matrix is supported.
  88208. */
  88209. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  88210. var _this = this;
  88211. return new Promise(function (res, rej) {
  88212. _this.useStandingMatrix(function (supported) {
  88213. res(supported);
  88214. });
  88215. });
  88216. };
  88217. /**
  88218. * Disposes the camera
  88219. */
  88220. WebVRFreeCamera.prototype.dispose = function () {
  88221. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  88222. _super.prototype.dispose.call(this);
  88223. };
  88224. /**
  88225. * Gets a vrController by name.
  88226. * @param name The name of the controller to retreive
  88227. * @returns the controller matching the name specified or null if not found
  88228. */
  88229. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  88230. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  88231. var gp = _a[_i];
  88232. if (gp.hand === name) {
  88233. return gp;
  88234. }
  88235. }
  88236. return null;
  88237. };
  88238. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  88239. /**
  88240. * The controller corrisponding to the users left hand.
  88241. */
  88242. get: function () {
  88243. if (!this._leftController) {
  88244. this._leftController = this.getControllerByName("left");
  88245. }
  88246. return this._leftController;
  88247. },
  88248. enumerable: true,
  88249. configurable: true
  88250. });
  88251. ;
  88252. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  88253. /**
  88254. * The controller corrisponding to the users right hand.
  88255. */
  88256. get: function () {
  88257. if (!this._rightController) {
  88258. this._rightController = this.getControllerByName("right");
  88259. }
  88260. return this._rightController;
  88261. },
  88262. enumerable: true,
  88263. configurable: true
  88264. });
  88265. ;
  88266. /**
  88267. * Casts a ray forward from the vrCamera's gaze.
  88268. * @param length Length of the ray (default: 100)
  88269. * @returns the ray corrisponding to the gaze
  88270. */
  88271. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  88272. if (length === void 0) { length = 100; }
  88273. if (this.leftCamera) {
  88274. // Use left eye to avoid computation to compute center on every call
  88275. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  88276. }
  88277. else {
  88278. return _super.prototype.getForwardRay.call(this, length);
  88279. }
  88280. };
  88281. /**
  88282. * Updates the camera based on device's frame data
  88283. */
  88284. WebVRFreeCamera.prototype._checkInputs = function () {
  88285. if (this._vrDevice && this._vrDevice.isPresenting) {
  88286. this._vrDevice.getFrameData(this._frameData);
  88287. this.updateFromDevice(this._frameData.pose);
  88288. }
  88289. _super.prototype._checkInputs.call(this);
  88290. };
  88291. /**
  88292. * Updates the poseControlled values based on the input device pose.
  88293. * @param poseData Pose coming from the device
  88294. */
  88295. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  88296. if (poseData && poseData.orientation) {
  88297. this.rawPose = poseData;
  88298. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  88299. if (this.getScene().useRightHandedSystem) {
  88300. this._deviceRoomRotationQuaternion.z *= -1;
  88301. this._deviceRoomRotationQuaternion.w *= -1;
  88302. }
  88303. if (this.webVROptions.trackPosition && this.rawPose.position) {
  88304. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  88305. if (this.getScene().useRightHandedSystem) {
  88306. this._deviceRoomPosition.z *= -1;
  88307. }
  88308. }
  88309. }
  88310. };
  88311. /**
  88312. * WebVR's attach control will start broadcasting frames to the device.
  88313. * Note that in certain browsers (chrome for example) this function must be called
  88314. * within a user-interaction callback. Example:
  88315. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  88316. *
  88317. * @param element html element to attach the vrDevice to
  88318. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  88319. */
  88320. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  88321. _super.prototype.attachControl.call(this, element, noPreventDefault);
  88322. this._attached = true;
  88323. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  88324. if (this._vrDevice) {
  88325. this.getEngine().enableVR();
  88326. }
  88327. };
  88328. /**
  88329. * Detaches the camera from the html element and disables VR
  88330. *
  88331. * @param element html element to detach from
  88332. */
  88333. WebVRFreeCamera.prototype.detachControl = function (element) {
  88334. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  88335. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  88336. _super.prototype.detachControl.call(this, element);
  88337. this._attached = false;
  88338. this.getEngine().disableVR();
  88339. };
  88340. /**
  88341. * @returns the name of this class
  88342. */
  88343. WebVRFreeCamera.prototype.getClassName = function () {
  88344. return "WebVRFreeCamera";
  88345. };
  88346. /**
  88347. * Calls resetPose on the vrDisplay
  88348. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  88349. */
  88350. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  88351. //uses the vrDisplay's "resetPose()".
  88352. //pitch and roll won't be affected.
  88353. this._vrDevice.resetPose();
  88354. };
  88355. /**
  88356. * Updates the rig cameras (left and right eye)
  88357. */
  88358. WebVRFreeCamera.prototype._updateRigCameras = function () {
  88359. var camLeft = this._rigCameras[0];
  88360. var camRight = this._rigCameras[1];
  88361. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  88362. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  88363. camLeft.position.copyFrom(this._deviceRoomPosition);
  88364. camRight.position.copyFrom(this._deviceRoomPosition);
  88365. };
  88366. /**
  88367. * Updates the cached values of the camera
  88368. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  88369. */
  88370. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  88371. var _this = this;
  88372. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  88373. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  88374. if (!this.updateCacheCalled) {
  88375. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  88376. this.updateCacheCalled = true;
  88377. this.update();
  88378. }
  88379. // Set working vector to the device position in room space rotated by the new rotation
  88380. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  88381. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  88382. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  88383. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  88384. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  88385. // Add translation from anchor position
  88386. this._deviceToWorld.getTranslationToRef(this._workingVector);
  88387. this._workingVector.addInPlace(this.position);
  88388. this._workingVector.subtractInPlace(this._cache.position);
  88389. this._deviceToWorld.setTranslation(this._workingVector);
  88390. // Set an inverted matrix to be used when updating the camera
  88391. this._deviceToWorld.invertToRef(this._worldToDevice);
  88392. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  88393. this.controllers.forEach(function (controller) {
  88394. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  88395. controller.update();
  88396. });
  88397. }
  88398. if (!ignoreParentClass) {
  88399. _super.prototype._updateCache.call(this);
  88400. }
  88401. this.updateCacheCalled = false;
  88402. };
  88403. /**
  88404. * Updates the current device position and rotation in the babylon world
  88405. */
  88406. WebVRFreeCamera.prototype.update = function () {
  88407. // Get current device position in babylon world
  88408. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  88409. // Get current device rotation in babylon world
  88410. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  88411. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  88412. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  88413. _super.prototype.update.call(this);
  88414. };
  88415. /**
  88416. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  88417. * @returns an identity matrix
  88418. */
  88419. WebVRFreeCamera.prototype._getViewMatrix = function () {
  88420. return BABYLON.Matrix.Identity();
  88421. };
  88422. /**
  88423. * This function is called by the two RIG cameras.
  88424. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  88425. */
  88426. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  88427. var _this = this;
  88428. // Update the parent camera prior to using a child camera to avoid desynchronization
  88429. var parentCamera = this._cameraRigParams["parentCamera"];
  88430. parentCamera._updateCache();
  88431. //WebVR 1.1
  88432. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  88433. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  88434. if (!this.getScene().useRightHandedSystem) {
  88435. [2, 6, 8, 9, 14].forEach(function (num) {
  88436. _this._webvrViewMatrix.m[num] *= -1;
  88437. });
  88438. }
  88439. // update the camera rotation matrix
  88440. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  88441. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  88442. // Computing target and final matrix
  88443. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  88444. // should the view matrix be updated with scale and position offset?
  88445. if (parentCamera.deviceScaleFactor !== 1) {
  88446. this._webvrViewMatrix.invert();
  88447. // scale the position, if set
  88448. if (parentCamera.deviceScaleFactor) {
  88449. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  88450. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  88451. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  88452. }
  88453. this._webvrViewMatrix.invert();
  88454. }
  88455. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  88456. // Compute global position
  88457. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  88458. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  88459. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  88460. this._workingMatrix.getTranslationToRef(this._globalPosition);
  88461. this._markSyncedWithParent();
  88462. return this._webvrViewMatrix;
  88463. };
  88464. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  88465. var _this = this;
  88466. var parentCamera = this.parent;
  88467. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  88468. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  88469. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  88470. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  88471. //babylon compatible matrix
  88472. if (!this.getScene().useRightHandedSystem) {
  88473. [8, 9, 10, 11].forEach(function (num) {
  88474. _this._projectionMatrix.m[num] *= -1;
  88475. });
  88476. }
  88477. return this._projectionMatrix;
  88478. };
  88479. /**
  88480. * Initializes the controllers and their meshes
  88481. */
  88482. WebVRFreeCamera.prototype.initControllers = function () {
  88483. var _this = this;
  88484. this.controllers = [];
  88485. var manager = this.getScene().gamepadManager;
  88486. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  88487. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  88488. var webVrController = gamepad;
  88489. if (webVrController.defaultModel) {
  88490. webVrController.defaultModel.setEnabled(false);
  88491. }
  88492. if (webVrController.hand === "right") {
  88493. _this._rightController = null;
  88494. }
  88495. if (webVrController.hand === "left") {
  88496. _this._leftController = null;
  88497. }
  88498. var controllerIndex = _this.controllers.indexOf(webVrController);
  88499. if (controllerIndex !== -1) {
  88500. _this.controllers.splice(controllerIndex, 1);
  88501. }
  88502. }
  88503. });
  88504. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  88505. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  88506. var webVrController_1 = gamepad;
  88507. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  88508. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  88509. if (_this.webVROptions.controllerMeshes) {
  88510. if (webVrController_1.defaultModel) {
  88511. webVrController_1.defaultModel.setEnabled(true);
  88512. }
  88513. else {
  88514. // Load the meshes
  88515. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  88516. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  88517. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  88518. if (_this.webVROptions.defaultLightingOnControllers) {
  88519. if (!_this._lightOnControllers) {
  88520. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  88521. }
  88522. var activateLightOnSubMeshes_1 = function (mesh, light) {
  88523. var children = mesh.getChildren();
  88524. if (children.length !== 0) {
  88525. children.forEach(function (mesh) {
  88526. light.includedOnlyMeshes.push(mesh);
  88527. activateLightOnSubMeshes_1(mesh, light);
  88528. });
  88529. }
  88530. };
  88531. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  88532. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  88533. }
  88534. });
  88535. }
  88536. }
  88537. webVrController_1.attachToPoseControlledCamera(_this);
  88538. // since this is async - sanity check. Is the controller already stored?
  88539. if (_this.controllers.indexOf(webVrController_1) === -1) {
  88540. //add to the controllers array
  88541. _this.controllers.push(webVrController_1);
  88542. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  88543. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  88544. // So we're overriding setting left & right manually to be sure
  88545. var firstViveWandDetected = false;
  88546. for (var i = 0; i < _this.controllers.length; i++) {
  88547. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88548. if (!firstViveWandDetected) {
  88549. firstViveWandDetected = true;
  88550. _this.controllers[i].hand = "left";
  88551. }
  88552. else {
  88553. _this.controllers[i].hand = "right";
  88554. }
  88555. }
  88556. }
  88557. //did we find enough controllers? Great! let the developer know.
  88558. if (_this.controllers.length >= 2) {
  88559. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  88560. }
  88561. }
  88562. }
  88563. });
  88564. };
  88565. return WebVRFreeCamera;
  88566. }(BABYLON.FreeCamera));
  88567. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  88568. })(BABYLON || (BABYLON = {}));
  88569. //# sourceMappingURL=babylon.webVRCamera.js.map
  88570. var BABYLON;
  88571. (function (BABYLON) {
  88572. // We're mainly based on the logic defined into the FreeCamera code
  88573. /**
  88574. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  88575. * being tilted forward or back and left or right.
  88576. */
  88577. var DeviceOrientationCamera = /** @class */ (function (_super) {
  88578. __extends(DeviceOrientationCamera, _super);
  88579. /**
  88580. * Creates a new device orientation camera
  88581. * @param name The name of the camera
  88582. * @param position The start position camera
  88583. * @param scene The scene the camera belongs to
  88584. */
  88585. function DeviceOrientationCamera(name, position, scene) {
  88586. var _this = _super.call(this, name, position, scene) || this;
  88587. _this._quaternionCache = new BABYLON.Quaternion();
  88588. _this.inputs.addDeviceOrientation();
  88589. return _this;
  88590. }
  88591. /**
  88592. * Gets the current instance class name ("DeviceOrientationCamera").
  88593. * This helps avoiding instanceof at run time.
  88594. * @returns the class name
  88595. */
  88596. DeviceOrientationCamera.prototype.getClassName = function () {
  88597. return "DeviceOrientationCamera";
  88598. };
  88599. /**
  88600. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  88601. */
  88602. DeviceOrientationCamera.prototype._checkInputs = function () {
  88603. _super.prototype._checkInputs.call(this);
  88604. this._quaternionCache.copyFrom(this.rotationQuaternion);
  88605. if (this._initialQuaternion) {
  88606. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  88607. }
  88608. };
  88609. /**
  88610. * Reset the camera to its default orientation on the specified axis only.
  88611. * @param axis The axis to reset
  88612. */
  88613. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  88614. var _this = this;
  88615. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  88616. //can only work if this camera has a rotation quaternion already.
  88617. if (!this.rotationQuaternion)
  88618. return;
  88619. if (!this._initialQuaternion) {
  88620. this._initialQuaternion = new BABYLON.Quaternion();
  88621. }
  88622. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  88623. ['x', 'y', 'z'].forEach(function (axisName) {
  88624. if (!axis[axisName]) {
  88625. _this._initialQuaternion[axisName] = 0;
  88626. }
  88627. else {
  88628. _this._initialQuaternion[axisName] *= -1;
  88629. }
  88630. });
  88631. this._initialQuaternion.normalize();
  88632. //force rotation update
  88633. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  88634. };
  88635. return DeviceOrientationCamera;
  88636. }(BABYLON.FreeCamera));
  88637. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  88638. })(BABYLON || (BABYLON = {}));
  88639. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  88640. var BABYLON;
  88641. (function (BABYLON) {
  88642. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  88643. __extends(VRDeviceOrientationFreeCamera, _super);
  88644. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  88645. if (compensateDistortion === void 0) { compensateDistortion = true; }
  88646. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  88647. var _this = _super.call(this, name, position, scene) || this;
  88648. vrCameraMetrics.compensateDistortion = compensateDistortion;
  88649. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  88650. return _this;
  88651. }
  88652. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  88653. return "VRDeviceOrientationFreeCamera";
  88654. };
  88655. return VRDeviceOrientationFreeCamera;
  88656. }(BABYLON.DeviceOrientationCamera));
  88657. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  88658. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  88659. __extends(VRDeviceOrientationGamepadCamera, _super);
  88660. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  88661. if (compensateDistortion === void 0) { compensateDistortion = true; }
  88662. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  88663. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  88664. _this.inputs.addGamepad();
  88665. return _this;
  88666. }
  88667. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  88668. return "VRDeviceOrientationGamepadCamera";
  88669. };
  88670. return VRDeviceOrientationGamepadCamera;
  88671. }(VRDeviceOrientationFreeCamera));
  88672. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  88673. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  88674. __extends(VRDeviceOrientationArcRotateCamera, _super);
  88675. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  88676. if (compensateDistortion === void 0) { compensateDistortion = true; }
  88677. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  88678. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88679. vrCameraMetrics.compensateDistortion = compensateDistortion;
  88680. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  88681. _this.inputs.addVRDeviceOrientation();
  88682. return _this;
  88683. }
  88684. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  88685. return "VRDeviceOrientationArcRotateCamera";
  88686. };
  88687. return VRDeviceOrientationArcRotateCamera;
  88688. }(BABYLON.ArcRotateCamera));
  88689. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  88690. })(BABYLON || (BABYLON = {}));
  88691. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  88692. var BABYLON;
  88693. (function (BABYLON) {
  88694. /**
  88695. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  88696. */
  88697. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  88698. __extends(AnaglyphFreeCamera, _super);
  88699. /**
  88700. * Creates a new AnaglyphFreeCamera
  88701. * @param name defines camera name
  88702. * @param position defines initial position
  88703. * @param interaxialDistance defines distance between each color axis
  88704. * @param scene defines the hosting scene
  88705. */
  88706. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  88707. var _this = _super.call(this, name, position, scene) || this;
  88708. _this.interaxialDistance = interaxialDistance;
  88709. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88710. return _this;
  88711. }
  88712. /**
  88713. * Gets camera class name
  88714. * @returns AnaglyphFreeCamera
  88715. */
  88716. AnaglyphFreeCamera.prototype.getClassName = function () {
  88717. return "AnaglyphFreeCamera";
  88718. };
  88719. return AnaglyphFreeCamera;
  88720. }(BABYLON.FreeCamera));
  88721. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  88722. /**
  88723. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  88724. */
  88725. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  88726. __extends(AnaglyphArcRotateCamera, _super);
  88727. /**
  88728. * Creates a new AnaglyphArcRotateCamera
  88729. * @param name defines camera name
  88730. * @param alpha defines alpha angle (in radians)
  88731. * @param beta defines beta angle (in radians)
  88732. * @param radius defines radius
  88733. * @param target defines camera target
  88734. * @param interaxialDistance defines distance between each color axis
  88735. * @param scene defines the hosting scene
  88736. */
  88737. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  88738. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88739. _this.interaxialDistance = interaxialDistance;
  88740. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88741. return _this;
  88742. }
  88743. /**
  88744. * Gets camera class name
  88745. * @returns AnaglyphArcRotateCamera
  88746. */
  88747. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  88748. return "AnaglyphArcRotateCamera";
  88749. };
  88750. return AnaglyphArcRotateCamera;
  88751. }(BABYLON.ArcRotateCamera));
  88752. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  88753. /**
  88754. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  88755. */
  88756. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  88757. __extends(AnaglyphGamepadCamera, _super);
  88758. /**
  88759. * Creates a new AnaglyphGamepadCamera
  88760. * @param name defines camera name
  88761. * @param position defines initial position
  88762. * @param interaxialDistance defines distance between each color axis
  88763. * @param scene defines the hosting scene
  88764. */
  88765. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  88766. var _this = _super.call(this, name, position, scene) || this;
  88767. _this.interaxialDistance = interaxialDistance;
  88768. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88769. return _this;
  88770. }
  88771. /**
  88772. * Gets camera class name
  88773. * @returns AnaglyphGamepadCamera
  88774. */
  88775. AnaglyphGamepadCamera.prototype.getClassName = function () {
  88776. return "AnaglyphGamepadCamera";
  88777. };
  88778. return AnaglyphGamepadCamera;
  88779. }(BABYLON.GamepadCamera));
  88780. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  88781. /**
  88782. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  88783. */
  88784. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  88785. __extends(AnaglyphUniversalCamera, _super);
  88786. /**
  88787. * Creates a new AnaglyphUniversalCamera
  88788. * @param name defines camera name
  88789. * @param position defines initial position
  88790. * @param interaxialDistance defines distance between each color axis
  88791. * @param scene defines the hosting scene
  88792. */
  88793. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  88794. var _this = _super.call(this, name, position, scene) || this;
  88795. _this.interaxialDistance = interaxialDistance;
  88796. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  88797. return _this;
  88798. }
  88799. /**
  88800. * Gets camera class name
  88801. * @returns AnaglyphUniversalCamera
  88802. */
  88803. AnaglyphUniversalCamera.prototype.getClassName = function () {
  88804. return "AnaglyphUniversalCamera";
  88805. };
  88806. return AnaglyphUniversalCamera;
  88807. }(BABYLON.UniversalCamera));
  88808. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  88809. /**
  88810. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  88811. */
  88812. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  88813. __extends(StereoscopicFreeCamera, _super);
  88814. /**
  88815. * Creates a new StereoscopicFreeCamera
  88816. * @param name defines camera name
  88817. * @param position defines initial position
  88818. * @param interaxialDistance defines distance between each color axis
  88819. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88820. * @param scene defines the hosting scene
  88821. */
  88822. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88823. var _this = _super.call(this, name, position, scene) || this;
  88824. _this.interaxialDistance = interaxialDistance;
  88825. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88826. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88827. return _this;
  88828. }
  88829. /**
  88830. * Gets camera class name
  88831. * @returns StereoscopicFreeCamera
  88832. */
  88833. StereoscopicFreeCamera.prototype.getClassName = function () {
  88834. return "StereoscopicFreeCamera";
  88835. };
  88836. return StereoscopicFreeCamera;
  88837. }(BABYLON.FreeCamera));
  88838. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  88839. /**
  88840. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  88841. */
  88842. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  88843. __extends(StereoscopicArcRotateCamera, _super);
  88844. /**
  88845. * Creates a new StereoscopicArcRotateCamera
  88846. * @param name defines camera name
  88847. * @param alpha defines alpha angle (in radians)
  88848. * @param beta defines beta angle (in radians)
  88849. * @param radius defines radius
  88850. * @param target defines camera target
  88851. * @param interaxialDistance defines distance between each color axis
  88852. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88853. * @param scene defines the hosting scene
  88854. */
  88855. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  88856. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  88857. _this.interaxialDistance = interaxialDistance;
  88858. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88859. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88860. return _this;
  88861. }
  88862. /**
  88863. * Gets camera class name
  88864. * @returns StereoscopicArcRotateCamera
  88865. */
  88866. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  88867. return "StereoscopicArcRotateCamera";
  88868. };
  88869. return StereoscopicArcRotateCamera;
  88870. }(BABYLON.ArcRotateCamera));
  88871. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  88872. /**
  88873. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  88874. */
  88875. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  88876. __extends(StereoscopicGamepadCamera, _super);
  88877. /**
  88878. * Creates a new StereoscopicGamepadCamera
  88879. * @param name defines camera name
  88880. * @param position defines initial position
  88881. * @param interaxialDistance defines distance between each color axis
  88882. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88883. * @param scene defines the hosting scene
  88884. */
  88885. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88886. var _this = _super.call(this, name, position, scene) || this;
  88887. _this.interaxialDistance = interaxialDistance;
  88888. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88889. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88890. return _this;
  88891. }
  88892. /**
  88893. * Gets camera class name
  88894. * @returns StereoscopicGamepadCamera
  88895. */
  88896. StereoscopicGamepadCamera.prototype.getClassName = function () {
  88897. return "StereoscopicGamepadCamera";
  88898. };
  88899. return StereoscopicGamepadCamera;
  88900. }(BABYLON.GamepadCamera));
  88901. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  88902. /**
  88903. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  88904. */
  88905. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  88906. __extends(StereoscopicUniversalCamera, _super);
  88907. /**
  88908. * Creates a new StereoscopicUniversalCamera
  88909. * @param name defines camera name
  88910. * @param position defines initial position
  88911. * @param interaxialDistance defines distance between each color axis
  88912. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  88913. * @param scene defines the hosting scene
  88914. */
  88915. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  88916. var _this = _super.call(this, name, position, scene) || this;
  88917. _this.interaxialDistance = interaxialDistance;
  88918. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  88919. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  88920. return _this;
  88921. }
  88922. /**
  88923. * Gets camera class name
  88924. * @returns StereoscopicUniversalCamera
  88925. */
  88926. StereoscopicUniversalCamera.prototype.getClassName = function () {
  88927. return "StereoscopicUniversalCamera";
  88928. };
  88929. return StereoscopicUniversalCamera;
  88930. }(BABYLON.UniversalCamera));
  88931. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  88932. })(BABYLON || (BABYLON = {}));
  88933. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  88934. var BABYLON;
  88935. (function (BABYLON) {
  88936. var VRExperienceHelperGazer = /** @class */ (function () {
  88937. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  88938. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  88939. this.scene = scene;
  88940. this._pointerDownOnMeshAsked = false;
  88941. this._isActionableMesh = false;
  88942. this._teleportationRequestInitiated = false;
  88943. this._teleportationBackRequestInitiated = false;
  88944. this._rotationRightAsked = false;
  88945. this._rotationLeftAsked = false;
  88946. this._dpadPressed = true;
  88947. this._activePointer = false;
  88948. this._id = VRExperienceHelperGazer._idCounter++;
  88949. // Gaze tracker
  88950. if (!gazeTrackerToClone) {
  88951. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  88952. this._gazeTracker.bakeCurrentTransformIntoVertices();
  88953. this._gazeTracker.isPickable = false;
  88954. this._gazeTracker.isVisible = false;
  88955. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  88956. targetMat.specularColor = BABYLON.Color3.Black();
  88957. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  88958. targetMat.backFaceCulling = false;
  88959. this._gazeTracker.material = targetMat;
  88960. }
  88961. else {
  88962. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  88963. }
  88964. }
  88965. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  88966. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  88967. };
  88968. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  88969. this._pointerDownOnMeshAsked = true;
  88970. if (this._currentHit) {
  88971. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  88972. }
  88973. };
  88974. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  88975. if (this._currentHit) {
  88976. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  88977. }
  88978. this._pointerDownOnMeshAsked = false;
  88979. };
  88980. VRExperienceHelperGazer.prototype._activatePointer = function () {
  88981. this._activePointer = true;
  88982. };
  88983. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  88984. this._activePointer = false;
  88985. };
  88986. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  88987. if (distance === void 0) { distance = 100; }
  88988. };
  88989. VRExperienceHelperGazer.prototype.dispose = function () {
  88990. this._interactionsEnabled = false;
  88991. this._teleportationEnabled = false;
  88992. if (this._gazeTracker) {
  88993. this._gazeTracker.dispose();
  88994. }
  88995. };
  88996. VRExperienceHelperGazer._idCounter = 0;
  88997. return VRExperienceHelperGazer;
  88998. }());
  88999. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  89000. __extends(VRExperienceHelperControllerGazer, _super);
  89001. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  89002. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  89003. _this.webVRController = webVRController;
  89004. // Laser pointer
  89005. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  89006. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  89007. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  89008. laserPointerMaterial.alpha = 0.6;
  89009. _this._laserPointer.material = laserPointerMaterial;
  89010. _this._laserPointer.rotation.x = Math.PI / 2;
  89011. _this._laserPointer.position.z = -0.5;
  89012. _this._laserPointer.isVisible = false;
  89013. if (!webVRController.mesh) {
  89014. // Create an empty mesh that is used prior to loading the high quality model
  89015. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  89016. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  89017. preloadPointerPose.rotation.x = -0.7;
  89018. preloadMesh.addChild(preloadPointerPose);
  89019. webVRController.attachToMesh(preloadMesh);
  89020. }
  89021. _this._setLaserPointerParent(webVRController.mesh);
  89022. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  89023. _this._setLaserPointerParent(mesh);
  89024. });
  89025. return _this;
  89026. }
  89027. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  89028. return this.webVRController.getForwardRay(length);
  89029. };
  89030. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  89031. _super.prototype._activatePointer.call(this);
  89032. this._laserPointer.isVisible = true;
  89033. };
  89034. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  89035. _super.prototype._deactivatePointer.call(this);
  89036. this._laserPointer.isVisible = false;
  89037. };
  89038. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  89039. this._laserPointer.material.emissiveColor = color;
  89040. };
  89041. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  89042. var makeNotPick = function (root) {
  89043. root.name += " laserPointer";
  89044. root.getChildMeshes().forEach(function (c) {
  89045. makeNotPick(c);
  89046. });
  89047. };
  89048. makeNotPick(mesh);
  89049. var childMeshes = mesh.getChildMeshes();
  89050. this.webVRController._pointingPoseNode = null;
  89051. for (var i = 0; i < childMeshes.length; i++) {
  89052. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  89053. mesh = childMeshes[i];
  89054. this.webVRController._pointingPoseNode = mesh;
  89055. break;
  89056. }
  89057. }
  89058. this._laserPointer.parent = mesh;
  89059. };
  89060. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  89061. if (distance === void 0) { distance = 100; }
  89062. this._laserPointer.scaling.y = distance;
  89063. this._laserPointer.position.z = -distance / 2;
  89064. };
  89065. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  89066. _super.prototype.dispose.call(this);
  89067. this._laserPointer.dispose();
  89068. if (this._meshAttachedObserver) {
  89069. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  89070. }
  89071. };
  89072. return VRExperienceHelperControllerGazer;
  89073. }(VRExperienceHelperGazer));
  89074. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  89075. __extends(VRExperienceHelperCameraGazer, _super);
  89076. function VRExperienceHelperCameraGazer(getCamera, scene) {
  89077. var _this = _super.call(this, scene) || this;
  89078. _this.getCamera = getCamera;
  89079. return _this;
  89080. }
  89081. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  89082. var camera = this.getCamera();
  89083. if (camera) {
  89084. return camera.getForwardRay(length);
  89085. }
  89086. else {
  89087. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  89088. }
  89089. };
  89090. return VRExperienceHelperCameraGazer;
  89091. }(VRExperienceHelperGazer));
  89092. /**
  89093. * Helps to quickly add VR support to an existing scene.
  89094. * See http://doc.babylonjs.com/how_to/webvr_helper
  89095. */
  89096. var VRExperienceHelper = /** @class */ (function () {
  89097. /**
  89098. * Instantiates a VRExperienceHelper.
  89099. * Helps to quickly add VR support to an existing scene.
  89100. * @param scene The scene the VRExperienceHelper belongs to.
  89101. * @param webVROptions Options to modify the vr experience helper's behavior.
  89102. */
  89103. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  89104. if (webVROptions === void 0) { webVROptions = {}; }
  89105. var _this = this;
  89106. this.webVROptions = webVROptions;
  89107. // Can the system support WebVR, even if a headset isn't plugged in?
  89108. this._webVRsupported = false;
  89109. // If WebVR is supported, is a headset plugged in and are we ready to present?
  89110. this._webVRready = false;
  89111. // Are we waiting for the requestPresent callback to complete?
  89112. this._webVRrequesting = false;
  89113. // Are we presenting to the headset right now?
  89114. this._webVRpresenting = false;
  89115. // Are we presenting in the fullscreen fallback?
  89116. this._fullscreenVRpresenting = false;
  89117. /**
  89118. * Observable raised when entering VR.
  89119. */
  89120. this.onEnteringVRObservable = new BABYLON.Observable();
  89121. /**
  89122. * Observable raised when exiting VR.
  89123. */
  89124. this.onExitingVRObservable = new BABYLON.Observable();
  89125. /**
  89126. * Observable raised when controller mesh is loaded.
  89127. */
  89128. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  89129. this._useCustomVRButton = false;
  89130. this._teleportationRequested = false;
  89131. this._teleportActive = false;
  89132. this._floorMeshesCollection = [];
  89133. this._rotationAllowed = true;
  89134. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  89135. this._isDefaultTeleportationTarget = true;
  89136. this._teleportationFillColor = "#444444";
  89137. this._teleportationBorderColor = "#FFFFFF";
  89138. this._rotationAngle = 0;
  89139. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  89140. this._padSensibilityUp = 0.65;
  89141. this._padSensibilityDown = 0.35;
  89142. this.leftController = null;
  89143. this.rightController = null;
  89144. /**
  89145. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  89146. */
  89147. this.onNewMeshSelected = new BABYLON.Observable();
  89148. /**
  89149. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  89150. */
  89151. this.onNewMeshPicked = new BABYLON.Observable();
  89152. /**
  89153. * Observable raised before camera teleportation
  89154. */
  89155. this.onBeforeCameraTeleport = new BABYLON.Observable();
  89156. /**
  89157. * Observable raised after camera teleportation
  89158. */
  89159. this.onAfterCameraTeleport = new BABYLON.Observable();
  89160. /**
  89161. * Observable raised when current selected mesh gets unselected
  89162. */
  89163. this.onSelectedMeshUnselected = new BABYLON.Observable();
  89164. /**
  89165. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  89166. */
  89167. this.teleportationEnabled = true;
  89168. this._teleportationInitialized = false;
  89169. this._interactionsEnabled = false;
  89170. this._interactionsRequested = false;
  89171. this._displayGaze = true;
  89172. this._displayLaserPointer = true;
  89173. this._onResize = function () {
  89174. _this.moveButtonToBottomRight();
  89175. if (_this._fullscreenVRpresenting && _this._webVRready) {
  89176. _this.exitVR();
  89177. }
  89178. };
  89179. this._onFullscreenChange = function () {
  89180. if (document.fullscreen !== undefined) {
  89181. _this._fullscreenVRpresenting = document.fullscreen;
  89182. }
  89183. else if (document.mozFullScreen !== undefined) {
  89184. _this._fullscreenVRpresenting = document.mozFullScreen;
  89185. }
  89186. else if (document.webkitIsFullScreen !== undefined) {
  89187. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  89188. }
  89189. else if (document.msIsFullScreen !== undefined) {
  89190. _this._fullscreenVRpresenting = document.msIsFullScreen;
  89191. }
  89192. if (!_this._fullscreenVRpresenting && _this._canvas) {
  89193. _this.exitVR();
  89194. if (!_this._useCustomVRButton) {
  89195. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  89196. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  89197. }
  89198. }
  89199. };
  89200. this.beforeRender = function () {
  89201. if (_this.leftController && _this.leftController._activePointer) {
  89202. _this._castRayAndSelectObject(_this.leftController);
  89203. }
  89204. if (_this.rightController && _this.rightController._activePointer) {
  89205. _this._castRayAndSelectObject(_this.rightController);
  89206. }
  89207. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  89208. _this._castRayAndSelectObject(_this._cameraGazer);
  89209. }
  89210. else {
  89211. _this._cameraGazer._gazeTracker.isVisible = false;
  89212. }
  89213. };
  89214. this._onNewGamepadConnected = function (gamepad) {
  89215. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  89216. if (gamepad.leftStick) {
  89217. gamepad.onleftstickchanged(function (stickValues) {
  89218. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  89219. // Listening to classic/xbox gamepad only if no VR controller is active
  89220. if ((!_this.leftController && !_this.rightController) ||
  89221. ((_this.leftController && !_this.leftController._activePointer) &&
  89222. (_this.rightController && !_this.rightController._activePointer))) {
  89223. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  89224. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  89225. }
  89226. }
  89227. });
  89228. }
  89229. if (gamepad.rightStick) {
  89230. gamepad.onrightstickchanged(function (stickValues) {
  89231. if (_this._teleportationInitialized) {
  89232. _this._checkRotate(stickValues, _this._cameraGazer);
  89233. }
  89234. });
  89235. }
  89236. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  89237. gamepad.onbuttondown(function (buttonPressed) {
  89238. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89239. _this._cameraGazer._selectionPointerDown();
  89240. }
  89241. });
  89242. gamepad.onbuttonup(function (buttonPressed) {
  89243. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  89244. _this._cameraGazer._selectionPointerUp();
  89245. }
  89246. });
  89247. }
  89248. }
  89249. else {
  89250. var webVRController = gamepad;
  89251. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  89252. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  89253. _this.rightController = controller;
  89254. }
  89255. else {
  89256. _this.leftController = controller;
  89257. }
  89258. _this._tryEnableInteractionOnController(controller);
  89259. }
  89260. };
  89261. // 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
  89262. this._tryEnableInteractionOnController = function (controller) {
  89263. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  89264. _this._enableInteractionOnController(controller);
  89265. }
  89266. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  89267. _this._enableTeleportationOnController(controller);
  89268. }
  89269. };
  89270. this._onNewGamepadDisconnected = function (gamepad) {
  89271. if (gamepad instanceof BABYLON.WebVRController) {
  89272. if (gamepad.hand === "left" && _this.leftController != null) {
  89273. _this.leftController.dispose();
  89274. _this.leftController = null;
  89275. }
  89276. if (gamepad.hand === "right" && _this.rightController != null) {
  89277. _this.rightController.dispose();
  89278. _this.rightController = null;
  89279. }
  89280. }
  89281. };
  89282. this._workingVector = BABYLON.Vector3.Zero();
  89283. this._workingQuaternion = BABYLON.Quaternion.Identity();
  89284. this._workingMatrix = BABYLON.Matrix.Identity();
  89285. this._scene = scene;
  89286. this._canvas = scene.getEngine().getRenderingCanvas();
  89287. // Parse options
  89288. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  89289. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  89290. }
  89291. if (webVROptions.createDeviceOrientationCamera === undefined) {
  89292. webVROptions.createDeviceOrientationCamera = true;
  89293. }
  89294. if (webVROptions.laserToggle === undefined) {
  89295. webVROptions.laserToggle = true;
  89296. }
  89297. if (webVROptions.defaultHeight === undefined) {
  89298. webVROptions.defaultHeight = 1.7;
  89299. }
  89300. if (webVROptions.useCustomVRButton) {
  89301. this._useCustomVRButton = true;
  89302. if (webVROptions.customVRButton) {
  89303. this._btnVR = webVROptions.customVRButton;
  89304. }
  89305. }
  89306. if (webVROptions.rayLength) {
  89307. this._rayLength = webVROptions.rayLength;
  89308. }
  89309. this._defaultHeight = webVROptions.defaultHeight;
  89310. if (webVROptions.positionScale) {
  89311. this._rayLength *= webVROptions.positionScale;
  89312. this._defaultHeight *= webVROptions.positionScale;
  89313. }
  89314. // Set position
  89315. if (this._scene.activeCamera) {
  89316. this._position = this._scene.activeCamera.position.clone();
  89317. }
  89318. else {
  89319. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  89320. }
  89321. // Set non-vr camera
  89322. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  89323. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  89324. // Copy data from existing camera
  89325. if (this._scene.activeCamera) {
  89326. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89327. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  89328. // Set rotation from previous camera
  89329. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  89330. var targetCamera = this._scene.activeCamera;
  89331. if (targetCamera.rotationQuaternion) {
  89332. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  89333. }
  89334. else {
  89335. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  89336. }
  89337. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  89338. }
  89339. }
  89340. this._scene.activeCamera = this._deviceOrientationCamera;
  89341. if (this._canvas) {
  89342. this._scene.activeCamera.attachControl(this._canvas);
  89343. }
  89344. }
  89345. else {
  89346. this._existingCamera = this._scene.activeCamera;
  89347. }
  89348. // Create VR cameras
  89349. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  89350. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  89351. }
  89352. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  89353. this._webVRCamera.useStandingMatrix();
  89354. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  89355. // Create default button
  89356. if (!this._useCustomVRButton) {
  89357. this._btnVR = document.createElement("BUTTON");
  89358. this._btnVR.className = "babylonVRicon";
  89359. this._btnVR.id = "babylonVRiconbtn";
  89360. this._btnVR.title = "Click to switch to VR";
  89361. 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) }";
  89362. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  89363. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  89364. // css += ".babylonVRicon.vrdisplaysupported { }";
  89365. // css += ".babylonVRicon.vrdisplayready { }";
  89366. // css += ".babylonVRicon.vrdisplayrequesting { }";
  89367. var style = document.createElement('style');
  89368. style.appendChild(document.createTextNode(css));
  89369. document.getElementsByTagName('head')[0].appendChild(style);
  89370. this.moveButtonToBottomRight();
  89371. }
  89372. // VR button click event
  89373. if (this._btnVR) {
  89374. this._btnVR.addEventListener("click", function () {
  89375. if (!_this.isInVRMode) {
  89376. _this.enterVR();
  89377. }
  89378. else {
  89379. _this.exitVR();
  89380. }
  89381. });
  89382. }
  89383. // Window events
  89384. window.addEventListener("resize", this._onResize);
  89385. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  89386. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  89387. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  89388. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  89389. // Display vr button when headset is connected
  89390. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  89391. this.displayVRButton();
  89392. }
  89393. else {
  89394. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  89395. if (e.vrDisplay) {
  89396. _this.displayVRButton();
  89397. }
  89398. });
  89399. }
  89400. // Exiting VR mode using 'ESC' key on desktop
  89401. this._onKeyDown = function (event) {
  89402. if (event.keyCode === 27 && _this.isInVRMode) {
  89403. _this.exitVR();
  89404. }
  89405. };
  89406. document.addEventListener("keydown", this._onKeyDown);
  89407. // Exiting VR mode double tapping the touch screen
  89408. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  89409. if (_this.isInVRMode) {
  89410. _this.exitVR();
  89411. if (_this._fullscreenVRpresenting) {
  89412. _this._scene.getEngine().switchFullscreen(true);
  89413. }
  89414. }
  89415. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  89416. // Listen for WebVR display changes
  89417. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  89418. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  89419. this._onVRRequestPresentStart = function () {
  89420. _this._webVRrequesting = true;
  89421. _this.updateButtonVisibility();
  89422. };
  89423. this._onVRRequestPresentComplete = function (success) {
  89424. _this._webVRrequesting = false;
  89425. _this.updateButtonVisibility();
  89426. };
  89427. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  89428. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  89429. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  89430. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89431. scene.onDisposeObservable.add(function () {
  89432. _this.dispose();
  89433. });
  89434. // Gamepad connection events
  89435. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  89436. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  89437. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  89438. this.updateButtonVisibility();
  89439. //create easing functions
  89440. this._circleEase = new BABYLON.CircleEase();
  89441. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  89442. if (this.webVROptions.floorMeshes) {
  89443. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  89444. }
  89445. }
  89446. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  89447. /** Return this.onEnteringVRObservable
  89448. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  89449. */
  89450. get: function () {
  89451. return this.onEnteringVRObservable;
  89452. },
  89453. enumerable: true,
  89454. configurable: true
  89455. });
  89456. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  89457. /** Return this.onExitingVRObservable
  89458. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  89459. */
  89460. get: function () {
  89461. return this.onExitingVRObservable;
  89462. },
  89463. enumerable: true,
  89464. configurable: true
  89465. });
  89466. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  89467. /** Return this.onControllerMeshLoadedObservable
  89468. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  89469. */
  89470. get: function () {
  89471. return this.onControllerMeshLoadedObservable;
  89472. },
  89473. enumerable: true,
  89474. configurable: true
  89475. });
  89476. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  89477. /**
  89478. * The mesh used to display where the user is going to teleport.
  89479. */
  89480. get: function () {
  89481. return this._teleportationTarget;
  89482. },
  89483. /**
  89484. * Sets the mesh to be used to display where the user is going to teleport.
  89485. */
  89486. set: function (value) {
  89487. if (value) {
  89488. value.name = "teleportationTarget";
  89489. this._isDefaultTeleportationTarget = false;
  89490. this._teleportationTarget = value;
  89491. }
  89492. },
  89493. enumerable: true,
  89494. configurable: true
  89495. });
  89496. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  89497. /**
  89498. * The mesh used to display where the user is selecting,
  89499. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  89500. * See http://doc.babylonjs.com/resources/baking_transformations
  89501. */
  89502. get: function () {
  89503. return this._cameraGazer._gazeTracker;
  89504. },
  89505. set: function (value) {
  89506. if (value) {
  89507. this._cameraGazer._gazeTracker = value;
  89508. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  89509. this._cameraGazer._gazeTracker.isPickable = false;
  89510. this._cameraGazer._gazeTracker.isVisible = false;
  89511. this._cameraGazer._gazeTracker.name = "gazeTracker";
  89512. if (this.leftController) {
  89513. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  89514. }
  89515. if (this.rightController) {
  89516. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  89517. }
  89518. }
  89519. },
  89520. enumerable: true,
  89521. configurable: true
  89522. });
  89523. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  89524. /**
  89525. * If the ray of the gaze should be displayed.
  89526. */
  89527. get: function () {
  89528. return this._displayGaze;
  89529. },
  89530. /**
  89531. * Sets if the ray of the gaze should be displayed.
  89532. */
  89533. set: function (value) {
  89534. this._displayGaze = value;
  89535. if (!value) {
  89536. this._cameraGazer._gazeTracker.isVisible = false;
  89537. if (this.leftController) {
  89538. this.leftController._gazeTracker.isVisible = false;
  89539. }
  89540. if (this.rightController) {
  89541. this.rightController._gazeTracker.isVisible = false;
  89542. }
  89543. }
  89544. },
  89545. enumerable: true,
  89546. configurable: true
  89547. });
  89548. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  89549. /**
  89550. * If the ray of the LaserPointer should be displayed.
  89551. */
  89552. get: function () {
  89553. return this._displayLaserPointer;
  89554. },
  89555. /**
  89556. * Sets if the ray of the LaserPointer should be displayed.
  89557. */
  89558. set: function (value) {
  89559. this._displayLaserPointer = value;
  89560. if (!value) {
  89561. if (this.rightController) {
  89562. this.rightController._deactivatePointer();
  89563. this.rightController._gazeTracker.isVisible = false;
  89564. }
  89565. if (this.leftController) {
  89566. this.leftController._deactivatePointer();
  89567. this.leftController._gazeTracker.isVisible = false;
  89568. }
  89569. }
  89570. else {
  89571. if (this.rightController) {
  89572. this.rightController._activatePointer();
  89573. }
  89574. if (this.leftController) {
  89575. this.leftController._activatePointer();
  89576. }
  89577. }
  89578. },
  89579. enumerable: true,
  89580. configurable: true
  89581. });
  89582. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  89583. /**
  89584. * The deviceOrientationCamera used as the camera when not in VR.
  89585. */
  89586. get: function () {
  89587. return this._deviceOrientationCamera;
  89588. },
  89589. enumerable: true,
  89590. configurable: true
  89591. });
  89592. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  89593. /**
  89594. * Based on the current WebVR support, returns the current VR camera used.
  89595. */
  89596. get: function () {
  89597. if (this._webVRready) {
  89598. return this._webVRCamera;
  89599. }
  89600. else {
  89601. return this._scene.activeCamera;
  89602. }
  89603. },
  89604. enumerable: true,
  89605. configurable: true
  89606. });
  89607. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  89608. /**
  89609. * The webVRCamera which is used when in VR.
  89610. */
  89611. get: function () {
  89612. return this._webVRCamera;
  89613. },
  89614. enumerable: true,
  89615. configurable: true
  89616. });
  89617. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  89618. /**
  89619. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  89620. */
  89621. get: function () {
  89622. return this._vrDeviceOrientationCamera;
  89623. },
  89624. enumerable: true,
  89625. configurable: true
  89626. });
  89627. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  89628. get: function () {
  89629. var result = this._cameraGazer._teleportationRequestInitiated
  89630. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  89631. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  89632. return result;
  89633. },
  89634. enumerable: true,
  89635. configurable: true
  89636. });
  89637. // Raised when one of the controller has loaded successfully its associated default mesh
  89638. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  89639. if (this.leftController && this.leftController.webVRController == webVRController) {
  89640. if (webVRController.mesh) {
  89641. this.leftController._setLaserPointerParent(webVRController.mesh);
  89642. }
  89643. }
  89644. if (this.rightController && this.rightController.webVRController == webVRController) {
  89645. if (webVRController.mesh) {
  89646. this.rightController._setLaserPointerParent(webVRController.mesh);
  89647. }
  89648. }
  89649. try {
  89650. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  89651. }
  89652. catch (err) {
  89653. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  89654. }
  89655. };
  89656. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  89657. /**
  89658. * Gets a value indicating if we are currently in VR mode.
  89659. */
  89660. get: function () {
  89661. return this._webVRpresenting || this._fullscreenVRpresenting;
  89662. },
  89663. enumerable: true,
  89664. configurable: true
  89665. });
  89666. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  89667. var vrDisplay = this._scene.getEngine().getVRDevice();
  89668. if (vrDisplay) {
  89669. var wasPresenting = this._webVRpresenting;
  89670. // A VR display is connected
  89671. this._webVRpresenting = vrDisplay.isPresenting;
  89672. if (wasPresenting && !this._webVRpresenting)
  89673. this.exitVR();
  89674. }
  89675. else {
  89676. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  89677. }
  89678. this.updateButtonVisibility();
  89679. };
  89680. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  89681. this._webVRsupported = eventArgs.vrSupported;
  89682. this._webVRready = !!eventArgs.vrDisplay;
  89683. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  89684. this.updateButtonVisibility();
  89685. };
  89686. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  89687. if (this._canvas && !this._useCustomVRButton) {
  89688. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  89689. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  89690. }
  89691. };
  89692. VRExperienceHelper.prototype.displayVRButton = function () {
  89693. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  89694. document.body.appendChild(this._btnVR);
  89695. this._btnVRDisplayed = true;
  89696. }
  89697. };
  89698. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  89699. if (!this._btnVR || this._useCustomVRButton) {
  89700. return;
  89701. }
  89702. this._btnVR.className = "babylonVRicon";
  89703. if (this.isInVRMode) {
  89704. this._btnVR.className += " vrdisplaypresenting";
  89705. }
  89706. else {
  89707. if (this._webVRready)
  89708. this._btnVR.className += " vrdisplayready";
  89709. if (this._webVRsupported)
  89710. this._btnVR.className += " vrdisplaysupported";
  89711. if (this._webVRrequesting)
  89712. this._btnVR.className += " vrdisplayrequesting";
  89713. }
  89714. };
  89715. /**
  89716. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  89717. * Otherwise, will use the fullscreen API.
  89718. */
  89719. VRExperienceHelper.prototype.enterVR = function () {
  89720. if (this.onEnteringVRObservable) {
  89721. try {
  89722. this.onEnteringVRObservable.notifyObservers(this);
  89723. }
  89724. catch (err) {
  89725. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  89726. }
  89727. }
  89728. if (this._scene.activeCamera) {
  89729. this._position = this._scene.activeCamera.position.clone();
  89730. // make sure that we return to the last active camera
  89731. this._existingCamera = this._scene.activeCamera;
  89732. }
  89733. if (this._webVRrequesting)
  89734. return;
  89735. // If WebVR is supported and a headset is connected
  89736. if (this._webVRready) {
  89737. if (!this._webVRpresenting) {
  89738. this._webVRCamera.position = this._position;
  89739. this._scene.activeCamera = this._webVRCamera;
  89740. }
  89741. }
  89742. else if (this._vrDeviceOrientationCamera) {
  89743. this._vrDeviceOrientationCamera.position = this._position;
  89744. if (this._scene.activeCamera) {
  89745. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  89746. }
  89747. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  89748. this._scene.getEngine().switchFullscreen(true);
  89749. this.updateButtonVisibility();
  89750. }
  89751. if (this._scene.activeCamera && this._canvas) {
  89752. this._scene.activeCamera.attachControl(this._canvas);
  89753. }
  89754. if (this._interactionsEnabled) {
  89755. this._scene.registerBeforeRender(this.beforeRender);
  89756. }
  89757. };
  89758. /**
  89759. * Attempt to exit VR, or fullscreen.
  89760. */
  89761. VRExperienceHelper.prototype.exitVR = function () {
  89762. if (this.onExitingVRObservable) {
  89763. try {
  89764. this.onExitingVRObservable.notifyObservers(this);
  89765. }
  89766. catch (err) {
  89767. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  89768. }
  89769. }
  89770. if (this._webVRpresenting) {
  89771. this._scene.getEngine().disableVR();
  89772. }
  89773. if (this._scene.activeCamera) {
  89774. this._position = this._scene.activeCamera.position.clone();
  89775. }
  89776. if (this._deviceOrientationCamera) {
  89777. this._deviceOrientationCamera.position = this._position;
  89778. this._scene.activeCamera = this._deviceOrientationCamera;
  89779. if (this._canvas) {
  89780. this._scene.activeCamera.attachControl(this._canvas);
  89781. }
  89782. }
  89783. else if (this._existingCamera) {
  89784. this._existingCamera.position = this._position;
  89785. this._scene.activeCamera = this._existingCamera;
  89786. }
  89787. this.updateButtonVisibility();
  89788. if (this._interactionsEnabled) {
  89789. this._scene.unregisterBeforeRender(this.beforeRender);
  89790. }
  89791. // resize to update width and height when exiting vr exits fullscreen
  89792. this._scene.getEngine().resize();
  89793. };
  89794. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  89795. /**
  89796. * The position of the vr experience helper.
  89797. */
  89798. get: function () {
  89799. return this._position;
  89800. },
  89801. /**
  89802. * Sets the position of the vr experience helper.
  89803. */
  89804. set: function (value) {
  89805. this._position = value;
  89806. if (this._scene.activeCamera) {
  89807. this._scene.activeCamera.position = value;
  89808. }
  89809. },
  89810. enumerable: true,
  89811. configurable: true
  89812. });
  89813. /**
  89814. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  89815. */
  89816. VRExperienceHelper.prototype.enableInteractions = function () {
  89817. var _this = this;
  89818. if (!this._interactionsEnabled) {
  89819. this._interactionsRequested = true;
  89820. if (this.leftController) {
  89821. this._enableInteractionOnController(this.leftController);
  89822. }
  89823. if (this.rightController) {
  89824. this._enableInteractionOnController(this.rightController);
  89825. }
  89826. this.raySelectionPredicate = function (mesh) {
  89827. return mesh.isVisible;
  89828. };
  89829. this.meshSelectionPredicate = function (mesh) {
  89830. return true;
  89831. };
  89832. this._raySelectionPredicate = function (mesh) {
  89833. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  89834. && mesh.name.indexOf("teleportationTarget") === -1
  89835. && mesh.name.indexOf("torusTeleportation") === -1
  89836. && mesh.name.indexOf("laserPointer") === -1)) {
  89837. return _this.raySelectionPredicate(mesh);
  89838. }
  89839. return false;
  89840. };
  89841. this._interactionsEnabled = true;
  89842. }
  89843. };
  89844. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  89845. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  89846. if (this._floorMeshesCollection[i].id === mesh.id) {
  89847. return true;
  89848. }
  89849. }
  89850. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  89851. return true;
  89852. }
  89853. return false;
  89854. };
  89855. /**
  89856. * Adds a floor mesh to be used for teleportation.
  89857. * @param floorMesh the mesh to be used for teleportation.
  89858. */
  89859. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  89860. if (!this._floorMeshesCollection) {
  89861. return;
  89862. }
  89863. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  89864. return;
  89865. }
  89866. this._floorMeshesCollection.push(floorMesh);
  89867. };
  89868. /**
  89869. * Removes a floor mesh from being used for teleportation.
  89870. * @param floorMesh the mesh to be removed.
  89871. */
  89872. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  89873. if (!this._floorMeshesCollection) {
  89874. return;
  89875. }
  89876. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  89877. if (meshIndex !== -1) {
  89878. this._floorMeshesCollection.splice(meshIndex, 1);
  89879. }
  89880. };
  89881. /**
  89882. * Enables interactions and teleportation using the VR controllers and gaze.
  89883. * @param vrTeleportationOptions options to modify teleportation behavior.
  89884. */
  89885. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  89886. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  89887. if (!this._teleportationInitialized) {
  89888. this._teleportationRequested = true;
  89889. this.enableInteractions();
  89890. if (vrTeleportationOptions.floorMeshName) {
  89891. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  89892. }
  89893. if (vrTeleportationOptions.floorMeshes) {
  89894. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  89895. }
  89896. if (this.leftController != null) {
  89897. this._enableTeleportationOnController(this.leftController);
  89898. }
  89899. if (this.rightController != null) {
  89900. this._enableTeleportationOnController(this.rightController);
  89901. }
  89902. // Creates an image processing post process for the vignette not relying
  89903. // on the main scene configuration for image processing to reduce setup and spaces
  89904. // (gamma/linear) conflicts.
  89905. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  89906. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  89907. imageProcessingConfiguration.vignetteEnabled = true;
  89908. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  89909. this._webVRCamera.detachPostProcess(this._postProcessMove);
  89910. this._teleportationInitialized = true;
  89911. if (this._isDefaultTeleportationTarget) {
  89912. this._createTeleportationCircles();
  89913. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  89914. }
  89915. }
  89916. };
  89917. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  89918. var _this = this;
  89919. var controllerMesh = controller.webVRController.mesh;
  89920. if (controllerMesh) {
  89921. controller._interactionsEnabled = true;
  89922. controller._activatePointer();
  89923. if (this.webVROptions.laserToggle) {
  89924. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  89925. // Enabling / disabling laserPointer
  89926. if (_this._displayLaserPointer && stateObject.value === 1) {
  89927. if (controller._activePointer) {
  89928. controller._deactivatePointer();
  89929. }
  89930. else {
  89931. controller._activatePointer();
  89932. }
  89933. if (_this.displayGaze) {
  89934. controller._gazeTracker.isVisible = controller._activePointer;
  89935. }
  89936. }
  89937. });
  89938. }
  89939. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  89940. if (!controller._pointerDownOnMeshAsked) {
  89941. if (stateObject.value > _this._padSensibilityUp) {
  89942. controller._selectionPointerDown();
  89943. }
  89944. }
  89945. else if (stateObject.value < _this._padSensibilityDown) {
  89946. controller._selectionPointerUp();
  89947. }
  89948. });
  89949. }
  89950. };
  89951. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  89952. // Dont teleport if another gaze already requested teleportation
  89953. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  89954. return;
  89955. }
  89956. if (!gazer._teleportationRequestInitiated) {
  89957. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  89958. gazer._activatePointer();
  89959. gazer._teleportationRequestInitiated = true;
  89960. }
  89961. }
  89962. else {
  89963. // Listening to the proper controller values changes to confirm teleportation
  89964. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  89965. if (this._teleportActive) {
  89966. this._teleportCamera(this._haloCenter);
  89967. }
  89968. gazer._teleportationRequestInitiated = false;
  89969. }
  89970. }
  89971. };
  89972. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  89973. // Only rotate when user is not currently selecting a teleportation location
  89974. if (gazer._teleportationRequestInitiated) {
  89975. return;
  89976. }
  89977. if (!gazer._rotationLeftAsked) {
  89978. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  89979. gazer._rotationLeftAsked = true;
  89980. if (this._rotationAllowed) {
  89981. this._rotateCamera(false);
  89982. }
  89983. }
  89984. }
  89985. else {
  89986. if (stateObject.x > -this._padSensibilityDown) {
  89987. gazer._rotationLeftAsked = false;
  89988. }
  89989. }
  89990. if (!gazer._rotationRightAsked) {
  89991. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  89992. gazer._rotationRightAsked = true;
  89993. if (this._rotationAllowed) {
  89994. this._rotateCamera(true);
  89995. }
  89996. }
  89997. }
  89998. else {
  89999. if (stateObject.x < this._padSensibilityDown) {
  90000. gazer._rotationRightAsked = false;
  90001. }
  90002. }
  90003. };
  90004. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  90005. // Only teleport backwards when user is not currently selecting a teleportation location
  90006. if (gazer._teleportationRequestInitiated) {
  90007. return;
  90008. }
  90009. // Teleport backwards
  90010. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  90011. if (!gazer._teleportationBackRequestInitiated) {
  90012. if (!this.currentVRCamera) {
  90013. return;
  90014. }
  90015. // Get rotation and position of the current camera
  90016. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  90017. var position = this.currentVRCamera.position;
  90018. // If the camera has device position, use that instead
  90019. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  90020. rotation = this.currentVRCamera.deviceRotationQuaternion;
  90021. position = this.currentVRCamera.devicePosition;
  90022. }
  90023. // Get matrix with only the y rotation of the device rotation
  90024. rotation.toEulerAnglesToRef(this._workingVector);
  90025. this._workingVector.z = 0;
  90026. this._workingVector.x = 0;
  90027. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  90028. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  90029. // Rotate backwards ray by device rotation to cast at the ground behind the user
  90030. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  90031. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  90032. var ray = new BABYLON.Ray(position, this._workingVector);
  90033. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90034. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  90035. this._teleportCamera(hit.pickedPoint);
  90036. }
  90037. gazer._teleportationBackRequestInitiated = true;
  90038. }
  90039. }
  90040. else {
  90041. gazer._teleportationBackRequestInitiated = false;
  90042. }
  90043. };
  90044. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  90045. var _this = this;
  90046. var controllerMesh = controller.webVRController.mesh;
  90047. if (controllerMesh) {
  90048. if (!controller._interactionsEnabled) {
  90049. this._enableInteractionOnController(controller);
  90050. }
  90051. controller._interactionsEnabled = true;
  90052. controller._teleportationEnabled = true;
  90053. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90054. controller._dpadPressed = false;
  90055. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  90056. controller._dpadPressed = stateObject.pressed;
  90057. if (!controller._dpadPressed) {
  90058. controller._rotationLeftAsked = false;
  90059. controller._rotationRightAsked = false;
  90060. controller._teleportationBackRequestInitiated = false;
  90061. }
  90062. });
  90063. }
  90064. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  90065. if (_this.teleportationEnabled) {
  90066. _this._checkTeleportBackwards(stateObject, controller);
  90067. _this._checkTeleportWithRay(stateObject, controller);
  90068. }
  90069. _this._checkRotate(stateObject, controller);
  90070. });
  90071. }
  90072. };
  90073. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  90074. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  90075. this._teleportationTarget.isPickable = false;
  90076. var length = 512;
  90077. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  90078. dynamicTexture.hasAlpha = true;
  90079. var context = dynamicTexture.getContext();
  90080. var centerX = length / 2;
  90081. var centerY = length / 2;
  90082. var radius = 200;
  90083. context.beginPath();
  90084. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  90085. context.fillStyle = this._teleportationFillColor;
  90086. context.fill();
  90087. context.lineWidth = 10;
  90088. context.strokeStyle = this._teleportationBorderColor;
  90089. context.stroke();
  90090. context.closePath();
  90091. dynamicTexture.update();
  90092. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  90093. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  90094. this._teleportationTarget.material = teleportationCircleMaterial;
  90095. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  90096. torus.isPickable = false;
  90097. torus.parent = this._teleportationTarget;
  90098. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  90099. var keys = [];
  90100. keys.push({
  90101. frame: 0,
  90102. value: 0
  90103. });
  90104. keys.push({
  90105. frame: 30,
  90106. value: 0.4
  90107. });
  90108. keys.push({
  90109. frame: 60,
  90110. value: 0
  90111. });
  90112. animationInnerCircle.setKeys(keys);
  90113. var easingFunction = new BABYLON.SineEase();
  90114. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  90115. animationInnerCircle.setEasingFunction(easingFunction);
  90116. torus.animations = [];
  90117. torus.animations.push(animationInnerCircle);
  90118. this._scene.beginAnimation(torus, 0, 60, true);
  90119. this._hideTeleportationTarget();
  90120. };
  90121. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  90122. this._teleportActive = true;
  90123. if (this._teleportationInitialized) {
  90124. this._teleportationTarget.isVisible = true;
  90125. if (this._isDefaultTeleportationTarget) {
  90126. this._teleportationTarget.getChildren()[0].isVisible = true;
  90127. }
  90128. }
  90129. };
  90130. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  90131. this._teleportActive = false;
  90132. if (this._teleportationInitialized) {
  90133. this._teleportationTarget.isVisible = false;
  90134. if (this._isDefaultTeleportationTarget) {
  90135. this._teleportationTarget.getChildren()[0].isVisible = false;
  90136. }
  90137. }
  90138. };
  90139. VRExperienceHelper.prototype._rotateCamera = function (right) {
  90140. var _this = this;
  90141. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90142. return;
  90143. }
  90144. if (right) {
  90145. this._rotationAngle++;
  90146. }
  90147. else {
  90148. this._rotationAngle--;
  90149. }
  90150. this.currentVRCamera.animations = [];
  90151. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  90152. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90153. var animationRotationKeys = [];
  90154. animationRotationKeys.push({
  90155. frame: 0,
  90156. value: this.currentVRCamera.rotationQuaternion
  90157. });
  90158. animationRotationKeys.push({
  90159. frame: 6,
  90160. value: target
  90161. });
  90162. animationRotation.setKeys(animationRotationKeys);
  90163. animationRotation.setEasingFunction(this._circleEase);
  90164. this.currentVRCamera.animations.push(animationRotation);
  90165. this._postProcessMove.animations = [];
  90166. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90167. var vignetteWeightKeys = [];
  90168. vignetteWeightKeys.push({
  90169. frame: 0,
  90170. value: 0
  90171. });
  90172. vignetteWeightKeys.push({
  90173. frame: 3,
  90174. value: 4
  90175. });
  90176. vignetteWeightKeys.push({
  90177. frame: 6,
  90178. value: 0
  90179. });
  90180. animationPP.setKeys(vignetteWeightKeys);
  90181. animationPP.setEasingFunction(this._circleEase);
  90182. this._postProcessMove.animations.push(animationPP);
  90183. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90184. var vignetteStretchKeys = [];
  90185. vignetteStretchKeys.push({
  90186. frame: 0,
  90187. value: 0
  90188. });
  90189. vignetteStretchKeys.push({
  90190. frame: 3,
  90191. value: 10
  90192. });
  90193. vignetteStretchKeys.push({
  90194. frame: 6,
  90195. value: 0
  90196. });
  90197. animationPP2.setKeys(vignetteStretchKeys);
  90198. animationPP2.setEasingFunction(this._circleEase);
  90199. this._postProcessMove.animations.push(animationPP2);
  90200. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90201. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90202. this._postProcessMove.samples = 4;
  90203. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90204. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  90205. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90206. });
  90207. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  90208. };
  90209. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  90210. if (hit.pickedPoint) {
  90211. if (gazer._teleportationRequestInitiated) {
  90212. this._displayTeleportationTarget();
  90213. this._haloCenter.copyFrom(hit.pickedPoint);
  90214. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  90215. }
  90216. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  90217. if (pickNormal) {
  90218. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90219. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90220. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  90221. }
  90222. this._teleportationTarget.position.y += 0.1;
  90223. }
  90224. };
  90225. VRExperienceHelper.prototype._teleportCamera = function (location) {
  90226. var _this = this;
  90227. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90228. return;
  90229. }
  90230. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  90231. // offset of the headset from the anchor.
  90232. if (this.webVRCamera.leftCamera) {
  90233. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  90234. this._workingVector.subtractInPlace(this.webVRCamera.position);
  90235. location.subtractToRef(this._workingVector, this._workingVector);
  90236. }
  90237. else {
  90238. this._workingVector.copyFrom(location);
  90239. }
  90240. // Add height to account for user's height offset
  90241. if (this.isInVRMode) {
  90242. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  90243. }
  90244. else {
  90245. this._workingVector.y += this._defaultHeight;
  90246. }
  90247. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  90248. // Create animation from the camera's position to the new location
  90249. this.currentVRCamera.animations = [];
  90250. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90251. var animationCameraTeleportationKeys = [{
  90252. frame: 0,
  90253. value: this.currentVRCamera.position
  90254. },
  90255. {
  90256. frame: 11,
  90257. value: this._workingVector
  90258. }
  90259. ];
  90260. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  90261. animationCameraTeleportation.setEasingFunction(this._circleEase);
  90262. this.currentVRCamera.animations.push(animationCameraTeleportation);
  90263. this._postProcessMove.animations = [];
  90264. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90265. var vignetteWeightKeys = [];
  90266. vignetteWeightKeys.push({
  90267. frame: 0,
  90268. value: 0
  90269. });
  90270. vignetteWeightKeys.push({
  90271. frame: 5,
  90272. value: 8
  90273. });
  90274. vignetteWeightKeys.push({
  90275. frame: 11,
  90276. value: 0
  90277. });
  90278. animationPP.setKeys(vignetteWeightKeys);
  90279. this._postProcessMove.animations.push(animationPP);
  90280. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  90281. var vignetteStretchKeys = [];
  90282. vignetteStretchKeys.push({
  90283. frame: 0,
  90284. value: 0
  90285. });
  90286. vignetteStretchKeys.push({
  90287. frame: 5,
  90288. value: 10
  90289. });
  90290. vignetteStretchKeys.push({
  90291. frame: 11,
  90292. value: 0
  90293. });
  90294. animationPP2.setKeys(vignetteStretchKeys);
  90295. this._postProcessMove.animations.push(animationPP2);
  90296. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  90297. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  90298. this._webVRCamera.attachPostProcess(this._postProcessMove);
  90299. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  90300. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  90301. });
  90302. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  90303. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  90304. });
  90305. this._hideTeleportationTarget();
  90306. };
  90307. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  90308. if (normal) {
  90309. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  90310. if (angle < Math.PI / 2) {
  90311. normal.scaleInPlace(-1);
  90312. }
  90313. }
  90314. return normal;
  90315. };
  90316. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  90317. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  90318. return;
  90319. }
  90320. var ray = gazer._getForwardRay(this._rayLength);
  90321. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  90322. if (hit) {
  90323. // Populate the contrllers mesh that can be used for drag/drop
  90324. if (gazer._laserPointer) {
  90325. hit.originMesh = gazer._laserPointer.parent;
  90326. }
  90327. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  90328. }
  90329. gazer._currentHit = hit;
  90330. // Moving the gazeTracker on the mesh face targetted
  90331. if (hit && hit.pickedPoint) {
  90332. if (this._displayGaze) {
  90333. var multiplier = 1;
  90334. gazer._gazeTracker.isVisible = true;
  90335. if (gazer._isActionableMesh) {
  90336. multiplier = 3;
  90337. }
  90338. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  90339. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  90340. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  90341. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  90342. // To avoid z-fighting
  90343. var deltaFighting = 0.002;
  90344. if (pickNormal) {
  90345. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  90346. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  90347. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  90348. }
  90349. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  90350. if (gazer._gazeTracker.position.x < 0) {
  90351. gazer._gazeTracker.position.x += deltaFighting;
  90352. }
  90353. else {
  90354. gazer._gazeTracker.position.x -= deltaFighting;
  90355. }
  90356. if (gazer._gazeTracker.position.y < 0) {
  90357. gazer._gazeTracker.position.y += deltaFighting;
  90358. }
  90359. else {
  90360. gazer._gazeTracker.position.y -= deltaFighting;
  90361. }
  90362. if (gazer._gazeTracker.position.z < 0) {
  90363. gazer._gazeTracker.position.z += deltaFighting;
  90364. }
  90365. else {
  90366. gazer._gazeTracker.position.z -= deltaFighting;
  90367. }
  90368. }
  90369. // Changing the size of the laser pointer based on the distance from the targetted point
  90370. gazer._updatePointerDistance(hit.distance);
  90371. }
  90372. else {
  90373. gazer._updatePointerDistance();
  90374. gazer._gazeTracker.isVisible = false;
  90375. }
  90376. if (hit && hit.pickedMesh) {
  90377. // The object selected is the floor, we're in a teleportation scenario
  90378. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  90379. // Moving the teleportation area to this targetted point
  90380. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  90381. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  90382. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  90383. }
  90384. gazer._currentMeshSelected = null;
  90385. if (gazer._teleportationRequestInitiated) {
  90386. this._moveTeleportationSelectorTo(hit, gazer, ray);
  90387. }
  90388. return;
  90389. }
  90390. // If not, we're in a selection scenario
  90391. //this._teleportationAllowed = false;
  90392. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  90393. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  90394. this.onNewMeshPicked.notifyObservers(hit);
  90395. gazer._currentMeshSelected = hit.pickedMesh;
  90396. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  90397. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  90398. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  90399. gazer._isActionableMesh = true;
  90400. }
  90401. else {
  90402. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90403. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90404. gazer._isActionableMesh = false;
  90405. }
  90406. try {
  90407. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  90408. }
  90409. catch (err) {
  90410. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  90411. }
  90412. }
  90413. else {
  90414. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  90415. gazer._currentMeshSelected = null;
  90416. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90417. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90418. }
  90419. }
  90420. }
  90421. else {
  90422. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  90423. gazer._currentMeshSelected = null;
  90424. //this._teleportationAllowed = false;
  90425. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90426. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  90427. }
  90428. };
  90429. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  90430. if (mesh) {
  90431. this.onSelectedMeshUnselected.notifyObservers(mesh);
  90432. }
  90433. };
  90434. /**
  90435. * Sets the color of the laser ray from the vr controllers.
  90436. * @param color new color for the ray.
  90437. */
  90438. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  90439. if (this.leftController) {
  90440. this.leftController._setLaserPointerColor(color);
  90441. }
  90442. if (this.rightController) {
  90443. this.rightController._setLaserPointerColor(color);
  90444. }
  90445. };
  90446. /**
  90447. * Sets the color of the ray from the vr headsets gaze.
  90448. * @param color new color for the ray.
  90449. */
  90450. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  90451. if (!this._cameraGazer._gazeTracker.material) {
  90452. return;
  90453. }
  90454. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  90455. if (this.leftController) {
  90456. this.leftController._gazeTracker.material.emissiveColor = color;
  90457. }
  90458. if (this.rightController) {
  90459. this.rightController._gazeTracker.material.emissiveColor = color;
  90460. }
  90461. };
  90462. /**
  90463. * Exits VR and disposes of the vr experience helper
  90464. */
  90465. VRExperienceHelper.prototype.dispose = function () {
  90466. if (this.isInVRMode) {
  90467. this.exitVR();
  90468. }
  90469. if (this._postProcessMove) {
  90470. this._postProcessMove.dispose();
  90471. }
  90472. if (this._webVRCamera) {
  90473. this._webVRCamera.dispose();
  90474. }
  90475. if (this._vrDeviceOrientationCamera) {
  90476. this._vrDeviceOrientationCamera.dispose();
  90477. }
  90478. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  90479. document.body.removeChild(this._btnVR);
  90480. }
  90481. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  90482. this._deviceOrientationCamera.dispose();
  90483. }
  90484. if (this._cameraGazer) {
  90485. this._cameraGazer.dispose();
  90486. }
  90487. if (this.leftController) {
  90488. this.leftController.dispose();
  90489. }
  90490. if (this.rightController) {
  90491. this.rightController.dispose();
  90492. }
  90493. if (this._teleportationTarget) {
  90494. this._teleportationTarget.dispose();
  90495. }
  90496. this._floorMeshesCollection = [];
  90497. document.removeEventListener("keydown", this._onKeyDown);
  90498. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90499. window.removeEventListener("resize", this._onResize);
  90500. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  90501. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  90502. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  90503. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  90504. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  90505. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  90506. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  90507. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  90508. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  90509. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  90510. this._scene.unregisterBeforeRender(this.beforeRender);
  90511. };
  90512. /**
  90513. * Gets the name of the VRExperienceHelper class
  90514. * @returns "VRExperienceHelper"
  90515. */
  90516. VRExperienceHelper.prototype.getClassName = function () {
  90517. return "VRExperienceHelper";
  90518. };
  90519. return VRExperienceHelper;
  90520. }());
  90521. BABYLON.VRExperienceHelper = VRExperienceHelper;
  90522. })(BABYLON || (BABYLON = {}));
  90523. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  90524. // Mainly based on these 2 articles :
  90525. // 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
  90526. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  90527. var BABYLON;
  90528. (function (BABYLON) {
  90529. /**
  90530. * Defines the potential axis of a Joystick
  90531. */
  90532. var JoystickAxis;
  90533. (function (JoystickAxis) {
  90534. /** X axis */
  90535. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  90536. /** Y axis */
  90537. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  90538. /** Z axis */
  90539. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  90540. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  90541. /**
  90542. * Class used to define virtual joystick (used in touch mode)
  90543. */
  90544. var VirtualJoystick = /** @class */ (function () {
  90545. /**
  90546. * Creates a new virtual joystick
  90547. * @param leftJoystick defines that the joystick is for left hand (false by default)
  90548. */
  90549. function VirtualJoystick(leftJoystick) {
  90550. var _this = this;
  90551. if (leftJoystick) {
  90552. this._leftJoystick = true;
  90553. }
  90554. else {
  90555. this._leftJoystick = false;
  90556. }
  90557. VirtualJoystick._globalJoystickIndex++;
  90558. // By default left & right arrow keys are moving the X
  90559. // and up & down keys are moving the Y
  90560. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  90561. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90562. this.reverseLeftRight = false;
  90563. this.reverseUpDown = false;
  90564. // collections of pointers
  90565. this._touches = new BABYLON.StringDictionary();
  90566. this.deltaPosition = BABYLON.Vector3.Zero();
  90567. this._joystickSensibility = 25;
  90568. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  90569. this._onResize = function (evt) {
  90570. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  90571. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  90572. if (VirtualJoystick.vjCanvas) {
  90573. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  90574. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  90575. }
  90576. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  90577. };
  90578. // injecting a canvas element on top of the canvas 3D game
  90579. if (!VirtualJoystick.vjCanvas) {
  90580. window.addEventListener("resize", this._onResize, false);
  90581. VirtualJoystick.vjCanvas = document.createElement("canvas");
  90582. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  90583. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  90584. VirtualJoystick.vjCanvas.width = window.innerWidth;
  90585. VirtualJoystick.vjCanvas.height = window.innerHeight;
  90586. VirtualJoystick.vjCanvas.style.width = "100%";
  90587. VirtualJoystick.vjCanvas.style.height = "100%";
  90588. VirtualJoystick.vjCanvas.style.position = "absolute";
  90589. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  90590. VirtualJoystick.vjCanvas.style.top = "0px";
  90591. VirtualJoystick.vjCanvas.style.left = "0px";
  90592. VirtualJoystick.vjCanvas.style.zIndex = "5";
  90593. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  90594. // Support for jQuery PEP polyfill
  90595. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  90596. var context = VirtualJoystick.vjCanvas.getContext('2d');
  90597. if (!context) {
  90598. throw new Error("Unable to create canvas for virtual joystick");
  90599. }
  90600. VirtualJoystick.vjCanvasContext = context;
  90601. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  90602. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90603. document.body.appendChild(VirtualJoystick.vjCanvas);
  90604. }
  90605. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  90606. this.pressed = false;
  90607. // default joystick color
  90608. this._joystickColor = "cyan";
  90609. this._joystickPointerID = -1;
  90610. // current joystick position
  90611. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  90612. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  90613. // origin joystick position
  90614. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  90615. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  90616. this._onPointerDownHandlerRef = function (evt) {
  90617. _this._onPointerDown(evt);
  90618. };
  90619. this._onPointerMoveHandlerRef = function (evt) {
  90620. _this._onPointerMove(evt);
  90621. };
  90622. this._onPointerUpHandlerRef = function (evt) {
  90623. _this._onPointerUp(evt);
  90624. };
  90625. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  90626. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  90627. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  90628. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  90629. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  90630. evt.preventDefault(); // Disables system menu
  90631. }, false);
  90632. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90633. }
  90634. /**
  90635. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  90636. * @param newJoystickSensibility defines the new sensibility
  90637. */
  90638. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  90639. this._joystickSensibility = newJoystickSensibility;
  90640. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  90641. };
  90642. VirtualJoystick.prototype._onPointerDown = function (e) {
  90643. var positionOnScreenCondition;
  90644. e.preventDefault();
  90645. if (this._leftJoystick === true) {
  90646. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  90647. }
  90648. else {
  90649. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  90650. }
  90651. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  90652. // First contact will be dedicated to the virtual joystick
  90653. this._joystickPointerID = e.pointerId;
  90654. this._joystickPointerStartPos.x = e.clientX;
  90655. this._joystickPointerStartPos.y = e.clientY;
  90656. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  90657. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  90658. this._deltaJoystickVector.x = 0;
  90659. this._deltaJoystickVector.y = 0;
  90660. this.pressed = true;
  90661. this._touches.add(e.pointerId.toString(), e);
  90662. }
  90663. else {
  90664. // You can only trigger the action buttons with a joystick declared
  90665. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  90666. this._action();
  90667. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  90668. }
  90669. }
  90670. };
  90671. VirtualJoystick.prototype._onPointerMove = function (e) {
  90672. // If the current pointer is the one associated to the joystick (first touch contact)
  90673. if (this._joystickPointerID == e.pointerId) {
  90674. this._joystickPointerPos.x = e.clientX;
  90675. this._joystickPointerPos.y = e.clientY;
  90676. this._deltaJoystickVector = this._joystickPointerPos.clone();
  90677. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  90678. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  90679. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  90680. switch (this._axisTargetedByLeftAndRight) {
  90681. case JoystickAxis.X:
  90682. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  90683. break;
  90684. case JoystickAxis.Y:
  90685. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  90686. break;
  90687. case JoystickAxis.Z:
  90688. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  90689. break;
  90690. }
  90691. var directionUpDown = this.reverseUpDown ? 1 : -1;
  90692. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  90693. switch (this._axisTargetedByUpAndDown) {
  90694. case JoystickAxis.X:
  90695. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  90696. break;
  90697. case JoystickAxis.Y:
  90698. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  90699. break;
  90700. case JoystickAxis.Z:
  90701. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  90702. break;
  90703. }
  90704. }
  90705. else {
  90706. var data = this._touches.get(e.pointerId.toString());
  90707. if (data) {
  90708. data.x = e.clientX;
  90709. data.y = e.clientY;
  90710. }
  90711. }
  90712. };
  90713. VirtualJoystick.prototype._onPointerUp = function (e) {
  90714. if (this._joystickPointerID == e.pointerId) {
  90715. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  90716. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  90717. this._joystickPointerID = -1;
  90718. this.pressed = false;
  90719. }
  90720. else {
  90721. var touch = this._touches.get(e.pointerId.toString());
  90722. if (touch) {
  90723. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90724. }
  90725. }
  90726. this._deltaJoystickVector.x = 0;
  90727. this._deltaJoystickVector.y = 0;
  90728. this._touches.remove(e.pointerId.toString());
  90729. };
  90730. /**
  90731. * Change the color of the virtual joystick
  90732. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  90733. */
  90734. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  90735. this._joystickColor = newColor;
  90736. };
  90737. /**
  90738. * Defines a callback to call when the joystick is touched
  90739. * @param action defines the callback
  90740. */
  90741. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  90742. this._action = action;
  90743. };
  90744. /**
  90745. * Defines which axis you'd like to control for left & right
  90746. * @param axis defines the axis to use
  90747. */
  90748. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  90749. switch (axis) {
  90750. case JoystickAxis.X:
  90751. case JoystickAxis.Y:
  90752. case JoystickAxis.Z:
  90753. this._axisTargetedByLeftAndRight = axis;
  90754. break;
  90755. default:
  90756. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  90757. break;
  90758. }
  90759. };
  90760. /**
  90761. * Defines which axis you'd like to control for up & down
  90762. * @param axis defines the axis to use
  90763. */
  90764. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  90765. switch (axis) {
  90766. case JoystickAxis.X:
  90767. case JoystickAxis.Y:
  90768. case JoystickAxis.Z:
  90769. this._axisTargetedByUpAndDown = axis;
  90770. break;
  90771. default:
  90772. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  90773. break;
  90774. }
  90775. };
  90776. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  90777. var _this = this;
  90778. if (this.pressed) {
  90779. this._touches.forEach(function (key, touch) {
  90780. if (touch.pointerId === _this._joystickPointerID) {
  90781. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  90782. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  90783. VirtualJoystick.vjCanvasContext.beginPath();
  90784. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90785. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90786. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  90787. VirtualJoystick.vjCanvasContext.stroke();
  90788. VirtualJoystick.vjCanvasContext.closePath();
  90789. VirtualJoystick.vjCanvasContext.beginPath();
  90790. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90791. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  90792. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  90793. VirtualJoystick.vjCanvasContext.stroke();
  90794. VirtualJoystick.vjCanvasContext.closePath();
  90795. VirtualJoystick.vjCanvasContext.beginPath();
  90796. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  90797. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  90798. VirtualJoystick.vjCanvasContext.stroke();
  90799. VirtualJoystick.vjCanvasContext.closePath();
  90800. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  90801. }
  90802. else {
  90803. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  90804. VirtualJoystick.vjCanvasContext.beginPath();
  90805. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  90806. VirtualJoystick.vjCanvasContext.beginPath();
  90807. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  90808. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  90809. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  90810. VirtualJoystick.vjCanvasContext.stroke();
  90811. VirtualJoystick.vjCanvasContext.closePath();
  90812. touch.prevX = touch.x;
  90813. touch.prevY = touch.y;
  90814. }
  90815. ;
  90816. });
  90817. }
  90818. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  90819. };
  90820. /**
  90821. * Release internal HTML canvas
  90822. */
  90823. VirtualJoystick.prototype.releaseCanvas = function () {
  90824. if (VirtualJoystick.vjCanvas) {
  90825. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  90826. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  90827. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  90828. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  90829. window.removeEventListener("resize", this._onResize);
  90830. document.body.removeChild(VirtualJoystick.vjCanvas);
  90831. VirtualJoystick.vjCanvas = null;
  90832. }
  90833. };
  90834. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  90835. VirtualJoystick._globalJoystickIndex = 0;
  90836. return VirtualJoystick;
  90837. }());
  90838. BABYLON.VirtualJoystick = VirtualJoystick;
  90839. })(BABYLON || (BABYLON = {}));
  90840. //# sourceMappingURL=babylon.virtualJoystick.js.map
  90841. var BABYLON;
  90842. (function (BABYLON) {
  90843. // We're mainly based on the logic defined into the FreeCamera code
  90844. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  90845. __extends(VirtualJoysticksCamera, _super);
  90846. function VirtualJoysticksCamera(name, position, scene) {
  90847. var _this = _super.call(this, name, position, scene) || this;
  90848. _this.inputs.addVirtualJoystick();
  90849. return _this;
  90850. }
  90851. VirtualJoysticksCamera.prototype.getClassName = function () {
  90852. return "VirtualJoysticksCamera";
  90853. };
  90854. return VirtualJoysticksCamera;
  90855. }(BABYLON.FreeCamera));
  90856. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  90857. })(BABYLON || (BABYLON = {}));
  90858. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  90859. var BABYLON;
  90860. (function (BABYLON) {
  90861. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  90862. function FreeCameraVirtualJoystickInput() {
  90863. }
  90864. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  90865. return this._leftjoystick;
  90866. };
  90867. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  90868. return this._rightjoystick;
  90869. };
  90870. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  90871. if (this._leftjoystick) {
  90872. var camera = this.camera;
  90873. var speed = camera._computeLocalCameraSpeed() * 50;
  90874. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  90875. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  90876. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  90877. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  90878. if (!this._leftjoystick.pressed) {
  90879. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  90880. }
  90881. if (!this._rightjoystick.pressed) {
  90882. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  90883. }
  90884. }
  90885. };
  90886. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  90887. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  90888. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  90889. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  90890. this._leftjoystick.setJoystickSensibility(0.15);
  90891. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  90892. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  90893. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  90894. this._rightjoystick.reverseUpDown = true;
  90895. this._rightjoystick.setJoystickSensibility(0.05);
  90896. this._rightjoystick.setJoystickColor("yellow");
  90897. };
  90898. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  90899. this._leftjoystick.releaseCanvas();
  90900. this._rightjoystick.releaseCanvas();
  90901. };
  90902. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  90903. return "FreeCameraVirtualJoystickInput";
  90904. };
  90905. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  90906. return "virtualJoystick";
  90907. };
  90908. return FreeCameraVirtualJoystickInput;
  90909. }());
  90910. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  90911. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  90912. })(BABYLON || (BABYLON = {}));
  90913. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  90914. var BABYLON;
  90915. (function (BABYLON) {
  90916. var SimplificationSettings = /** @class */ (function () {
  90917. function SimplificationSettings(quality, distance, optimizeMesh) {
  90918. this.quality = quality;
  90919. this.distance = distance;
  90920. this.optimizeMesh = optimizeMesh;
  90921. }
  90922. return SimplificationSettings;
  90923. }());
  90924. BABYLON.SimplificationSettings = SimplificationSettings;
  90925. var SimplificationQueue = /** @class */ (function () {
  90926. function SimplificationQueue() {
  90927. this.running = false;
  90928. this._simplificationArray = [];
  90929. }
  90930. SimplificationQueue.prototype.addTask = function (task) {
  90931. this._simplificationArray.push(task);
  90932. };
  90933. SimplificationQueue.prototype.executeNext = function () {
  90934. var task = this._simplificationArray.pop();
  90935. if (task) {
  90936. this.running = true;
  90937. this.runSimplification(task);
  90938. }
  90939. else {
  90940. this.running = false;
  90941. }
  90942. };
  90943. SimplificationQueue.prototype.runSimplification = function (task) {
  90944. var _this = this;
  90945. if (task.parallelProcessing) {
  90946. //parallel simplifier
  90947. task.settings.forEach(function (setting) {
  90948. var simplifier = _this.getSimplifier(task);
  90949. simplifier.simplify(setting, function (newMesh) {
  90950. task.mesh.addLODLevel(setting.distance, newMesh);
  90951. newMesh.isVisible = true;
  90952. //check if it is the last
  90953. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  90954. //all done, run the success callback.
  90955. task.successCallback();
  90956. }
  90957. _this.executeNext();
  90958. });
  90959. });
  90960. }
  90961. else {
  90962. //single simplifier.
  90963. var simplifier = this.getSimplifier(task);
  90964. var runDecimation = function (setting, callback) {
  90965. simplifier.simplify(setting, function (newMesh) {
  90966. task.mesh.addLODLevel(setting.distance, newMesh);
  90967. newMesh.isVisible = true;
  90968. //run the next quality level
  90969. callback();
  90970. });
  90971. };
  90972. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  90973. runDecimation(task.settings[loop.index], function () {
  90974. loop.executeNext();
  90975. });
  90976. }, function () {
  90977. //execution ended, run the success callback.
  90978. if (task.successCallback) {
  90979. task.successCallback();
  90980. }
  90981. _this.executeNext();
  90982. });
  90983. }
  90984. };
  90985. SimplificationQueue.prototype.getSimplifier = function (task) {
  90986. switch (task.simplificationType) {
  90987. case SimplificationType.QUADRATIC:
  90988. default:
  90989. return new QuadraticErrorSimplification(task.mesh);
  90990. }
  90991. };
  90992. return SimplificationQueue;
  90993. }());
  90994. BABYLON.SimplificationQueue = SimplificationQueue;
  90995. /**
  90996. * The implemented types of simplification
  90997. * At the moment only Quadratic Error Decimation is implemented
  90998. */
  90999. var SimplificationType;
  91000. (function (SimplificationType) {
  91001. /** Quadratic error decimation */
  91002. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  91003. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  91004. var DecimationTriangle = /** @class */ (function () {
  91005. function DecimationTriangle(vertices) {
  91006. this.vertices = vertices;
  91007. this.error = new Array(4);
  91008. this.deleted = false;
  91009. this.isDirty = false;
  91010. this.deletePending = false;
  91011. this.borderFactor = 0;
  91012. }
  91013. return DecimationTriangle;
  91014. }());
  91015. BABYLON.DecimationTriangle = DecimationTriangle;
  91016. var DecimationVertex = /** @class */ (function () {
  91017. function DecimationVertex(position, id) {
  91018. this.position = position;
  91019. this.id = id;
  91020. this.isBorder = true;
  91021. this.q = new QuadraticMatrix();
  91022. this.triangleCount = 0;
  91023. this.triangleStart = 0;
  91024. this.originalOffsets = [];
  91025. }
  91026. DecimationVertex.prototype.updatePosition = function (newPosition) {
  91027. this.position.copyFrom(newPosition);
  91028. };
  91029. return DecimationVertex;
  91030. }());
  91031. BABYLON.DecimationVertex = DecimationVertex;
  91032. var QuadraticMatrix = /** @class */ (function () {
  91033. function QuadraticMatrix(data) {
  91034. this.data = new Array(10);
  91035. for (var i = 0; i < 10; ++i) {
  91036. if (data && data[i]) {
  91037. this.data[i] = data[i];
  91038. }
  91039. else {
  91040. this.data[i] = 0;
  91041. }
  91042. }
  91043. }
  91044. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  91045. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  91046. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  91047. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  91048. return det;
  91049. };
  91050. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  91051. for (var i = 0; i < 10; ++i) {
  91052. this.data[i] += matrix.data[i];
  91053. }
  91054. };
  91055. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  91056. for (var i = 0; i < 10; ++i) {
  91057. this.data[i] += data[i];
  91058. }
  91059. };
  91060. QuadraticMatrix.prototype.add = function (matrix) {
  91061. var m = new QuadraticMatrix();
  91062. for (var i = 0; i < 10; ++i) {
  91063. m.data[i] = this.data[i] + matrix.data[i];
  91064. }
  91065. return m;
  91066. };
  91067. QuadraticMatrix.FromData = function (a, b, c, d) {
  91068. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  91069. };
  91070. //returning an array to avoid garbage collection
  91071. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  91072. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  91073. };
  91074. return QuadraticMatrix;
  91075. }());
  91076. BABYLON.QuadraticMatrix = QuadraticMatrix;
  91077. var Reference = /** @class */ (function () {
  91078. function Reference(vertexId, triangleId) {
  91079. this.vertexId = vertexId;
  91080. this.triangleId = triangleId;
  91081. }
  91082. return Reference;
  91083. }());
  91084. BABYLON.Reference = Reference;
  91085. /**
  91086. * An implementation of the Quadratic Error simplification algorithm.
  91087. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  91088. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  91089. * @author RaananW
  91090. */
  91091. var QuadraticErrorSimplification = /** @class */ (function () {
  91092. function QuadraticErrorSimplification(_mesh) {
  91093. this._mesh = _mesh;
  91094. this.syncIterations = 5000;
  91095. this.aggressiveness = 7;
  91096. this.decimationIterations = 100;
  91097. this.boundingBoxEpsilon = BABYLON.Epsilon;
  91098. }
  91099. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  91100. var _this = this;
  91101. this.initDecimatedMesh();
  91102. //iterating through the submeshes array, one after the other.
  91103. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  91104. _this.initWithMesh(loop.index, function () {
  91105. _this.runDecimation(settings, loop.index, function () {
  91106. loop.executeNext();
  91107. });
  91108. }, settings.optimizeMesh);
  91109. }, function () {
  91110. setTimeout(function () {
  91111. successCallback(_this._reconstructedMesh);
  91112. }, 0);
  91113. });
  91114. };
  91115. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  91116. var _this = this;
  91117. var targetCount = ~~(this.triangles.length * settings.quality);
  91118. var deletedTriangles = 0;
  91119. var triangleCount = this.triangles.length;
  91120. var iterationFunction = function (iteration, callback) {
  91121. setTimeout(function () {
  91122. if (iteration % 5 === 0) {
  91123. _this.updateMesh(iteration === 0);
  91124. }
  91125. for (var i = 0; i < _this.triangles.length; ++i) {
  91126. _this.triangles[i].isDirty = false;
  91127. }
  91128. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  91129. var trianglesIterator = function (i) {
  91130. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  91131. var t = _this.triangles[tIdx];
  91132. if (!t)
  91133. return;
  91134. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  91135. return;
  91136. }
  91137. for (var j = 0; j < 3; ++j) {
  91138. if (t.error[j] < threshold) {
  91139. var deleted0 = [];
  91140. var deleted1 = [];
  91141. var v0 = t.vertices[j];
  91142. var v1 = t.vertices[(j + 1) % 3];
  91143. if (v0.isBorder || v1.isBorder)
  91144. continue;
  91145. var p = BABYLON.Vector3.Zero();
  91146. var n = BABYLON.Vector3.Zero();
  91147. var uv = BABYLON.Vector2.Zero();
  91148. var color = new BABYLON.Color4(0, 0, 0, 1);
  91149. _this.calculateError(v0, v1, p, n, uv, color);
  91150. var delTr = new Array();
  91151. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  91152. continue;
  91153. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  91154. continue;
  91155. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  91156. continue;
  91157. var uniqueArray = new Array();
  91158. delTr.forEach(function (deletedT) {
  91159. if (uniqueArray.indexOf(deletedT) === -1) {
  91160. deletedT.deletePending = true;
  91161. uniqueArray.push(deletedT);
  91162. }
  91163. });
  91164. if (uniqueArray.length % 2 !== 0) {
  91165. continue;
  91166. }
  91167. v0.q = v1.q.add(v0.q);
  91168. v0.updatePosition(p);
  91169. var tStart = _this.references.length;
  91170. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  91171. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  91172. var tCount = _this.references.length - tStart;
  91173. if (tCount <= v0.triangleCount) {
  91174. if (tCount) {
  91175. for (var c = 0; c < tCount; c++) {
  91176. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  91177. }
  91178. }
  91179. }
  91180. else {
  91181. v0.triangleStart = tStart;
  91182. }
  91183. v0.triangleCount = tCount;
  91184. break;
  91185. }
  91186. }
  91187. };
  91188. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  91189. }, 0);
  91190. };
  91191. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  91192. if (triangleCount - deletedTriangles <= targetCount)
  91193. loop.breakLoop();
  91194. else {
  91195. iterationFunction(loop.index, function () {
  91196. loop.executeNext();
  91197. });
  91198. }
  91199. }, function () {
  91200. setTimeout(function () {
  91201. //reconstruct this part of the mesh
  91202. _this.reconstructMesh(submeshIndex);
  91203. successCallback();
  91204. }, 0);
  91205. });
  91206. };
  91207. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  91208. var _this = this;
  91209. this.vertices = [];
  91210. this.triangles = [];
  91211. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91212. var indices = this._mesh.getIndices();
  91213. var submesh = this._mesh.subMeshes[submeshIndex];
  91214. var findInVertices = function (positionToSearch) {
  91215. if (optimizeMesh) {
  91216. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  91217. if (_this.vertices[ii].position.equals(positionToSearch)) {
  91218. return _this.vertices[ii];
  91219. }
  91220. }
  91221. }
  91222. return null;
  91223. };
  91224. var vertexReferences = [];
  91225. var vertexInit = function (i) {
  91226. if (!positionData) {
  91227. return;
  91228. }
  91229. var offset = i + submesh.verticesStart;
  91230. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  91231. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  91232. vertex.originalOffsets.push(offset);
  91233. if (vertex.id === _this.vertices.length) {
  91234. _this.vertices.push(vertex);
  91235. }
  91236. vertexReferences.push(vertex.id);
  91237. };
  91238. //var totalVertices = mesh.getTotalVertices();
  91239. var totalVertices = submesh.verticesCount;
  91240. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  91241. var indicesInit = function (i) {
  91242. if (!indices) {
  91243. return;
  91244. }
  91245. var offset = (submesh.indexStart / 3) + i;
  91246. var pos = (offset * 3);
  91247. var i0 = indices[pos + 0];
  91248. var i1 = indices[pos + 1];
  91249. var i2 = indices[pos + 2];
  91250. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  91251. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  91252. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  91253. var triangle = new DecimationTriangle([v0, v1, v2]);
  91254. triangle.originalOffset = pos;
  91255. _this.triangles.push(triangle);
  91256. };
  91257. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  91258. _this.init(callback);
  91259. });
  91260. });
  91261. };
  91262. QuadraticErrorSimplification.prototype.init = function (callback) {
  91263. var _this = this;
  91264. var triangleInit1 = function (i) {
  91265. var t = _this.triangles[i];
  91266. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  91267. for (var j = 0; j < 3; j++) {
  91268. 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))));
  91269. }
  91270. };
  91271. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  91272. var triangleInit2 = function (i) {
  91273. var t = _this.triangles[i];
  91274. for (var j = 0; j < 3; ++j) {
  91275. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  91276. }
  91277. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  91278. };
  91279. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  91280. callback();
  91281. });
  91282. });
  91283. };
  91284. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  91285. var newTriangles = [];
  91286. var i;
  91287. for (i = 0; i < this.vertices.length; ++i) {
  91288. this.vertices[i].triangleCount = 0;
  91289. }
  91290. var t;
  91291. var j;
  91292. for (i = 0; i < this.triangles.length; ++i) {
  91293. if (!this.triangles[i].deleted) {
  91294. t = this.triangles[i];
  91295. for (j = 0; j < 3; ++j) {
  91296. t.vertices[j].triangleCount = 1;
  91297. }
  91298. newTriangles.push(t);
  91299. }
  91300. }
  91301. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  91302. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  91303. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  91304. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  91305. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  91306. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  91307. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  91308. var vertexCount = 0;
  91309. for (i = 0; i < this.vertices.length; ++i) {
  91310. var vertex = this.vertices[i];
  91311. vertex.id = vertexCount;
  91312. if (vertex.triangleCount) {
  91313. vertex.originalOffsets.forEach(function (originalOffset) {
  91314. if (!normalData) {
  91315. return;
  91316. }
  91317. newPositionData.push(vertex.position.x);
  91318. newPositionData.push(vertex.position.y);
  91319. newPositionData.push(vertex.position.z);
  91320. newNormalData.push(normalData[originalOffset * 3]);
  91321. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  91322. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  91323. if (uvs && uvs.length) {
  91324. newUVsData.push(uvs[(originalOffset * 2)]);
  91325. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  91326. }
  91327. else if (colorsData && colorsData.length) {
  91328. newColorsData.push(colorsData[(originalOffset * 4)]);
  91329. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  91330. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  91331. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  91332. }
  91333. ++vertexCount;
  91334. });
  91335. }
  91336. }
  91337. var startingIndex = this._reconstructedMesh.getTotalIndices();
  91338. var startingVertex = this._reconstructedMesh.getTotalVertices();
  91339. var submeshesArray = this._reconstructedMesh.subMeshes;
  91340. this._reconstructedMesh.subMeshes = [];
  91341. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  91342. var originalIndices = this._mesh.getIndices();
  91343. for (i = 0; i < newTriangles.length; ++i) {
  91344. t = newTriangles[i]; //now get the new referencing point for each vertex
  91345. [0, 1, 2].forEach(function (idx) {
  91346. var id = originalIndices[t.originalOffset + idx];
  91347. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  91348. if (offset < 0)
  91349. offset = 0;
  91350. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  91351. });
  91352. }
  91353. //overwriting the old vertex buffers and indices.
  91354. this._reconstructedMesh.setIndices(newIndicesArray);
  91355. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  91356. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  91357. if (newUVsData.length > 0)
  91358. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  91359. if (newColorsData.length > 0)
  91360. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  91361. //create submesh
  91362. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  91363. if (submeshIndex > 0) {
  91364. this._reconstructedMesh.subMeshes = [];
  91365. submeshesArray.forEach(function (submesh) {
  91366. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  91367. });
  91368. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  91369. }
  91370. };
  91371. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  91372. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  91373. this._reconstructedMesh.material = this._mesh.material;
  91374. this._reconstructedMesh.parent = this._mesh.parent;
  91375. this._reconstructedMesh.isVisible = false;
  91376. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  91377. };
  91378. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  91379. for (var i = 0; i < vertex1.triangleCount; ++i) {
  91380. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  91381. if (t.deleted)
  91382. continue;
  91383. var s = this.references[vertex1.triangleStart + i].vertexId;
  91384. var v1 = t.vertices[(s + 1) % 3];
  91385. var v2 = t.vertices[(s + 2) % 3];
  91386. if ((v1 === vertex2 || v2 === vertex2)) {
  91387. deletedArray[i] = true;
  91388. delTr.push(t);
  91389. continue;
  91390. }
  91391. var d1 = v1.position.subtract(point);
  91392. d1 = d1.normalize();
  91393. var d2 = v2.position.subtract(point);
  91394. d2 = d2.normalize();
  91395. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  91396. return true;
  91397. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  91398. deletedArray[i] = false;
  91399. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  91400. return true;
  91401. }
  91402. return false;
  91403. };
  91404. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  91405. var newDeleted = deletedTriangles;
  91406. for (var i = 0; i < vertex.triangleCount; ++i) {
  91407. var ref = this.references[vertex.triangleStart + i];
  91408. var t = this.triangles[ref.triangleId];
  91409. if (t.deleted)
  91410. continue;
  91411. if (deletedArray[i] && t.deletePending) {
  91412. t.deleted = true;
  91413. newDeleted++;
  91414. continue;
  91415. }
  91416. t.vertices[ref.vertexId] = origVertex;
  91417. t.isDirty = true;
  91418. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  91419. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  91420. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  91421. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  91422. this.references.push(ref);
  91423. }
  91424. return newDeleted;
  91425. };
  91426. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  91427. for (var i = 0; i < this.vertices.length; ++i) {
  91428. var vCount = [];
  91429. var vId = [];
  91430. var v = this.vertices[i];
  91431. var j;
  91432. for (j = 0; j < v.triangleCount; ++j) {
  91433. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  91434. for (var ii = 0; ii < 3; ii++) {
  91435. var ofs = 0;
  91436. var vv = triangle.vertices[ii];
  91437. while (ofs < vCount.length) {
  91438. if (vId[ofs] === vv.id)
  91439. break;
  91440. ++ofs;
  91441. }
  91442. if (ofs === vCount.length) {
  91443. vCount.push(1);
  91444. vId.push(vv.id);
  91445. }
  91446. else {
  91447. vCount[ofs]++;
  91448. }
  91449. }
  91450. }
  91451. for (j = 0; j < vCount.length; ++j) {
  91452. if (vCount[j] === 1) {
  91453. this.vertices[vId[j]].isBorder = true;
  91454. }
  91455. else {
  91456. this.vertices[vId[j]].isBorder = false;
  91457. }
  91458. }
  91459. }
  91460. };
  91461. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  91462. if (identifyBorders === void 0) { identifyBorders = false; }
  91463. var i;
  91464. if (!identifyBorders) {
  91465. var newTrianglesVector = [];
  91466. for (i = 0; i < this.triangles.length; ++i) {
  91467. if (!this.triangles[i].deleted) {
  91468. newTrianglesVector.push(this.triangles[i]);
  91469. }
  91470. }
  91471. this.triangles = newTrianglesVector;
  91472. }
  91473. for (i = 0; i < this.vertices.length; ++i) {
  91474. this.vertices[i].triangleCount = 0;
  91475. this.vertices[i].triangleStart = 0;
  91476. }
  91477. var t;
  91478. var j;
  91479. var v;
  91480. for (i = 0; i < this.triangles.length; ++i) {
  91481. t = this.triangles[i];
  91482. for (j = 0; j < 3; ++j) {
  91483. v = t.vertices[j];
  91484. v.triangleCount++;
  91485. }
  91486. }
  91487. var tStart = 0;
  91488. for (i = 0; i < this.vertices.length; ++i) {
  91489. this.vertices[i].triangleStart = tStart;
  91490. tStart += this.vertices[i].triangleCount;
  91491. this.vertices[i].triangleCount = 0;
  91492. }
  91493. var newReferences = new Array(this.triangles.length * 3);
  91494. for (i = 0; i < this.triangles.length; ++i) {
  91495. t = this.triangles[i];
  91496. for (j = 0; j < 3; ++j) {
  91497. v = t.vertices[j];
  91498. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  91499. v.triangleCount++;
  91500. }
  91501. }
  91502. this.references = newReferences;
  91503. if (identifyBorders) {
  91504. this.identifyBorder();
  91505. }
  91506. };
  91507. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  91508. var x = point.x;
  91509. var y = point.y;
  91510. var z = point.z;
  91511. 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
  91512. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  91513. };
  91514. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  91515. var q = vertex1.q.add(vertex2.q);
  91516. var border = vertex1.isBorder && vertex2.isBorder;
  91517. var error = 0;
  91518. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  91519. if (qDet !== 0 && !border) {
  91520. if (!pointResult) {
  91521. pointResult = BABYLON.Vector3.Zero();
  91522. }
  91523. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  91524. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  91525. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  91526. error = this.vertexError(q, pointResult);
  91527. }
  91528. else {
  91529. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  91530. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  91531. var error1 = this.vertexError(q, vertex1.position);
  91532. var error2 = this.vertexError(q, vertex2.position);
  91533. var error3 = this.vertexError(q, p3);
  91534. error = Math.min(error1, error2, error3);
  91535. if (error === error1) {
  91536. if (pointResult) {
  91537. pointResult.copyFrom(vertex1.position);
  91538. }
  91539. }
  91540. else if (error === error2) {
  91541. if (pointResult) {
  91542. pointResult.copyFrom(vertex2.position);
  91543. }
  91544. }
  91545. else {
  91546. if (pointResult) {
  91547. pointResult.copyFrom(p3);
  91548. }
  91549. }
  91550. }
  91551. return error;
  91552. };
  91553. return QuadraticErrorSimplification;
  91554. }());
  91555. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  91556. })(BABYLON || (BABYLON = {}));
  91557. //# sourceMappingURL=babylon.meshSimplification.js.map
  91558. var BABYLON;
  91559. (function (BABYLON) {
  91560. var MeshLODLevel = /** @class */ (function () {
  91561. function MeshLODLevel(distance, mesh) {
  91562. this.distance = distance;
  91563. this.mesh = mesh;
  91564. }
  91565. return MeshLODLevel;
  91566. }());
  91567. BABYLON.MeshLODLevel = MeshLODLevel;
  91568. })(BABYLON || (BABYLON = {}));
  91569. //# sourceMappingURL=babylon.meshLODLevel.js.map
  91570. var BABYLON;
  91571. (function (BABYLON) {
  91572. /**
  91573. * Defines the root class used to create scene optimization to use with SceneOptimizer
  91574. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91575. */
  91576. var SceneOptimization = /** @class */ (function () {
  91577. /**
  91578. * Creates the SceneOptimization object
  91579. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91580. * @param desc defines the description associated with the optimization
  91581. */
  91582. function SceneOptimization(
  91583. /**
  91584. * Defines the priority of this optimization (0 by default which means first in the list)
  91585. */
  91586. priority) {
  91587. if (priority === void 0) { priority = 0; }
  91588. this.priority = priority;
  91589. }
  91590. /**
  91591. * Gets a string describing the action executed by the current optimization
  91592. * @returns description string
  91593. */
  91594. SceneOptimization.prototype.getDescription = function () {
  91595. return "";
  91596. };
  91597. /**
  91598. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91599. * @param scene defines the current scene where to apply this optimization
  91600. * @param optimizer defines the current optimizer
  91601. * @returns true if everything that can be done was applied
  91602. */
  91603. SceneOptimization.prototype.apply = function (scene, optimizer) {
  91604. return true;
  91605. };
  91606. ;
  91607. return SceneOptimization;
  91608. }());
  91609. BABYLON.SceneOptimization = SceneOptimization;
  91610. /**
  91611. * Defines an optimization used to reduce the size of render target textures
  91612. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91613. */
  91614. var TextureOptimization = /** @class */ (function (_super) {
  91615. __extends(TextureOptimization, _super);
  91616. /**
  91617. * Creates the TextureOptimization object
  91618. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91619. * @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
  91620. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  91621. */
  91622. function TextureOptimization(
  91623. /**
  91624. * Defines the priority of this optimization (0 by default which means first in the list)
  91625. */
  91626. priority,
  91627. /**
  91628. * 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
  91629. */
  91630. maximumSize,
  91631. /**
  91632. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  91633. */
  91634. step) {
  91635. if (priority === void 0) { priority = 0; }
  91636. if (maximumSize === void 0) { maximumSize = 1024; }
  91637. if (step === void 0) { step = 0.5; }
  91638. var _this = _super.call(this, priority) || this;
  91639. _this.priority = priority;
  91640. _this.maximumSize = maximumSize;
  91641. _this.step = step;
  91642. return _this;
  91643. }
  91644. /**
  91645. * Gets a string describing the action executed by the current optimization
  91646. * @returns description string
  91647. */
  91648. TextureOptimization.prototype.getDescription = function () {
  91649. return "Reducing render target texture size to " + this.maximumSize;
  91650. };
  91651. /**
  91652. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91653. * @param scene defines the current scene where to apply this optimization
  91654. * @param optimizer defines the current optimizer
  91655. * @returns true if everything that can be done was applied
  91656. */
  91657. TextureOptimization.prototype.apply = function (scene, optimizer) {
  91658. var allDone = true;
  91659. for (var index = 0; index < scene.textures.length; index++) {
  91660. var texture = scene.textures[index];
  91661. if (!texture.canRescale || texture.getContext) {
  91662. continue;
  91663. }
  91664. var currentSize = texture.getSize();
  91665. var maxDimension = Math.max(currentSize.width, currentSize.height);
  91666. if (maxDimension > this.maximumSize) {
  91667. texture.scale(this.step);
  91668. allDone = false;
  91669. }
  91670. }
  91671. return allDone;
  91672. };
  91673. return TextureOptimization;
  91674. }(SceneOptimization));
  91675. BABYLON.TextureOptimization = TextureOptimization;
  91676. /**
  91677. * Defines an optimization used to increase or decrease the rendering resolution
  91678. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91679. */
  91680. var HardwareScalingOptimization = /** @class */ (function (_super) {
  91681. __extends(HardwareScalingOptimization, _super);
  91682. /**
  91683. * Creates the HardwareScalingOptimization object
  91684. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  91685. * @param maximumScale defines the maximum scale to use (2 by default)
  91686. * @param step defines the step to use between two passes (0.5 by default)
  91687. */
  91688. function HardwareScalingOptimization(
  91689. /**
  91690. * Defines the priority of this optimization (0 by default which means first in the list)
  91691. */
  91692. priority,
  91693. /**
  91694. * Defines the maximum scale to use (2 by default)
  91695. */
  91696. maximumScale,
  91697. /**
  91698. * Defines the step to use between two passes (0.5 by default)
  91699. */
  91700. step) {
  91701. if (priority === void 0) { priority = 0; }
  91702. if (maximumScale === void 0) { maximumScale = 2; }
  91703. if (step === void 0) { step = 0.25; }
  91704. var _this = _super.call(this, priority) || this;
  91705. _this.priority = priority;
  91706. _this.maximumScale = maximumScale;
  91707. _this.step = step;
  91708. _this._currentScale = -1;
  91709. _this._directionOffset = 1;
  91710. return _this;
  91711. }
  91712. /**
  91713. * Gets a string describing the action executed by the current optimization
  91714. * @return description string
  91715. */
  91716. HardwareScalingOptimization.prototype.getDescription = function () {
  91717. return "Setting hardware scaling level to " + this._currentScale;
  91718. };
  91719. /**
  91720. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91721. * @param scene defines the current scene where to apply this optimization
  91722. * @param optimizer defines the current optimizer
  91723. * @returns true if everything that can be done was applied
  91724. */
  91725. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  91726. if (this._currentScale === -1) {
  91727. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  91728. if (this._currentScale > this.maximumScale) {
  91729. this._directionOffset = -1;
  91730. }
  91731. }
  91732. this._currentScale += this._directionOffset * this.step;
  91733. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  91734. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  91735. };
  91736. ;
  91737. return HardwareScalingOptimization;
  91738. }(SceneOptimization));
  91739. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  91740. /**
  91741. * Defines an optimization used to remove shadows
  91742. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91743. */
  91744. var ShadowsOptimization = /** @class */ (function (_super) {
  91745. __extends(ShadowsOptimization, _super);
  91746. function ShadowsOptimization() {
  91747. return _super !== null && _super.apply(this, arguments) || this;
  91748. }
  91749. /**
  91750. * Gets a string describing the action executed by the current optimization
  91751. * @return description string
  91752. */
  91753. ShadowsOptimization.prototype.getDescription = function () {
  91754. return "Turning shadows on/off";
  91755. };
  91756. /**
  91757. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91758. * @param scene defines the current scene where to apply this optimization
  91759. * @param optimizer defines the current optimizer
  91760. * @returns true if everything that can be done was applied
  91761. */
  91762. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  91763. scene.shadowsEnabled = optimizer.isInImprovementMode;
  91764. return true;
  91765. };
  91766. ;
  91767. return ShadowsOptimization;
  91768. }(SceneOptimization));
  91769. BABYLON.ShadowsOptimization = ShadowsOptimization;
  91770. /**
  91771. * Defines an optimization used to turn post-processes off
  91772. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91773. */
  91774. var PostProcessesOptimization = /** @class */ (function (_super) {
  91775. __extends(PostProcessesOptimization, _super);
  91776. function PostProcessesOptimization() {
  91777. return _super !== null && _super.apply(this, arguments) || this;
  91778. }
  91779. /**
  91780. * Gets a string describing the action executed by the current optimization
  91781. * @return description string
  91782. */
  91783. PostProcessesOptimization.prototype.getDescription = function () {
  91784. return "Turning post-processes on/off";
  91785. };
  91786. /**
  91787. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91788. * @param scene defines the current scene where to apply this optimization
  91789. * @param optimizer defines the current optimizer
  91790. * @returns true if everything that can be done was applied
  91791. */
  91792. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  91793. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  91794. return true;
  91795. };
  91796. ;
  91797. return PostProcessesOptimization;
  91798. }(SceneOptimization));
  91799. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  91800. /**
  91801. * Defines an optimization used to turn lens flares off
  91802. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91803. */
  91804. var LensFlaresOptimization = /** @class */ (function (_super) {
  91805. __extends(LensFlaresOptimization, _super);
  91806. function LensFlaresOptimization() {
  91807. return _super !== null && _super.apply(this, arguments) || this;
  91808. }
  91809. /**
  91810. * Gets a string describing the action executed by the current optimization
  91811. * @return description string
  91812. */
  91813. LensFlaresOptimization.prototype.getDescription = function () {
  91814. return "Turning lens flares on/off";
  91815. };
  91816. /**
  91817. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91818. * @param scene defines the current scene where to apply this optimization
  91819. * @param optimizer defines the current optimizer
  91820. * @returns true if everything that can be done was applied
  91821. */
  91822. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  91823. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  91824. return true;
  91825. };
  91826. ;
  91827. return LensFlaresOptimization;
  91828. }(SceneOptimization));
  91829. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  91830. /**
  91831. * Defines an optimization based on user defined callback.
  91832. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91833. */
  91834. var CustomOptimization = /** @class */ (function (_super) {
  91835. __extends(CustomOptimization, _super);
  91836. function CustomOptimization() {
  91837. return _super !== null && _super.apply(this, arguments) || this;
  91838. }
  91839. /**
  91840. * Gets a string describing the action executed by the current optimization
  91841. * @returns description string
  91842. */
  91843. CustomOptimization.prototype.getDescription = function () {
  91844. if (this.onGetDescription) {
  91845. return this.onGetDescription();
  91846. }
  91847. return "Running user defined callback";
  91848. };
  91849. /**
  91850. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91851. * @param scene defines the current scene where to apply this optimization
  91852. * @param optimizer defines the current optimizer
  91853. * @returns true if everything that can be done was applied
  91854. */
  91855. CustomOptimization.prototype.apply = function (scene, optimizer) {
  91856. if (this.onApply) {
  91857. return this.onApply(scene, optimizer);
  91858. }
  91859. return true;
  91860. };
  91861. ;
  91862. return CustomOptimization;
  91863. }(SceneOptimization));
  91864. BABYLON.CustomOptimization = CustomOptimization;
  91865. /**
  91866. * Defines an optimization used to turn particles off
  91867. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91868. */
  91869. var ParticlesOptimization = /** @class */ (function (_super) {
  91870. __extends(ParticlesOptimization, _super);
  91871. function ParticlesOptimization() {
  91872. return _super !== null && _super.apply(this, arguments) || this;
  91873. }
  91874. /**
  91875. * Gets a string describing the action executed by the current optimization
  91876. * @return description string
  91877. */
  91878. ParticlesOptimization.prototype.getDescription = function () {
  91879. return "Turning particles on/off";
  91880. };
  91881. /**
  91882. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91883. * @param scene defines the current scene where to apply this optimization
  91884. * @param optimizer defines the current optimizer
  91885. * @returns true if everything that can be done was applied
  91886. */
  91887. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  91888. scene.particlesEnabled = optimizer.isInImprovementMode;
  91889. return true;
  91890. };
  91891. ;
  91892. return ParticlesOptimization;
  91893. }(SceneOptimization));
  91894. BABYLON.ParticlesOptimization = ParticlesOptimization;
  91895. /**
  91896. * Defines an optimization used to turn render targets off
  91897. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91898. */
  91899. var RenderTargetsOptimization = /** @class */ (function (_super) {
  91900. __extends(RenderTargetsOptimization, _super);
  91901. function RenderTargetsOptimization() {
  91902. return _super !== null && _super.apply(this, arguments) || this;
  91903. }
  91904. /**
  91905. * Gets a string describing the action executed by the current optimization
  91906. * @return description string
  91907. */
  91908. RenderTargetsOptimization.prototype.getDescription = function () {
  91909. return "Turning render targets off";
  91910. };
  91911. /**
  91912. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91913. * @param scene defines the current scene where to apply this optimization
  91914. * @param optimizer defines the current optimizer
  91915. * @returns true if everything that can be done was applied
  91916. */
  91917. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  91918. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  91919. return true;
  91920. };
  91921. ;
  91922. return RenderTargetsOptimization;
  91923. }(SceneOptimization));
  91924. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  91925. /**
  91926. * Defines an optimization used to merge meshes with compatible materials
  91927. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  91928. */
  91929. var MergeMeshesOptimization = /** @class */ (function (_super) {
  91930. __extends(MergeMeshesOptimization, _super);
  91931. function MergeMeshesOptimization() {
  91932. var _this = _super !== null && _super.apply(this, arguments) || this;
  91933. _this._canBeMerged = function (abstractMesh) {
  91934. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  91935. return false;
  91936. }
  91937. var mesh = abstractMesh;
  91938. if (!mesh.isVisible || !mesh.isEnabled()) {
  91939. return false;
  91940. }
  91941. if (mesh.instances.length > 0) {
  91942. return false;
  91943. }
  91944. if (mesh.skeleton || mesh.hasLODLevels) {
  91945. return false;
  91946. }
  91947. if (mesh.parent) {
  91948. return false;
  91949. }
  91950. return true;
  91951. };
  91952. return _this;
  91953. }
  91954. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  91955. /**
  91956. * Gets or sets a boolean which defines if optimization octree has to be updated
  91957. */
  91958. get: function () {
  91959. return MergeMeshesOptimization._UpdateSelectionTree;
  91960. },
  91961. /**
  91962. * Gets or sets a boolean which defines if optimization octree has to be updated
  91963. */
  91964. set: function (value) {
  91965. MergeMeshesOptimization._UpdateSelectionTree = value;
  91966. },
  91967. enumerable: true,
  91968. configurable: true
  91969. });
  91970. /**
  91971. * Gets a string describing the action executed by the current optimization
  91972. * @return description string
  91973. */
  91974. MergeMeshesOptimization.prototype.getDescription = function () {
  91975. return "Merging similar meshes together";
  91976. };
  91977. /**
  91978. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  91979. * @param scene defines the current scene where to apply this optimization
  91980. * @param optimizer defines the current optimizer
  91981. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  91982. * @returns true if everything that can be done was applied
  91983. */
  91984. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  91985. var globalPool = scene.meshes.slice(0);
  91986. var globalLength = globalPool.length;
  91987. for (var index = 0; index < globalLength; index++) {
  91988. var currentPool = new Array();
  91989. var current = globalPool[index];
  91990. // Checks
  91991. if (!this._canBeMerged(current)) {
  91992. continue;
  91993. }
  91994. currentPool.push(current);
  91995. // Find compatible meshes
  91996. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  91997. var otherMesh = globalPool[subIndex];
  91998. if (!this._canBeMerged(otherMesh)) {
  91999. continue;
  92000. }
  92001. if (otherMesh.material !== current.material) {
  92002. continue;
  92003. }
  92004. if (otherMesh.checkCollisions !== current.checkCollisions) {
  92005. continue;
  92006. }
  92007. currentPool.push(otherMesh);
  92008. globalLength--;
  92009. globalPool.splice(subIndex, 1);
  92010. subIndex--;
  92011. }
  92012. if (currentPool.length < 2) {
  92013. continue;
  92014. }
  92015. // Merge meshes
  92016. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  92017. }
  92018. if (updateSelectionTree != undefined) {
  92019. if (updateSelectionTree) {
  92020. scene.createOrUpdateSelectionOctree();
  92021. }
  92022. }
  92023. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  92024. scene.createOrUpdateSelectionOctree();
  92025. }
  92026. return true;
  92027. };
  92028. ;
  92029. MergeMeshesOptimization._UpdateSelectionTree = false;
  92030. return MergeMeshesOptimization;
  92031. }(SceneOptimization));
  92032. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  92033. /**
  92034. * Defines a list of options used by SceneOptimizer
  92035. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92036. */
  92037. var SceneOptimizerOptions = /** @class */ (function () {
  92038. /**
  92039. * Creates a new list of options used by SceneOptimizer
  92040. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  92041. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  92042. */
  92043. function SceneOptimizerOptions(
  92044. /**
  92045. * Defines the target frame rate to reach (60 by default)
  92046. */
  92047. targetFrameRate,
  92048. /**
  92049. * Defines the interval between two checkes (2000ms by default)
  92050. */
  92051. trackerDuration) {
  92052. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  92053. if (trackerDuration === void 0) { trackerDuration = 2000; }
  92054. this.targetFrameRate = targetFrameRate;
  92055. this.trackerDuration = trackerDuration;
  92056. /**
  92057. * Gets the list of optimizations to apply
  92058. */
  92059. this.optimizations = new Array();
  92060. }
  92061. /**
  92062. * Add a new optimization
  92063. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  92064. * @returns the current SceneOptimizerOptions
  92065. */
  92066. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  92067. this.optimizations.push(optimization);
  92068. return this;
  92069. };
  92070. /**
  92071. * Add a new custom optimization
  92072. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  92073. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  92074. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  92075. * @returns the current SceneOptimizerOptions
  92076. */
  92077. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  92078. if (priority === void 0) { priority = 0; }
  92079. var optimization = new CustomOptimization(priority);
  92080. optimization.onApply = onApply;
  92081. optimization.onGetDescription = onGetDescription;
  92082. this.optimizations.push(optimization);
  92083. return this;
  92084. };
  92085. /**
  92086. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  92087. * @param targetFrameRate defines the target frame rate (60 by default)
  92088. * @returns a SceneOptimizerOptions object
  92089. */
  92090. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  92091. var result = new SceneOptimizerOptions(targetFrameRate);
  92092. var priority = 0;
  92093. result.addOptimization(new MergeMeshesOptimization(priority));
  92094. result.addOptimization(new ShadowsOptimization(priority));
  92095. result.addOptimization(new LensFlaresOptimization(priority));
  92096. // Next priority
  92097. priority++;
  92098. result.addOptimization(new PostProcessesOptimization(priority));
  92099. result.addOptimization(new ParticlesOptimization(priority));
  92100. // Next priority
  92101. priority++;
  92102. result.addOptimization(new TextureOptimization(priority, 1024));
  92103. return result;
  92104. };
  92105. /**
  92106. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  92107. * @param targetFrameRate defines the target frame rate (60 by default)
  92108. * @returns a SceneOptimizerOptions object
  92109. */
  92110. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  92111. var result = new SceneOptimizerOptions(targetFrameRate);
  92112. var priority = 0;
  92113. result.addOptimization(new MergeMeshesOptimization(priority));
  92114. result.addOptimization(new ShadowsOptimization(priority));
  92115. result.addOptimization(new LensFlaresOptimization(priority));
  92116. // Next priority
  92117. priority++;
  92118. result.addOptimization(new PostProcessesOptimization(priority));
  92119. result.addOptimization(new ParticlesOptimization(priority));
  92120. // Next priority
  92121. priority++;
  92122. result.addOptimization(new TextureOptimization(priority, 512));
  92123. // Next priority
  92124. priority++;
  92125. result.addOptimization(new RenderTargetsOptimization(priority));
  92126. // Next priority
  92127. priority++;
  92128. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  92129. return result;
  92130. };
  92131. /**
  92132. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  92133. * @param targetFrameRate defines the target frame rate (60 by default)
  92134. * @returns a SceneOptimizerOptions object
  92135. */
  92136. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  92137. var result = new SceneOptimizerOptions(targetFrameRate);
  92138. var priority = 0;
  92139. result.addOptimization(new MergeMeshesOptimization(priority));
  92140. result.addOptimization(new ShadowsOptimization(priority));
  92141. result.addOptimization(new LensFlaresOptimization(priority));
  92142. // Next priority
  92143. priority++;
  92144. result.addOptimization(new PostProcessesOptimization(priority));
  92145. result.addOptimization(new ParticlesOptimization(priority));
  92146. // Next priority
  92147. priority++;
  92148. result.addOptimization(new TextureOptimization(priority, 256));
  92149. // Next priority
  92150. priority++;
  92151. result.addOptimization(new RenderTargetsOptimization(priority));
  92152. // Next priority
  92153. priority++;
  92154. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  92155. return result;
  92156. };
  92157. return SceneOptimizerOptions;
  92158. }());
  92159. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  92160. /**
  92161. * Class used to run optimizations in order to reach a target frame rate
  92162. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  92163. */
  92164. var SceneOptimizer = /** @class */ (function () {
  92165. /**
  92166. * Creates a new SceneOptimizer
  92167. * @param scene defines the scene to work on
  92168. * @param options defines the options to use with the SceneOptimizer
  92169. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  92170. * @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)
  92171. */
  92172. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  92173. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  92174. if (improvementMode === void 0) { improvementMode = false; }
  92175. var _this = this;
  92176. this._isRunning = false;
  92177. this._currentPriorityLevel = 0;
  92178. this._targetFrameRate = 60;
  92179. this._trackerDuration = 2000;
  92180. this._currentFrameRate = 0;
  92181. this._improvementMode = false;
  92182. /**
  92183. * Defines an observable called when the optimizer reaches the target frame rate
  92184. */
  92185. this.onSuccessObservable = new BABYLON.Observable();
  92186. /**
  92187. * Defines an observable called when the optimizer enables an optimization
  92188. */
  92189. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  92190. /**
  92191. * Defines an observable called when the optimizer is not able to reach the target frame rate
  92192. */
  92193. this.onFailureObservable = new BABYLON.Observable();
  92194. if (!options) {
  92195. this._options = new SceneOptimizerOptions();
  92196. }
  92197. else {
  92198. this._options = options;
  92199. }
  92200. if (this._options.targetFrameRate) {
  92201. this._targetFrameRate = this._options.targetFrameRate;
  92202. }
  92203. if (this._options.trackerDuration) {
  92204. this._trackerDuration = this._options.trackerDuration;
  92205. }
  92206. if (autoGeneratePriorities) {
  92207. var priority = 0;
  92208. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  92209. var optim = _a[_i];
  92210. optim.priority = priority++;
  92211. }
  92212. }
  92213. this._improvementMode = improvementMode;
  92214. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92215. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  92216. _this._sceneDisposeObserver = null;
  92217. _this.dispose();
  92218. });
  92219. }
  92220. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  92221. /**
  92222. * Gets a boolean indicating if the optimizer is in improvement mode
  92223. */
  92224. get: function () {
  92225. return this._improvementMode;
  92226. },
  92227. enumerable: true,
  92228. configurable: true
  92229. });
  92230. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  92231. /**
  92232. * Gets the current priority level (0 at start)
  92233. */
  92234. get: function () {
  92235. return this._currentPriorityLevel;
  92236. },
  92237. enumerable: true,
  92238. configurable: true
  92239. });
  92240. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  92241. /**
  92242. * Gets the current frame rate checked by the SceneOptimizer
  92243. */
  92244. get: function () {
  92245. return this._currentFrameRate;
  92246. },
  92247. enumerable: true,
  92248. configurable: true
  92249. });
  92250. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  92251. /**
  92252. * Gets or sets the current target frame rate (60 by default)
  92253. */
  92254. get: function () {
  92255. return this._targetFrameRate;
  92256. },
  92257. /**
  92258. * Gets or sets the current target frame rate (60 by default)
  92259. */
  92260. set: function (value) {
  92261. this._targetFrameRate = value;
  92262. },
  92263. enumerable: true,
  92264. configurable: true
  92265. });
  92266. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  92267. /**
  92268. * Gets or sets the current interval between two checks (every 2000ms by default)
  92269. */
  92270. get: function () {
  92271. return this._trackerDuration;
  92272. },
  92273. /**
  92274. * Gets or sets the current interval between two checks (every 2000ms by default)
  92275. */
  92276. set: function (value) {
  92277. this._trackerDuration = value;
  92278. },
  92279. enumerable: true,
  92280. configurable: true
  92281. });
  92282. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  92283. /**
  92284. * Gets the list of active optimizations
  92285. */
  92286. get: function () {
  92287. return this._options.optimizations;
  92288. },
  92289. enumerable: true,
  92290. configurable: true
  92291. });
  92292. /**
  92293. * Stops the current optimizer
  92294. */
  92295. SceneOptimizer.prototype.stop = function () {
  92296. this._isRunning = false;
  92297. };
  92298. /**
  92299. * Reset the optimizer to initial step (current priority level = 0)
  92300. */
  92301. SceneOptimizer.prototype.reset = function () {
  92302. this._currentPriorityLevel = 0;
  92303. };
  92304. /**
  92305. * Start the optimizer. By default it will try to reach a specific framerate
  92306. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  92307. */
  92308. SceneOptimizer.prototype.start = function () {
  92309. var _this = this;
  92310. if (this._isRunning) {
  92311. return;
  92312. }
  92313. this._isRunning = true;
  92314. // Let's wait for the scene to be ready before running our check
  92315. this._scene.executeWhenReady(function () {
  92316. setTimeout(function () {
  92317. _this._checkCurrentState();
  92318. }, _this._trackerDuration);
  92319. });
  92320. };
  92321. SceneOptimizer.prototype._checkCurrentState = function () {
  92322. var _this = this;
  92323. if (!this._isRunning) {
  92324. return;
  92325. }
  92326. var scene = this._scene;
  92327. var options = this._options;
  92328. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  92329. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  92330. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  92331. this._isRunning = false;
  92332. this.onSuccessObservable.notifyObservers(this);
  92333. return;
  92334. }
  92335. // Apply current level of optimizations
  92336. var allDone = true;
  92337. var noOptimizationApplied = true;
  92338. for (var index = 0; index < options.optimizations.length; index++) {
  92339. var optimization = options.optimizations[index];
  92340. if (optimization.priority === this._currentPriorityLevel) {
  92341. noOptimizationApplied = false;
  92342. allDone = allDone && optimization.apply(scene, this);
  92343. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  92344. }
  92345. }
  92346. // If no optimization was applied, this is a failure :(
  92347. if (noOptimizationApplied) {
  92348. this._isRunning = false;
  92349. this.onFailureObservable.notifyObservers(this);
  92350. return;
  92351. }
  92352. // If all optimizations were done, move to next level
  92353. if (allDone) {
  92354. this._currentPriorityLevel++;
  92355. }
  92356. // Let's the system running for a specific amount of time before checking FPS
  92357. scene.executeWhenReady(function () {
  92358. setTimeout(function () {
  92359. _this._checkCurrentState();
  92360. }, _this._trackerDuration);
  92361. });
  92362. };
  92363. /**
  92364. * Release all resources
  92365. */
  92366. SceneOptimizer.prototype.dispose = function () {
  92367. this.stop();
  92368. this.onSuccessObservable.clear();
  92369. this.onFailureObservable.clear();
  92370. this.onNewOptimizationAppliedObservable.clear();
  92371. if (this._sceneDisposeObserver) {
  92372. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  92373. }
  92374. };
  92375. /**
  92376. * Helper function to create a SceneOptimizer with one single line of code
  92377. * @param scene defines the scene to work on
  92378. * @param options defines the options to use with the SceneOptimizer
  92379. * @param onSuccess defines a callback to call on success
  92380. * @param onFailure defines a callback to call on failure
  92381. * @returns the new SceneOptimizer object
  92382. */
  92383. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  92384. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  92385. if (onSuccess) {
  92386. optimizer.onSuccessObservable.add(function () {
  92387. onSuccess();
  92388. });
  92389. }
  92390. if (onFailure) {
  92391. optimizer.onFailureObservable.add(function () {
  92392. onFailure();
  92393. });
  92394. }
  92395. optimizer.start();
  92396. return optimizer;
  92397. };
  92398. return SceneOptimizer;
  92399. }());
  92400. BABYLON.SceneOptimizer = SceneOptimizer;
  92401. })(BABYLON || (BABYLON = {}));
  92402. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  92403. var BABYLON;
  92404. (function (BABYLON) {
  92405. var OutlineRenderer = /** @class */ (function () {
  92406. function OutlineRenderer(scene) {
  92407. this.zOffset = 1;
  92408. this._scene = scene;
  92409. }
  92410. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  92411. var _this = this;
  92412. if (useOverlay === void 0) { useOverlay = false; }
  92413. var scene = this._scene;
  92414. var engine = this._scene.getEngine();
  92415. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  92416. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  92417. return;
  92418. }
  92419. var mesh = subMesh.getRenderingMesh();
  92420. var material = subMesh.getMaterial();
  92421. if (!material || !scene.activeCamera) {
  92422. return;
  92423. }
  92424. engine.enableEffect(this._effect);
  92425. // Logarithmic depth
  92426. if (material.useLogarithmicDepth) {
  92427. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  92428. }
  92429. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  92430. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  92431. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  92432. // Bones
  92433. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  92434. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  92435. }
  92436. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  92437. // Alpha test
  92438. if (material && material.needAlphaTesting()) {
  92439. var alphaTexture = material.getAlphaTestTexture();
  92440. if (alphaTexture) {
  92441. this._effect.setTexture("diffuseSampler", alphaTexture);
  92442. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  92443. }
  92444. }
  92445. engine.setZOffset(-this.zOffset);
  92446. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  92447. engine.setZOffset(0);
  92448. };
  92449. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  92450. var defines = [];
  92451. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  92452. var mesh = subMesh.getMesh();
  92453. var material = subMesh.getMaterial();
  92454. if (material) {
  92455. // Alpha test
  92456. if (material.needAlphaTesting()) {
  92457. defines.push("#define ALPHATEST");
  92458. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92459. attribs.push(BABYLON.VertexBuffer.UVKind);
  92460. defines.push("#define UV1");
  92461. }
  92462. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  92463. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92464. defines.push("#define UV2");
  92465. }
  92466. }
  92467. //Logarithmic depth
  92468. if (material.useLogarithmicDepth) {
  92469. defines.push("#define LOGARITHMICDEPTH");
  92470. }
  92471. }
  92472. // Bones
  92473. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  92474. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  92475. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  92476. if (mesh.numBoneInfluencers > 4) {
  92477. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  92478. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  92479. }
  92480. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  92481. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  92482. }
  92483. else {
  92484. defines.push("#define NUM_BONE_INFLUENCERS 0");
  92485. }
  92486. // Instances
  92487. if (useInstances) {
  92488. defines.push("#define INSTANCES");
  92489. attribs.push("world0");
  92490. attribs.push("world1");
  92491. attribs.push("world2");
  92492. attribs.push("world3");
  92493. }
  92494. // Get correct effect
  92495. var join = defines.join("\n");
  92496. if (this._cachedDefines !== join) {
  92497. this._cachedDefines = join;
  92498. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  92499. }
  92500. return this._effect.isReady();
  92501. };
  92502. return OutlineRenderer;
  92503. }());
  92504. BABYLON.OutlineRenderer = OutlineRenderer;
  92505. })(BABYLON || (BABYLON = {}));
  92506. //# sourceMappingURL=babylon.outlineRenderer.js.map
  92507. var BABYLON;
  92508. (function (BABYLON) {
  92509. var FaceAdjacencies = /** @class */ (function () {
  92510. function FaceAdjacencies() {
  92511. this.edges = new Array();
  92512. this.edgesConnectedCount = 0;
  92513. }
  92514. return FaceAdjacencies;
  92515. }());
  92516. var EdgesRenderer = /** @class */ (function () {
  92517. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  92518. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  92519. if (epsilon === void 0) { epsilon = 0.95; }
  92520. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  92521. this.edgesWidthScalerForOrthographic = 1000.0;
  92522. this.edgesWidthScalerForPerspective = 50.0;
  92523. this._linesPositions = new Array();
  92524. this._linesNormals = new Array();
  92525. this._linesIndices = new Array();
  92526. this._buffers = {};
  92527. this._checkVerticesInsteadOfIndices = false;
  92528. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  92529. this.isEnabled = true;
  92530. this._source = source;
  92531. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  92532. this._epsilon = epsilon;
  92533. this._prepareRessources();
  92534. this._generateEdgesLines();
  92535. }
  92536. EdgesRenderer.prototype._prepareRessources = function () {
  92537. if (this._lineShader) {
  92538. return;
  92539. }
  92540. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  92541. attributes: ["position", "normal"],
  92542. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  92543. });
  92544. this._lineShader.disableDepthWrite = true;
  92545. this._lineShader.backFaceCulling = false;
  92546. };
  92547. EdgesRenderer.prototype._rebuild = function () {
  92548. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  92549. if (buffer) {
  92550. buffer._rebuild();
  92551. }
  92552. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  92553. if (buffer) {
  92554. buffer._rebuild();
  92555. }
  92556. var scene = this._source.getScene();
  92557. var engine = scene.getEngine();
  92558. this._ib = engine.createIndexBuffer(this._linesIndices);
  92559. };
  92560. EdgesRenderer.prototype.dispose = function () {
  92561. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  92562. if (buffer) {
  92563. buffer.dispose();
  92564. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  92565. }
  92566. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  92567. if (buffer) {
  92568. buffer.dispose();
  92569. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  92570. }
  92571. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  92572. this._lineShader.dispose();
  92573. };
  92574. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  92575. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  92576. return 0;
  92577. }
  92578. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  92579. return 1;
  92580. }
  92581. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  92582. return 2;
  92583. }
  92584. return -1;
  92585. };
  92586. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  92587. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  92588. return 0;
  92589. }
  92590. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  92591. return 1;
  92592. }
  92593. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  92594. return 2;
  92595. }
  92596. return -1;
  92597. };
  92598. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  92599. var needToCreateLine;
  92600. if (edge === undefined) {
  92601. needToCreateLine = true;
  92602. }
  92603. else {
  92604. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  92605. needToCreateLine = dotProduct < this._epsilon;
  92606. }
  92607. if (needToCreateLine) {
  92608. var offset = this._linesPositions.length / 3;
  92609. var normal = p0.subtract(p1);
  92610. normal.normalize();
  92611. // Positions
  92612. this._linesPositions.push(p0.x);
  92613. this._linesPositions.push(p0.y);
  92614. this._linesPositions.push(p0.z);
  92615. this._linesPositions.push(p0.x);
  92616. this._linesPositions.push(p0.y);
  92617. this._linesPositions.push(p0.z);
  92618. this._linesPositions.push(p1.x);
  92619. this._linesPositions.push(p1.y);
  92620. this._linesPositions.push(p1.z);
  92621. this._linesPositions.push(p1.x);
  92622. this._linesPositions.push(p1.y);
  92623. this._linesPositions.push(p1.z);
  92624. // Normals
  92625. this._linesNormals.push(p1.x);
  92626. this._linesNormals.push(p1.y);
  92627. this._linesNormals.push(p1.z);
  92628. this._linesNormals.push(-1);
  92629. this._linesNormals.push(p1.x);
  92630. this._linesNormals.push(p1.y);
  92631. this._linesNormals.push(p1.z);
  92632. this._linesNormals.push(1);
  92633. this._linesNormals.push(p0.x);
  92634. this._linesNormals.push(p0.y);
  92635. this._linesNormals.push(p0.z);
  92636. this._linesNormals.push(-1);
  92637. this._linesNormals.push(p0.x);
  92638. this._linesNormals.push(p0.y);
  92639. this._linesNormals.push(p0.z);
  92640. this._linesNormals.push(1);
  92641. // Indices
  92642. this._linesIndices.push(offset);
  92643. this._linesIndices.push(offset + 1);
  92644. this._linesIndices.push(offset + 2);
  92645. this._linesIndices.push(offset);
  92646. this._linesIndices.push(offset + 2);
  92647. this._linesIndices.push(offset + 3);
  92648. }
  92649. };
  92650. EdgesRenderer.prototype._generateEdgesLines = function () {
  92651. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  92652. var indices = this._source.getIndices();
  92653. if (!indices || !positions) {
  92654. return;
  92655. }
  92656. // First let's find adjacencies
  92657. var adjacencies = new Array();
  92658. var faceNormals = new Array();
  92659. var index;
  92660. var faceAdjacencies;
  92661. // Prepare faces
  92662. for (index = 0; index < indices.length; index += 3) {
  92663. faceAdjacencies = new FaceAdjacencies();
  92664. var p0Index = indices[index];
  92665. var p1Index = indices[index + 1];
  92666. var p2Index = indices[index + 2];
  92667. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  92668. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  92669. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  92670. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  92671. faceNormal.normalize();
  92672. faceNormals.push(faceNormal);
  92673. adjacencies.push(faceAdjacencies);
  92674. }
  92675. // Scan
  92676. for (index = 0; index < adjacencies.length; index++) {
  92677. faceAdjacencies = adjacencies[index];
  92678. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  92679. var otherFaceAdjacencies = adjacencies[otherIndex];
  92680. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  92681. break;
  92682. }
  92683. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  92684. continue;
  92685. }
  92686. var otherP0 = indices[otherIndex * 3];
  92687. var otherP1 = indices[otherIndex * 3 + 1];
  92688. var otherP2 = indices[otherIndex * 3 + 2];
  92689. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  92690. var otherEdgeIndex = 0;
  92691. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  92692. continue;
  92693. }
  92694. switch (edgeIndex) {
  92695. case 0:
  92696. if (this._checkVerticesInsteadOfIndices) {
  92697. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92698. }
  92699. else {
  92700. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  92701. }
  92702. break;
  92703. case 1:
  92704. if (this._checkVerticesInsteadOfIndices) {
  92705. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92706. }
  92707. else {
  92708. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  92709. }
  92710. break;
  92711. case 2:
  92712. if (this._checkVerticesInsteadOfIndices) {
  92713. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  92714. }
  92715. else {
  92716. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  92717. }
  92718. break;
  92719. }
  92720. if (otherEdgeIndex === -1) {
  92721. continue;
  92722. }
  92723. faceAdjacencies.edges[edgeIndex] = otherIndex;
  92724. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  92725. faceAdjacencies.edgesConnectedCount++;
  92726. otherFaceAdjacencies.edgesConnectedCount++;
  92727. if (faceAdjacencies.edgesConnectedCount === 3) {
  92728. break;
  92729. }
  92730. }
  92731. }
  92732. }
  92733. // Create lines
  92734. for (index = 0; index < adjacencies.length; index++) {
  92735. // 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
  92736. var current = adjacencies[index];
  92737. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  92738. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  92739. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  92740. }
  92741. // Merge into a single mesh
  92742. var engine = this._source.getScene().getEngine();
  92743. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  92744. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  92745. this._ib = engine.createIndexBuffer(this._linesIndices);
  92746. this._indicesCount = this._linesIndices.length;
  92747. };
  92748. EdgesRenderer.prototype.render = function () {
  92749. var scene = this._source.getScene();
  92750. if (!this._lineShader.isReady() || !scene.activeCamera) {
  92751. return;
  92752. }
  92753. var engine = scene.getEngine();
  92754. this._lineShader._preBind();
  92755. // VBOs
  92756. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  92757. scene.resetCachedMaterial();
  92758. this._lineShader.setColor4("color", this._source.edgesColor);
  92759. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  92760. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  92761. }
  92762. else {
  92763. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  92764. }
  92765. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  92766. this._lineShader.bind(this._source.getWorldMatrix());
  92767. // Draw order
  92768. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  92769. this._lineShader.unbind();
  92770. engine.setDepthWrite(true);
  92771. };
  92772. return EdgesRenderer;
  92773. }());
  92774. BABYLON.EdgesRenderer = EdgesRenderer;
  92775. })(BABYLON || (BABYLON = {}));
  92776. //# sourceMappingURL=babylon.edgesRenderer.js.map
  92777. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92778. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92779. s = arguments[i];
  92780. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92781. t[p] = s[p];
  92782. }
  92783. return t;
  92784. };
  92785. var BABYLON;
  92786. (function (BABYLON) {
  92787. /**
  92788. * The effect layer Helps adding post process effect blended with the main pass.
  92789. *
  92790. * This can be for instance use to generate glow or higlight effects on the scene.
  92791. *
  92792. * The effect layer class can not be used directly and is intented to inherited from to be
  92793. * customized per effects.
  92794. */
  92795. var EffectLayer = /** @class */ (function () {
  92796. /**
  92797. * Instantiates a new effect Layer and references it in the scene.
  92798. * @param name The name of the layer
  92799. * @param scene The scene to use the layer in
  92800. */
  92801. function EffectLayer(
  92802. /** The Friendly of the effect in the scene */
  92803. name, scene) {
  92804. this._vertexBuffers = {};
  92805. this._maxSize = 0;
  92806. this._mainTextureDesiredSize = { width: 0, height: 0 };
  92807. this._shouldRender = true;
  92808. this._postProcesses = [];
  92809. this._textures = [];
  92810. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  92811. /**
  92812. * The clear color of the texture used to generate the glow map.
  92813. */
  92814. this.neutralColor = new BABYLON.Color4();
  92815. /**
  92816. * Specifies wether the highlight layer is enabled or not.
  92817. */
  92818. this.isEnabled = true;
  92819. /**
  92820. * An event triggered when the effect layer has been disposed.
  92821. */
  92822. this.onDisposeObservable = new BABYLON.Observable();
  92823. /**
  92824. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  92825. */
  92826. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  92827. /**
  92828. * An event triggered when the generated texture is being merged in the scene.
  92829. */
  92830. this.onBeforeComposeObservable = new BABYLON.Observable();
  92831. /**
  92832. * An event triggered when the generated texture has been merged in the scene.
  92833. */
  92834. this.onAfterComposeObservable = new BABYLON.Observable();
  92835. /**
  92836. * An event triggered when the efffect layer changes its size.
  92837. */
  92838. this.onSizeChangedObservable = new BABYLON.Observable();
  92839. this.name = name;
  92840. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92841. this._engine = scene.getEngine();
  92842. this._maxSize = this._engine.getCaps().maxTextureSize;
  92843. this._scene.effectLayers.push(this);
  92844. // Generate Buffers
  92845. this._generateIndexBuffer();
  92846. this._genrateVertexBuffer();
  92847. }
  92848. Object.defineProperty(EffectLayer.prototype, "camera", {
  92849. /**
  92850. * Gets the camera attached to the layer.
  92851. */
  92852. get: function () {
  92853. return this._effectLayerOptions.camera;
  92854. },
  92855. enumerable: true,
  92856. configurable: true
  92857. });
  92858. /**
  92859. * Initializes the effect layer with the required options.
  92860. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  92861. */
  92862. EffectLayer.prototype._init = function (options) {
  92863. // Adapt options
  92864. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  92865. this._setMainTextureSize();
  92866. this._createMainTexture();
  92867. this._createTextureAndPostProcesses();
  92868. this._mergeEffect = this._createMergeEffect();
  92869. };
  92870. /**
  92871. * Generates the index buffer of the full screen quad blending to the main canvas.
  92872. */
  92873. EffectLayer.prototype._generateIndexBuffer = function () {
  92874. // Indices
  92875. var indices = [];
  92876. indices.push(0);
  92877. indices.push(1);
  92878. indices.push(2);
  92879. indices.push(0);
  92880. indices.push(2);
  92881. indices.push(3);
  92882. this._indexBuffer = this._engine.createIndexBuffer(indices);
  92883. };
  92884. /**
  92885. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  92886. */
  92887. EffectLayer.prototype._genrateVertexBuffer = function () {
  92888. // VBO
  92889. var vertices = [];
  92890. vertices.push(1, 1);
  92891. vertices.push(-1, 1);
  92892. vertices.push(-1, -1);
  92893. vertices.push(1, -1);
  92894. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  92895. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  92896. };
  92897. /**
  92898. * Sets the main texture desired size which is the closest power of two
  92899. * of the engine canvas size.
  92900. */
  92901. EffectLayer.prototype._setMainTextureSize = function () {
  92902. if (this._effectLayerOptions.mainTextureFixedSize) {
  92903. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  92904. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  92905. }
  92906. else {
  92907. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  92908. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  92909. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  92910. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  92911. }
  92912. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  92913. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  92914. };
  92915. /**
  92916. * Creates the main texture for the effect layer.
  92917. */
  92918. EffectLayer.prototype._createMainTexture = function () {
  92919. var _this = this;
  92920. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  92921. width: this._mainTextureDesiredSize.width,
  92922. height: this._mainTextureDesiredSize.height
  92923. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  92924. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  92925. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92926. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92927. this._mainTexture.anisotropicFilteringLevel = 1;
  92928. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92929. this._mainTexture.renderParticles = false;
  92930. this._mainTexture.renderList = null;
  92931. this._mainTexture.ignoreCameraViewport = true;
  92932. // Custom render function
  92933. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  92934. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  92935. var index;
  92936. var engine = _this._scene.getEngine();
  92937. if (depthOnlySubMeshes.length) {
  92938. engine.setColorWrite(false);
  92939. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  92940. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  92941. }
  92942. engine.setColorWrite(true);
  92943. }
  92944. for (index = 0; index < opaqueSubMeshes.length; index++) {
  92945. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  92946. }
  92947. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  92948. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  92949. }
  92950. for (index = 0; index < transparentSubMeshes.length; index++) {
  92951. _this._renderSubMesh(transparentSubMeshes.data[index]);
  92952. }
  92953. };
  92954. this._mainTexture.onClearObservable.add(function (engine) {
  92955. engine.clear(_this.neutralColor, true, true, true);
  92956. });
  92957. };
  92958. /**
  92959. * Checks for the readiness of the element composing the layer.
  92960. * @param subMesh the mesh to check for
  92961. * @param useInstances specify wether or not to use instances to render the mesh
  92962. * @param emissiveTexture the associated emissive texture used to generate the glow
  92963. * @return true if ready otherwise, false
  92964. */
  92965. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  92966. var material = subMesh.getMaterial();
  92967. if (!material) {
  92968. return false;
  92969. }
  92970. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  92971. return false;
  92972. }
  92973. var defines = [];
  92974. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92975. var mesh = subMesh.getMesh();
  92976. var uv1 = false;
  92977. var uv2 = false;
  92978. // Alpha test
  92979. if (material && material.needAlphaTesting()) {
  92980. var alphaTexture = material.getAlphaTestTexture();
  92981. if (alphaTexture) {
  92982. defines.push("#define ALPHATEST");
  92983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92984. alphaTexture.coordinatesIndex === 1) {
  92985. defines.push("#define DIFFUSEUV2");
  92986. uv2 = true;
  92987. }
  92988. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  92989. defines.push("#define DIFFUSEUV1");
  92990. uv1 = true;
  92991. }
  92992. }
  92993. }
  92994. // Emissive
  92995. if (emissiveTexture) {
  92996. defines.push("#define EMISSIVE");
  92997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  92998. emissiveTexture.coordinatesIndex === 1) {
  92999. defines.push("#define EMISSIVEUV2");
  93000. uv2 = true;
  93001. }
  93002. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  93003. defines.push("#define EMISSIVEUV1");
  93004. uv1 = true;
  93005. }
  93006. }
  93007. if (uv1) {
  93008. attribs.push(BABYLON.VertexBuffer.UVKind);
  93009. defines.push("#define UV1");
  93010. }
  93011. if (uv2) {
  93012. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  93013. defines.push("#define UV2");
  93014. }
  93015. // Bones
  93016. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  93017. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  93018. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  93019. if (mesh.numBoneInfluencers > 4) {
  93020. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  93021. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  93022. }
  93023. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  93024. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  93025. }
  93026. else {
  93027. defines.push("#define NUM_BONE_INFLUENCERS 0");
  93028. }
  93029. // Morph targets
  93030. var manager = mesh.morphTargetManager;
  93031. var morphInfluencers = 0;
  93032. if (manager) {
  93033. if (manager.numInfluencers > 0) {
  93034. defines.push("#define MORPHTARGETS");
  93035. morphInfluencers = manager.numInfluencers;
  93036. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  93037. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  93038. }
  93039. }
  93040. // Instances
  93041. if (useInstances) {
  93042. defines.push("#define INSTANCES");
  93043. attribs.push("world0");
  93044. attribs.push("world1");
  93045. attribs.push("world2");
  93046. attribs.push("world3");
  93047. }
  93048. // Get correct effect
  93049. var join = defines.join("\n");
  93050. if (this._cachedDefines !== join) {
  93051. this._cachedDefines = join;
  93052. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  93053. }
  93054. return this._effectLayerMapGenerationEffect.isReady();
  93055. };
  93056. /**
  93057. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  93058. */
  93059. EffectLayer.prototype.render = function () {
  93060. var currentEffect = this._mergeEffect;
  93061. // Check
  93062. if (!currentEffect.isReady())
  93063. return;
  93064. for (var i = 0; i < this._postProcesses.length; i++) {
  93065. if (!this._postProcesses[i].isReady()) {
  93066. return;
  93067. }
  93068. }
  93069. var engine = this._scene.getEngine();
  93070. this.onBeforeComposeObservable.notifyObservers(this);
  93071. // Render
  93072. engine.enableEffect(currentEffect);
  93073. engine.setState(false);
  93074. // VBOs
  93075. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93076. // Cache
  93077. var previousAlphaMode = engine.getAlphaMode();
  93078. // Go Blend.
  93079. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  93080. // Blends the map on the main canvas.
  93081. this._internalRender(currentEffect);
  93082. // Restore Alpha
  93083. engine.setAlphaMode(previousAlphaMode);
  93084. this.onAfterComposeObservable.notifyObservers(this);
  93085. // Handle size changes.
  93086. var size = this._mainTexture.getSize();
  93087. this._setMainTextureSize();
  93088. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  93089. // Recreate RTT and post processes on size change.
  93090. this.onSizeChangedObservable.notifyObservers(this);
  93091. this._disposeTextureAndPostProcesses();
  93092. this._createMainTexture();
  93093. this._createTextureAndPostProcesses();
  93094. }
  93095. };
  93096. /**
  93097. * Determine if a given mesh will be used in the current effect.
  93098. * @param mesh mesh to test
  93099. * @returns true if the mesh will be used
  93100. */
  93101. EffectLayer.prototype.hasMesh = function (mesh) {
  93102. return true;
  93103. };
  93104. /**
  93105. * Returns true if the layer contains information to display, otherwise false.
  93106. * @returns true if the glow layer should be rendered
  93107. */
  93108. EffectLayer.prototype.shouldRender = function () {
  93109. return this.isEnabled && this._shouldRender;
  93110. };
  93111. /**
  93112. * Returns true if the mesh should render, otherwise false.
  93113. * @param mesh The mesh to render
  93114. * @returns true if it should render otherwise false
  93115. */
  93116. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  93117. return true;
  93118. };
  93119. /**
  93120. * Returns true if the mesh should render, otherwise false.
  93121. * @param mesh The mesh to render
  93122. * @returns true if it should render otherwise false
  93123. */
  93124. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  93125. return true;
  93126. };
  93127. /**
  93128. * Renders the submesh passed in parameter to the generation map.
  93129. */
  93130. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  93131. var _this = this;
  93132. if (!this.shouldRender()) {
  93133. return;
  93134. }
  93135. var material = subMesh.getMaterial();
  93136. var mesh = subMesh.getRenderingMesh();
  93137. var scene = this._scene;
  93138. var engine = scene.getEngine();
  93139. if (!material) {
  93140. return;
  93141. }
  93142. // Do not block in blend mode.
  93143. if (material.needAlphaBlendingForMesh(mesh)) {
  93144. return;
  93145. }
  93146. // Culling
  93147. engine.setState(material.backFaceCulling);
  93148. // Managing instances
  93149. var batch = mesh._getInstancesRenderList(subMesh._id);
  93150. if (batch.mustReturn) {
  93151. return;
  93152. }
  93153. // Early Exit per mesh
  93154. if (!this._shouldRenderMesh(mesh)) {
  93155. return;
  93156. }
  93157. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  93158. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  93159. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  93160. engine.enableEffect(this._effectLayerMapGenerationEffect);
  93161. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  93162. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  93163. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  93164. // Alpha test
  93165. if (material && material.needAlphaTesting()) {
  93166. var alphaTexture = material.getAlphaTestTexture();
  93167. if (alphaTexture) {
  93168. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  93169. var textureMatrix = alphaTexture.getTextureMatrix();
  93170. if (textureMatrix) {
  93171. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  93172. }
  93173. }
  93174. }
  93175. // Glow emissive only
  93176. if (this._emissiveTextureAndColor.texture) {
  93177. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  93178. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  93179. }
  93180. // Bones
  93181. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  93182. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  93183. }
  93184. // Morph targets
  93185. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  93186. // Draw
  93187. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  93188. }
  93189. else {
  93190. // Need to reset refresh rate of the shadowMap
  93191. this._mainTexture.resetRefreshCounter();
  93192. }
  93193. };
  93194. /**
  93195. * Rebuild the required buffers.
  93196. * @hidden Internal use only.
  93197. */
  93198. EffectLayer.prototype._rebuild = function () {
  93199. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93200. if (vb) {
  93201. vb._rebuild();
  93202. }
  93203. this._generateIndexBuffer();
  93204. };
  93205. /**
  93206. * Dispose only the render target textures and post process.
  93207. */
  93208. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  93209. this._mainTexture.dispose();
  93210. for (var i = 0; i < this._postProcesses.length; i++) {
  93211. if (this._postProcesses[i]) {
  93212. this._postProcesses[i].dispose();
  93213. }
  93214. }
  93215. this._postProcesses = [];
  93216. for (var i = 0; i < this._textures.length; i++) {
  93217. if (this._textures[i]) {
  93218. this._textures[i].dispose();
  93219. }
  93220. }
  93221. this._textures = [];
  93222. };
  93223. /**
  93224. * Dispose the highlight layer and free resources.
  93225. */
  93226. EffectLayer.prototype.dispose = function () {
  93227. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93228. if (vertexBuffer) {
  93229. vertexBuffer.dispose();
  93230. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93231. }
  93232. if (this._indexBuffer) {
  93233. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93234. this._indexBuffer = null;
  93235. }
  93236. // Clean textures and post processes
  93237. this._disposeTextureAndPostProcesses();
  93238. // Remove from scene
  93239. var index = this._scene.effectLayers.indexOf(this, 0);
  93240. if (index > -1) {
  93241. this._scene.effectLayers.splice(index, 1);
  93242. }
  93243. // Callback
  93244. this.onDisposeObservable.notifyObservers(this);
  93245. this.onDisposeObservable.clear();
  93246. this.onBeforeRenderMainTextureObservable.clear();
  93247. this.onBeforeComposeObservable.clear();
  93248. this.onAfterComposeObservable.clear();
  93249. this.onSizeChangedObservable.clear();
  93250. };
  93251. /**
  93252. * Gets the class name of the effect layer
  93253. * @returns the string with the class name of the effect layer
  93254. */
  93255. EffectLayer.prototype.getClassName = function () {
  93256. return "EffectLayer";
  93257. };
  93258. /**
  93259. * Creates an effect layer from parsed effect layer data
  93260. * @param parsedEffectLayer defines effect layer data
  93261. * @param scene defines the current scene
  93262. * @param rootUrl defines the root URL containing the effect layer information
  93263. * @returns a parsed effect Layer
  93264. */
  93265. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  93266. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  93267. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  93268. };
  93269. __decorate([
  93270. BABYLON.serialize()
  93271. ], EffectLayer.prototype, "name", void 0);
  93272. __decorate([
  93273. BABYLON.serializeAsColor4()
  93274. ], EffectLayer.prototype, "neutralColor", void 0);
  93275. __decorate([
  93276. BABYLON.serialize()
  93277. ], EffectLayer.prototype, "isEnabled", void 0);
  93278. __decorate([
  93279. BABYLON.serializeAsCameraReference()
  93280. ], EffectLayer.prototype, "camera", null);
  93281. return EffectLayer;
  93282. }());
  93283. BABYLON.EffectLayer = EffectLayer;
  93284. })(BABYLON || (BABYLON = {}));
  93285. //# sourceMappingURL=babylon.effectLayer.js.map
  93286. var BABYLON;
  93287. (function (BABYLON) {
  93288. /**
  93289. * Special Glow Blur post process only blurring the alpha channel
  93290. * It enforces keeping the most luminous color in the color channel.
  93291. */
  93292. var GlowBlurPostProcess = /** @class */ (function (_super) {
  93293. __extends(GlowBlurPostProcess, _super);
  93294. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  93295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  93296. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  93297. _this.direction = direction;
  93298. _this.kernel = kernel;
  93299. _this.onApplyObservable.add(function (effect) {
  93300. effect.setFloat2("screenSize", _this.width, _this.height);
  93301. effect.setVector2("direction", _this.direction);
  93302. effect.setFloat("blurWidth", _this.kernel);
  93303. });
  93304. return _this;
  93305. }
  93306. return GlowBlurPostProcess;
  93307. }(BABYLON.PostProcess));
  93308. /**
  93309. * The highlight layer Helps adding a glow effect around a mesh.
  93310. *
  93311. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93312. * glowy meshes to your scene.
  93313. *
  93314. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  93315. */
  93316. var HighlightLayer = /** @class */ (function (_super) {
  93317. __extends(HighlightLayer, _super);
  93318. /**
  93319. * Instantiates a new highlight Layer and references it to the scene..
  93320. * @param name The name of the layer
  93321. * @param scene The scene to use the layer in
  93322. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  93323. */
  93324. function HighlightLayer(name, scene, options) {
  93325. var _this = _super.call(this, name, scene) || this;
  93326. _this.name = name;
  93327. /**
  93328. * Specifies whether or not the inner glow is ACTIVE in the layer.
  93329. */
  93330. _this.innerGlow = true;
  93331. /**
  93332. * Specifies whether or not the outer glow is ACTIVE in the layer.
  93333. */
  93334. _this.outerGlow = true;
  93335. /**
  93336. * An event triggered when the highlight layer is being blurred.
  93337. */
  93338. _this.onBeforeBlurObservable = new BABYLON.Observable();
  93339. /**
  93340. * An event triggered when the highlight layer has been blurred.
  93341. */
  93342. _this.onAfterBlurObservable = new BABYLON.Observable();
  93343. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  93344. _this._meshes = {};
  93345. _this._excludedMeshes = {};
  93346. _this.neutralColor = HighlightLayer.NeutralColor;
  93347. // Warn on stencil
  93348. if (!_this._engine.isStencilEnable) {
  93349. 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 }");
  93350. }
  93351. // Adapt options
  93352. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  93353. // Initialize the layer
  93354. _this._init({
  93355. alphaBlendingMode: _this._options.alphaBlendingMode,
  93356. camera: _this._options.camera,
  93357. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93358. mainTextureRatio: _this._options.mainTextureRatio
  93359. });
  93360. // Do not render as long as no meshes have been added
  93361. _this._shouldRender = false;
  93362. return _this;
  93363. }
  93364. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  93365. /**
  93366. * Gets the horizontal size of the blur.
  93367. */
  93368. get: function () {
  93369. return this._horizontalBlurPostprocess.kernel;
  93370. },
  93371. /**
  93372. * Specifies the horizontal size of the blur.
  93373. */
  93374. set: function (value) {
  93375. this._horizontalBlurPostprocess.kernel = value;
  93376. },
  93377. enumerable: true,
  93378. configurable: true
  93379. });
  93380. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  93381. /**
  93382. * Gets the vertical size of the blur.
  93383. */
  93384. get: function () {
  93385. return this._verticalBlurPostprocess.kernel;
  93386. },
  93387. /**
  93388. * Specifies the vertical size of the blur.
  93389. */
  93390. set: function (value) {
  93391. this._verticalBlurPostprocess.kernel = value;
  93392. },
  93393. enumerable: true,
  93394. configurable: true
  93395. });
  93396. /**
  93397. * Get the effect name of the layer.
  93398. * @return The effect name
  93399. */
  93400. HighlightLayer.prototype.getEffectName = function () {
  93401. return HighlightLayer.EffectName;
  93402. };
  93403. /**
  93404. * Create the merge effect. This is the shader use to blit the information back
  93405. * to the main canvas at the end of the scene rendering.
  93406. */
  93407. HighlightLayer.prototype._createMergeEffect = function () {
  93408. // Effect
  93409. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  93410. };
  93411. /**
  93412. * Creates the render target textures and post processes used in the highlight layer.
  93413. */
  93414. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  93415. var _this = this;
  93416. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  93417. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  93418. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93419. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93420. var textureType = 0;
  93421. if (this._engine.getCaps().textureHalfFloatRender) {
  93422. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93423. }
  93424. else {
  93425. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93426. }
  93427. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  93428. width: blurTextureWidth,
  93429. height: blurTextureHeight
  93430. }, this._scene, false, true, textureType);
  93431. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93432. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93433. this._blurTexture.anisotropicFilteringLevel = 16;
  93434. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  93435. this._blurTexture.renderParticles = false;
  93436. this._blurTexture.ignoreCameraViewport = true;
  93437. this._textures = [this._blurTexture];
  93438. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  93439. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  93440. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  93441. effect.setTexture("textureSampler", _this._mainTexture);
  93442. });
  93443. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  93444. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  93445. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  93446. });
  93447. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  93448. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  93449. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  93450. });
  93451. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  93452. }
  93453. else {
  93454. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  93455. width: blurTextureWidth,
  93456. height: blurTextureHeight
  93457. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93458. this._horizontalBlurPostprocess.width = blurTextureWidth;
  93459. this._horizontalBlurPostprocess.height = blurTextureHeight;
  93460. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  93461. effect.setTexture("textureSampler", _this._mainTexture);
  93462. });
  93463. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  93464. width: blurTextureWidth,
  93465. height: blurTextureHeight
  93466. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93467. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  93468. }
  93469. this._mainTexture.onAfterUnbindObservable.add(function () {
  93470. _this.onBeforeBlurObservable.notifyObservers(_this);
  93471. var internalTexture = _this._blurTexture.getInternalTexture();
  93472. if (internalTexture) {
  93473. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  93474. }
  93475. _this.onAfterBlurObservable.notifyObservers(_this);
  93476. });
  93477. // Prevent autoClear.
  93478. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  93479. };
  93480. /**
  93481. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  93482. */
  93483. HighlightLayer.prototype.needStencil = function () {
  93484. return true;
  93485. };
  93486. /**
  93487. * Checks for the readiness of the element composing the layer.
  93488. * @param subMesh the mesh to check for
  93489. * @param useInstances specify wether or not to use instances to render the mesh
  93490. * @param emissiveTexture the associated emissive texture used to generate the glow
  93491. * @return true if ready otherwise, false
  93492. */
  93493. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  93494. var material = subMesh.getMaterial();
  93495. var mesh = subMesh.getRenderingMesh();
  93496. if (!material || !mesh || !this._meshes) {
  93497. return false;
  93498. }
  93499. var emissiveTexture = null;
  93500. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  93501. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  93502. emissiveTexture = material.emissiveTexture;
  93503. }
  93504. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  93505. };
  93506. /**
  93507. * Implementation specific of rendering the generating effect on the main canvas.
  93508. * @param effect The effect used to render through
  93509. */
  93510. HighlightLayer.prototype._internalRender = function (effect) {
  93511. // Texture
  93512. effect.setTexture("textureSampler", this._blurTexture);
  93513. // Cache
  93514. var engine = this._engine;
  93515. var previousStencilBuffer = engine.getStencilBuffer();
  93516. var previousStencilFunction = engine.getStencilFunction();
  93517. var previousStencilMask = engine.getStencilMask();
  93518. var previousStencilOperationPass = engine.getStencilOperationPass();
  93519. var previousStencilOperationFail = engine.getStencilOperationFail();
  93520. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  93521. var previousStencilReference = engine.getStencilFunctionReference();
  93522. // Stencil operations
  93523. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  93524. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  93525. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  93526. // Draw order
  93527. engine.setStencilMask(0x00);
  93528. engine.setStencilBuffer(true);
  93529. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  93530. // 2 passes inner outer
  93531. if (this.outerGlow) {
  93532. effect.setFloat("offset", 0);
  93533. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  93534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93535. }
  93536. if (this.innerGlow) {
  93537. effect.setFloat("offset", 1);
  93538. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  93539. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93540. }
  93541. // Restore Cache
  93542. engine.setStencilFunction(previousStencilFunction);
  93543. engine.setStencilMask(previousStencilMask);
  93544. engine.setStencilBuffer(previousStencilBuffer);
  93545. engine.setStencilOperationPass(previousStencilOperationPass);
  93546. engine.setStencilOperationFail(previousStencilOperationFail);
  93547. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  93548. engine.setStencilFunctionReference(previousStencilReference);
  93549. };
  93550. /**
  93551. * Returns true if the layer contains information to display, otherwise false.
  93552. */
  93553. HighlightLayer.prototype.shouldRender = function () {
  93554. if (_super.prototype.shouldRender.call(this)) {
  93555. return this._meshes ? true : false;
  93556. }
  93557. return false;
  93558. };
  93559. /**
  93560. * Returns true if the mesh should render, otherwise false.
  93561. * @param mesh The mesh to render
  93562. * @returns true if it should render otherwise false
  93563. */
  93564. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  93565. // Excluded Mesh
  93566. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  93567. return false;
  93568. }
  93569. ;
  93570. return true;
  93571. };
  93572. /**
  93573. * Sets the required values for both the emissive texture and and the main color.
  93574. */
  93575. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  93576. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  93577. if (highlightLayerMesh) {
  93578. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  93579. }
  93580. else {
  93581. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  93582. }
  93583. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  93584. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  93585. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  93586. }
  93587. else {
  93588. this._emissiveTextureAndColor.texture = null;
  93589. }
  93590. };
  93591. /**
  93592. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  93593. * @param mesh The mesh to exclude from the highlight layer
  93594. */
  93595. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  93596. if (!this._excludedMeshes) {
  93597. return;
  93598. }
  93599. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  93600. if (!meshExcluded) {
  93601. this._excludedMeshes[mesh.uniqueId] = {
  93602. mesh: mesh,
  93603. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  93604. mesh.getEngine().setStencilBuffer(false);
  93605. }),
  93606. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  93607. mesh.getEngine().setStencilBuffer(true);
  93608. }),
  93609. };
  93610. }
  93611. };
  93612. /**
  93613. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  93614. * @param mesh The mesh to highlight
  93615. */
  93616. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  93617. if (!this._excludedMeshes) {
  93618. return;
  93619. }
  93620. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  93621. if (meshExcluded) {
  93622. if (meshExcluded.beforeRender) {
  93623. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  93624. }
  93625. if (meshExcluded.afterRender) {
  93626. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  93627. }
  93628. }
  93629. this._excludedMeshes[mesh.uniqueId] = null;
  93630. };
  93631. /**
  93632. * Determine if a given mesh will be highlighted by the current HighlightLayer
  93633. * @param mesh mesh to test
  93634. * @returns true if the mesh will be highlighted by the current HighlightLayer
  93635. */
  93636. HighlightLayer.prototype.hasMesh = function (mesh) {
  93637. if (!this._meshes) {
  93638. return false;
  93639. }
  93640. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  93641. };
  93642. /**
  93643. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  93644. * @param mesh The mesh to highlight
  93645. * @param color The color of the highlight
  93646. * @param glowEmissiveOnly Extract the glow from the emissive texture
  93647. */
  93648. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  93649. var _this = this;
  93650. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  93651. if (!this._meshes) {
  93652. return;
  93653. }
  93654. var meshHighlight = this._meshes[mesh.uniqueId];
  93655. if (meshHighlight) {
  93656. meshHighlight.color = color;
  93657. }
  93658. else {
  93659. this._meshes[mesh.uniqueId] = {
  93660. mesh: mesh,
  93661. color: color,
  93662. // Lambda required for capture due to Observable this context
  93663. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  93664. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  93665. _this._defaultStencilReference(mesh);
  93666. }
  93667. else {
  93668. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  93669. }
  93670. }),
  93671. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  93672. glowEmissiveOnly: glowEmissiveOnly
  93673. };
  93674. }
  93675. this._shouldRender = true;
  93676. };
  93677. /**
  93678. * Remove a mesh from the highlight layer in order to make it stop glowing.
  93679. * @param mesh The mesh to highlight
  93680. */
  93681. HighlightLayer.prototype.removeMesh = function (mesh) {
  93682. if (!this._meshes) {
  93683. return;
  93684. }
  93685. var meshHighlight = this._meshes[mesh.uniqueId];
  93686. if (meshHighlight) {
  93687. if (meshHighlight.observerHighlight) {
  93688. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  93689. }
  93690. if (meshHighlight.observerDefault) {
  93691. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  93692. }
  93693. delete this._meshes[mesh.uniqueId];
  93694. }
  93695. this._shouldRender = false;
  93696. for (var meshHighlightToCheck in this._meshes) {
  93697. if (this._meshes[meshHighlightToCheck]) {
  93698. this._shouldRender = true;
  93699. break;
  93700. }
  93701. }
  93702. };
  93703. /**
  93704. * Force the stencil to the normal expected value for none glowing parts
  93705. */
  93706. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  93707. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  93708. };
  93709. /**
  93710. * Free any resources and references associated to a mesh.
  93711. * Internal use
  93712. * @param mesh The mesh to free.
  93713. */
  93714. HighlightLayer.prototype._disposeMesh = function (mesh) {
  93715. this.removeMesh(mesh);
  93716. this.removeExcludedMesh(mesh);
  93717. };
  93718. /**
  93719. * Dispose the highlight layer and free resources.
  93720. */
  93721. HighlightLayer.prototype.dispose = function () {
  93722. if (this._meshes) {
  93723. // Clean mesh references
  93724. for (var id in this._meshes) {
  93725. var meshHighlight = this._meshes[id];
  93726. if (meshHighlight && meshHighlight.mesh) {
  93727. if (meshHighlight.observerHighlight) {
  93728. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  93729. }
  93730. if (meshHighlight.observerDefault) {
  93731. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  93732. }
  93733. }
  93734. }
  93735. this._meshes = null;
  93736. }
  93737. if (this._excludedMeshes) {
  93738. for (var id in this._excludedMeshes) {
  93739. var meshHighlight = this._excludedMeshes[id];
  93740. if (meshHighlight) {
  93741. if (meshHighlight.beforeRender) {
  93742. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  93743. }
  93744. if (meshHighlight.afterRender) {
  93745. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  93746. }
  93747. }
  93748. }
  93749. this._excludedMeshes = null;
  93750. }
  93751. _super.prototype.dispose.call(this);
  93752. };
  93753. /**
  93754. * Gets the class name of the effect layer
  93755. * @returns the string with the class name of the effect layer
  93756. */
  93757. HighlightLayer.prototype.getClassName = function () {
  93758. return "HighlightLayer";
  93759. };
  93760. /**
  93761. * Serializes this Highlight layer
  93762. * @returns a serialized Highlight layer object
  93763. */
  93764. HighlightLayer.prototype.serialize = function () {
  93765. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  93766. serializationObject.customType = "BABYLON.HighlightLayer";
  93767. // Highlighted meshes
  93768. serializationObject.meshes = [];
  93769. if (this._meshes) {
  93770. for (var m in this._meshes) {
  93771. var mesh = this._meshes[m];
  93772. if (mesh) {
  93773. serializationObject.meshes.push({
  93774. glowEmissiveOnly: mesh.glowEmissiveOnly,
  93775. color: mesh.color.asArray(),
  93776. meshId: mesh.mesh.id
  93777. });
  93778. }
  93779. }
  93780. }
  93781. // Excluded meshes
  93782. serializationObject.excludedMeshes = [];
  93783. if (this._excludedMeshes) {
  93784. for (var e in this._excludedMeshes) {
  93785. var excludedMesh = this._excludedMeshes[e];
  93786. if (excludedMesh) {
  93787. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  93788. }
  93789. }
  93790. }
  93791. return serializationObject;
  93792. };
  93793. /**
  93794. * Creates a Highlight layer from parsed Highlight layer data
  93795. * @param parsedHightlightLayer defines the Highlight layer data
  93796. * @param scene defines the current scene
  93797. * @param rootUrl defines the root URL containing the Highlight layer information
  93798. * @returns a parsed Highlight layer
  93799. */
  93800. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  93801. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  93802. var index;
  93803. // Excluded meshes
  93804. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  93805. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  93806. if (mesh) {
  93807. hl.addExcludedMesh(mesh);
  93808. }
  93809. }
  93810. // Included meshes
  93811. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  93812. var highlightedMesh = parsedHightlightLayer.meshes[index];
  93813. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  93814. if (mesh) {
  93815. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  93816. }
  93817. }
  93818. return hl;
  93819. };
  93820. /**
  93821. * Effect Name of the highlight layer.
  93822. */
  93823. HighlightLayer.EffectName = "HighlightLayer";
  93824. /**
  93825. * The neutral color used during the preparation of the glow effect.
  93826. * This is black by default as the blend operation is a blend operation.
  93827. */
  93828. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  93829. /**
  93830. * Stencil value used for glowing meshes.
  93831. */
  93832. HighlightLayer.GlowingMeshStencilReference = 0x02;
  93833. /**
  93834. * Stencil value used for the other meshes in the scene.
  93835. */
  93836. HighlightLayer.NormalMeshStencilReference = 0x01;
  93837. __decorate([
  93838. BABYLON.serialize()
  93839. ], HighlightLayer.prototype, "innerGlow", void 0);
  93840. __decorate([
  93841. BABYLON.serialize()
  93842. ], HighlightLayer.prototype, "outerGlow", void 0);
  93843. __decorate([
  93844. BABYLON.serialize()
  93845. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  93846. __decorate([
  93847. BABYLON.serialize()
  93848. ], HighlightLayer.prototype, "blurVerticalSize", null);
  93849. __decorate([
  93850. BABYLON.serialize("options")
  93851. ], HighlightLayer.prototype, "_options", void 0);
  93852. return HighlightLayer;
  93853. }(BABYLON.EffectLayer));
  93854. BABYLON.HighlightLayer = HighlightLayer;
  93855. })(BABYLON || (BABYLON = {}));
  93856. //# sourceMappingURL=babylon.highlightLayer.js.map
  93857. var BABYLON;
  93858. (function (BABYLON) {
  93859. /**
  93860. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  93861. *
  93862. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  93863. * glowy meshes to your scene.
  93864. *
  93865. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  93866. */
  93867. var GlowLayer = /** @class */ (function (_super) {
  93868. __extends(GlowLayer, _super);
  93869. /**
  93870. * Instantiates a new glow Layer and references it to the scene.
  93871. * @param name The name of the layer
  93872. * @param scene The scene to use the layer in
  93873. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  93874. */
  93875. function GlowLayer(name, scene, options) {
  93876. var _this = _super.call(this, name, scene) || this;
  93877. _this._intensity = 1.0;
  93878. _this._includedOnlyMeshes = [];
  93879. _this._excludedMeshes = [];
  93880. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  93881. // Adapt options
  93882. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  93883. // Initialize the layer
  93884. _this._init({
  93885. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  93886. camera: _this._options.camera,
  93887. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  93888. mainTextureRatio: _this._options.mainTextureRatio
  93889. });
  93890. return _this;
  93891. }
  93892. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  93893. /**
  93894. * Gets the kernel size of the blur.
  93895. */
  93896. get: function () {
  93897. return this._horizontalBlurPostprocess1.kernel;
  93898. },
  93899. /**
  93900. * Sets the kernel size of the blur.
  93901. */
  93902. set: function (value) {
  93903. this._horizontalBlurPostprocess1.kernel = value;
  93904. this._verticalBlurPostprocess1.kernel = value;
  93905. this._horizontalBlurPostprocess2.kernel = value;
  93906. this._verticalBlurPostprocess2.kernel = value;
  93907. },
  93908. enumerable: true,
  93909. configurable: true
  93910. });
  93911. Object.defineProperty(GlowLayer.prototype, "intensity", {
  93912. /**
  93913. * Gets the glow intensity.
  93914. */
  93915. get: function () {
  93916. return this._intensity;
  93917. },
  93918. /**
  93919. * Sets the glow intensity.
  93920. */
  93921. set: function (value) {
  93922. this._intensity = value;
  93923. },
  93924. enumerable: true,
  93925. configurable: true
  93926. });
  93927. /**
  93928. * Get the effect name of the layer.
  93929. * @return The effect name
  93930. */
  93931. GlowLayer.prototype.getEffectName = function () {
  93932. return GlowLayer.EffectName;
  93933. };
  93934. /**
  93935. * Create the merge effect. This is the shader use to blit the information back
  93936. * to the main canvas at the end of the scene rendering.
  93937. */
  93938. GlowLayer.prototype._createMergeEffect = function () {
  93939. // Effect
  93940. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  93941. };
  93942. /**
  93943. * Creates the render target textures and post processes used in the glow layer.
  93944. */
  93945. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  93946. var _this = this;
  93947. var blurTextureWidth = this._mainTextureDesiredSize.width;
  93948. var blurTextureHeight = this._mainTextureDesiredSize.height;
  93949. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  93950. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  93951. var textureType = 0;
  93952. if (this._engine.getCaps().textureHalfFloatRender) {
  93953. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93954. }
  93955. else {
  93956. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93957. }
  93958. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  93959. width: blurTextureWidth,
  93960. height: blurTextureHeight
  93961. }, this._scene, false, true, textureType);
  93962. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93963. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93964. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93965. this._blurTexture1.renderParticles = false;
  93966. this._blurTexture1.ignoreCameraViewport = true;
  93967. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  93968. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  93969. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  93970. width: blurTextureWidth2,
  93971. height: blurTextureHeight2
  93972. }, this._scene, false, true, textureType);
  93973. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93974. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93975. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93976. this._blurTexture2.renderParticles = false;
  93977. this._blurTexture2.ignoreCameraViewport = true;
  93978. this._textures = [this._blurTexture1, this._blurTexture2];
  93979. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93980. width: blurTextureWidth,
  93981. height: blurTextureHeight
  93982. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93983. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  93984. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  93985. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  93986. effect.setTexture("textureSampler", _this._mainTexture);
  93987. });
  93988. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  93989. width: blurTextureWidth,
  93990. height: blurTextureHeight
  93991. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93992. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  93993. width: blurTextureWidth2,
  93994. height: blurTextureHeight2
  93995. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  93996. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  93997. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  93998. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  93999. effect.setTexture("textureSampler", _this._blurTexture1);
  94000. });
  94001. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  94002. width: blurTextureWidth2,
  94003. height: blurTextureHeight2
  94004. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  94005. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94006. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  94007. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  94008. this._mainTexture.samples = this._options.mainTextureSamples;
  94009. this._mainTexture.onAfterUnbindObservable.add(function () {
  94010. var internalTexture = _this._blurTexture1.getInternalTexture();
  94011. if (internalTexture) {
  94012. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  94013. internalTexture = _this._blurTexture2.getInternalTexture();
  94014. if (internalTexture) {
  94015. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  94016. }
  94017. }
  94018. });
  94019. // Prevent autoClear.
  94020. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  94021. };
  94022. /**
  94023. * Checks for the readiness of the element composing the layer.
  94024. * @param subMesh the mesh to check for
  94025. * @param useInstances specify wether or not to use instances to render the mesh
  94026. * @param emissiveTexture the associated emissive texture used to generate the glow
  94027. * @return true if ready otherwise, false
  94028. */
  94029. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  94030. var material = subMesh.getMaterial();
  94031. var mesh = subMesh.getRenderingMesh();
  94032. if (!material || !mesh) {
  94033. return false;
  94034. }
  94035. var emissiveTexture = material.emissiveTexture;
  94036. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  94037. };
  94038. /**
  94039. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  94040. */
  94041. GlowLayer.prototype.needStencil = function () {
  94042. return false;
  94043. };
  94044. /**
  94045. * Implementation specific of rendering the generating effect on the main canvas.
  94046. * @param effect The effect used to render through
  94047. */
  94048. GlowLayer.prototype._internalRender = function (effect) {
  94049. // Texture
  94050. effect.setTexture("textureSampler", this._blurTexture1);
  94051. effect.setTexture("textureSampler2", this._blurTexture2);
  94052. effect.setFloat("offset", this._intensity);
  94053. // Cache
  94054. var engine = this._engine;
  94055. var previousStencilBuffer = engine.getStencilBuffer();
  94056. // Draw order
  94057. engine.setStencilBuffer(false);
  94058. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94059. // Draw order
  94060. engine.setStencilBuffer(previousStencilBuffer);
  94061. };
  94062. /**
  94063. * Sets the required values for both the emissive texture and and the main color.
  94064. */
  94065. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  94066. var textureLevel = 1.0;
  94067. if (this.customEmissiveTextureSelector) {
  94068. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  94069. }
  94070. else {
  94071. if (material) {
  94072. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  94073. if (this._emissiveTextureAndColor.texture) {
  94074. textureLevel = this._emissiveTextureAndColor.texture.level;
  94075. }
  94076. }
  94077. else {
  94078. this._emissiveTextureAndColor.texture = null;
  94079. }
  94080. }
  94081. if (this.customEmissiveColorSelector) {
  94082. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  94083. }
  94084. else {
  94085. if (material.emissiveColor) {
  94086. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  94087. }
  94088. else {
  94089. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  94090. }
  94091. }
  94092. };
  94093. /**
  94094. * Returns true if the mesh should render, otherwise false.
  94095. * @param mesh The mesh to render
  94096. * @returns true if it should render otherwise false
  94097. */
  94098. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  94099. return this.hasMesh(mesh);
  94100. };
  94101. /**
  94102. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  94103. * @param mesh The mesh to exclude from the glow layer
  94104. */
  94105. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  94106. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  94107. this._excludedMeshes.push(mesh.uniqueId);
  94108. }
  94109. };
  94110. /**
  94111. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  94112. * @param mesh The mesh to remove
  94113. */
  94114. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  94115. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  94116. if (index !== -1) {
  94117. this._excludedMeshes.splice(index, 1);
  94118. }
  94119. };
  94120. /**
  94121. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  94122. * @param mesh The mesh to include in the glow layer
  94123. */
  94124. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  94125. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  94126. this._includedOnlyMeshes.push(mesh.uniqueId);
  94127. }
  94128. };
  94129. /**
  94130. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  94131. * @param mesh The mesh to remove
  94132. */
  94133. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  94134. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  94135. if (index !== -1) {
  94136. this._includedOnlyMeshes.splice(index, 1);
  94137. }
  94138. };
  94139. /**
  94140. * Determine if a given mesh will be used in the glow layer
  94141. * @param mesh The mesh to test
  94142. * @returns true if the mesh will be highlighted by the current glow layer
  94143. */
  94144. GlowLayer.prototype.hasMesh = function (mesh) {
  94145. // Included Mesh
  94146. if (this._includedOnlyMeshes.length) {
  94147. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  94148. }
  94149. ;
  94150. // Excluded Mesh
  94151. if (this._excludedMeshes.length) {
  94152. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  94153. }
  94154. ;
  94155. return true;
  94156. };
  94157. /**
  94158. * Free any resources and references associated to a mesh.
  94159. * Internal use
  94160. * @param mesh The mesh to free.
  94161. */
  94162. GlowLayer.prototype._disposeMesh = function (mesh) {
  94163. this.removeIncludedOnlyMesh(mesh);
  94164. this.removeExcludedMesh(mesh);
  94165. };
  94166. /**
  94167. * Gets the class name of the effect layer
  94168. * @returns the string with the class name of the effect layer
  94169. */
  94170. GlowLayer.prototype.getClassName = function () {
  94171. return "GlowLayer";
  94172. };
  94173. /**
  94174. * Serializes this glow layer
  94175. * @returns a serialized glow layer object
  94176. */
  94177. GlowLayer.prototype.serialize = function () {
  94178. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  94179. serializationObject.customType = "BABYLON.GlowLayer";
  94180. var index;
  94181. // Included meshes
  94182. serializationObject.includedMeshes = [];
  94183. if (this._includedOnlyMeshes.length) {
  94184. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  94185. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  94186. if (mesh) {
  94187. serializationObject.includedMeshes.push(mesh.id);
  94188. }
  94189. }
  94190. }
  94191. // Excluded meshes
  94192. serializationObject.excludedMeshes = [];
  94193. if (this._excludedMeshes.length) {
  94194. for (index = 0; index < this._excludedMeshes.length; index++) {
  94195. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  94196. if (mesh) {
  94197. serializationObject.excludedMeshes.push(mesh.id);
  94198. }
  94199. }
  94200. }
  94201. return serializationObject;
  94202. };
  94203. /**
  94204. * Creates a Glow Layer from parsed glow layer data
  94205. * @param parsedGlowLayer defines glow layer data
  94206. * @param scene defines the current scene
  94207. * @param rootUrl defines the root URL containing the glow layer information
  94208. * @returns a parsed Glow Layer
  94209. */
  94210. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  94211. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  94212. var index;
  94213. // Excluded meshes
  94214. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  94215. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  94216. if (mesh) {
  94217. gl.addExcludedMesh(mesh);
  94218. }
  94219. }
  94220. // Included meshes
  94221. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  94222. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  94223. if (mesh) {
  94224. gl.addIncludedOnlyMesh(mesh);
  94225. }
  94226. }
  94227. return gl;
  94228. };
  94229. /**
  94230. * Effect Name of the layer.
  94231. */
  94232. GlowLayer.EffectName = "GlowLayer";
  94233. /**
  94234. * The default blur kernel size used for the glow.
  94235. */
  94236. GlowLayer.DefaultBlurKernelSize = 32;
  94237. /**
  94238. * The default texture size ratio used for the glow.
  94239. */
  94240. GlowLayer.DefaultTextureRatio = 0.5;
  94241. __decorate([
  94242. BABYLON.serialize()
  94243. ], GlowLayer.prototype, "blurKernelSize", null);
  94244. __decorate([
  94245. BABYLON.serialize()
  94246. ], GlowLayer.prototype, "intensity", null);
  94247. __decorate([
  94248. BABYLON.serialize("options")
  94249. ], GlowLayer.prototype, "_options", void 0);
  94250. return GlowLayer;
  94251. }(BABYLON.EffectLayer));
  94252. BABYLON.GlowLayer = GlowLayer;
  94253. })(BABYLON || (BABYLON = {}));
  94254. //# sourceMappingURL=babylon.glowLayer.js.map
  94255. var BABYLON;
  94256. (function (BABYLON) {
  94257. /**
  94258. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  94259. */
  94260. var AssetTaskState;
  94261. (function (AssetTaskState) {
  94262. /**
  94263. * Initialization
  94264. */
  94265. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  94266. /**
  94267. * Running
  94268. */
  94269. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  94270. /**
  94271. * Done
  94272. */
  94273. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  94274. /**
  94275. * Error
  94276. */
  94277. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  94278. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  94279. /**
  94280. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  94281. */
  94282. var AbstractAssetTask = /** @class */ (function () {
  94283. /**
  94284. * Creates a new {BABYLON.AssetsManager}
  94285. * @param name defines the name of the task
  94286. */
  94287. function AbstractAssetTask(
  94288. /**
  94289. * Task name
  94290. */ name) {
  94291. this.name = name;
  94292. this._isCompleted = false;
  94293. this._taskState = AssetTaskState.INIT;
  94294. }
  94295. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  94296. /**
  94297. * Get if the task is completed
  94298. */
  94299. get: function () {
  94300. return this._isCompleted;
  94301. },
  94302. enumerable: true,
  94303. configurable: true
  94304. });
  94305. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  94306. /**
  94307. * Gets the current state of the task
  94308. */
  94309. get: function () {
  94310. return this._taskState;
  94311. },
  94312. enumerable: true,
  94313. configurable: true
  94314. });
  94315. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  94316. /**
  94317. * Gets the current error object (if task is in error)
  94318. */
  94319. get: function () {
  94320. return this._errorObject;
  94321. },
  94322. enumerable: true,
  94323. configurable: true
  94324. });
  94325. /**
  94326. * Internal only
  94327. * @hidden
  94328. */
  94329. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  94330. if (this._errorObject) {
  94331. return;
  94332. }
  94333. this._errorObject = {
  94334. message: message,
  94335. exception: exception
  94336. };
  94337. };
  94338. /**
  94339. * Execute the current task
  94340. * @param scene defines the scene where you want your assets to be loaded
  94341. * @param onSuccess is a callback called when the task is successfully executed
  94342. * @param onError is a callback called if an error occurs
  94343. */
  94344. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94345. var _this = this;
  94346. this._taskState = AssetTaskState.RUNNING;
  94347. this.runTask(scene, function () {
  94348. _this.onDoneCallback(onSuccess, onError);
  94349. }, function (msg, exception) {
  94350. _this.onErrorCallback(onError, msg, exception);
  94351. });
  94352. };
  94353. /**
  94354. * Execute the current task
  94355. * @param scene defines the scene where you want your assets to be loaded
  94356. * @param onSuccess is a callback called when the task is successfully executed
  94357. * @param onError is a callback called if an error occurs
  94358. */
  94359. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94360. throw new Error("runTask is not implemented");
  94361. };
  94362. /**
  94363. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  94364. * This can be used with failed tasks that have the reason for failure fixed.
  94365. */
  94366. AbstractAssetTask.prototype.reset = function () {
  94367. this._taskState = AssetTaskState.INIT;
  94368. };
  94369. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  94370. this._taskState = AssetTaskState.ERROR;
  94371. this._errorObject = {
  94372. message: message,
  94373. exception: exception
  94374. };
  94375. if (this.onError) {
  94376. this.onError(this, message, exception);
  94377. }
  94378. onError();
  94379. };
  94380. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  94381. try {
  94382. this._taskState = AssetTaskState.DONE;
  94383. this._isCompleted = true;
  94384. if (this.onSuccess) {
  94385. this.onSuccess(this);
  94386. }
  94387. onSuccess();
  94388. }
  94389. catch (e) {
  94390. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  94391. }
  94392. };
  94393. return AbstractAssetTask;
  94394. }());
  94395. BABYLON.AbstractAssetTask = AbstractAssetTask;
  94396. /**
  94397. * Class used to share progress information about assets loading
  94398. */
  94399. var AssetsProgressEvent = /** @class */ (function () {
  94400. /**
  94401. * Creates a {BABYLON.AssetsProgressEvent}
  94402. * @param remainingCount defines the number of remaining tasks to process
  94403. * @param totalCount defines the total number of tasks
  94404. * @param task defines the task that was just processed
  94405. */
  94406. function AssetsProgressEvent(remainingCount, totalCount, task) {
  94407. this.remainingCount = remainingCount;
  94408. this.totalCount = totalCount;
  94409. this.task = task;
  94410. }
  94411. return AssetsProgressEvent;
  94412. }());
  94413. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  94414. /**
  94415. * Define a task used by {BABYLON.AssetsManager} to load meshes
  94416. */
  94417. var MeshAssetTask = /** @class */ (function (_super) {
  94418. __extends(MeshAssetTask, _super);
  94419. /**
  94420. * Creates a new {BABYLON.MeshAssetTask}
  94421. * @param name defines the name of the task
  94422. * @param meshesNames defines the list of mesh's names you want to load
  94423. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  94424. * @param sceneFilename defines the filename of the scene to load from
  94425. */
  94426. function MeshAssetTask(
  94427. /**
  94428. * Defines the name of the task
  94429. */
  94430. name,
  94431. /**
  94432. * Defines the list of mesh's names you want to load
  94433. */
  94434. meshesNames,
  94435. /**
  94436. * Defines the root url to use as a base to load your meshes and associated resources
  94437. */
  94438. rootUrl,
  94439. /**
  94440. * Defines the filename of the scene to load from
  94441. */
  94442. sceneFilename) {
  94443. var _this = _super.call(this, name) || this;
  94444. _this.name = name;
  94445. _this.meshesNames = meshesNames;
  94446. _this.rootUrl = rootUrl;
  94447. _this.sceneFilename = sceneFilename;
  94448. return _this;
  94449. }
  94450. /**
  94451. * Execute the current task
  94452. * @param scene defines the scene where you want your assets to be loaded
  94453. * @param onSuccess is a callback called when the task is successfully executed
  94454. * @param onError is a callback called if an error occurs
  94455. */
  94456. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94457. var _this = this;
  94458. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  94459. _this.loadedMeshes = meshes;
  94460. _this.loadedParticleSystems = particleSystems;
  94461. _this.loadedSkeletons = skeletons;
  94462. onSuccess();
  94463. }, null, function (scene, message, exception) {
  94464. onError(message, exception);
  94465. });
  94466. };
  94467. return MeshAssetTask;
  94468. }(AbstractAssetTask));
  94469. BABYLON.MeshAssetTask = MeshAssetTask;
  94470. /**
  94471. * Define a task used by {BABYLON.AssetsManager} to load text content
  94472. */
  94473. var TextFileAssetTask = /** @class */ (function (_super) {
  94474. __extends(TextFileAssetTask, _super);
  94475. /**
  94476. * Creates a new TextFileAssetTask object
  94477. * @param name defines the name of the task
  94478. * @param url defines the location of the file to load
  94479. */
  94480. function TextFileAssetTask(
  94481. /**
  94482. * Defines the name of the task
  94483. */
  94484. name,
  94485. /**
  94486. * Defines the location of the file to load
  94487. */
  94488. url) {
  94489. var _this = _super.call(this, name) || this;
  94490. _this.name = name;
  94491. _this.url = url;
  94492. return _this;
  94493. }
  94494. /**
  94495. * Execute the current task
  94496. * @param scene defines the scene where you want your assets to be loaded
  94497. * @param onSuccess is a callback called when the task is successfully executed
  94498. * @param onError is a callback called if an error occurs
  94499. */
  94500. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94501. var _this = this;
  94502. scene._loadFile(this.url, function (data) {
  94503. _this.text = data;
  94504. onSuccess();
  94505. }, undefined, false, false, function (request, exception) {
  94506. if (request) {
  94507. onError(request.status + " " + request.statusText, exception);
  94508. }
  94509. });
  94510. };
  94511. return TextFileAssetTask;
  94512. }(AbstractAssetTask));
  94513. BABYLON.TextFileAssetTask = TextFileAssetTask;
  94514. /**
  94515. * Define a task used by {BABYLON.AssetsManager} to load binary data
  94516. */
  94517. var BinaryFileAssetTask = /** @class */ (function (_super) {
  94518. __extends(BinaryFileAssetTask, _super);
  94519. /**
  94520. * Creates a new BinaryFileAssetTask object
  94521. * @param name defines the name of the new task
  94522. * @param url defines the location of the file to load
  94523. */
  94524. function BinaryFileAssetTask(
  94525. /**
  94526. * Defines the name of the task
  94527. */
  94528. name,
  94529. /**
  94530. * Defines the location of the file to load
  94531. */
  94532. url) {
  94533. var _this = _super.call(this, name) || this;
  94534. _this.name = name;
  94535. _this.url = url;
  94536. return _this;
  94537. }
  94538. /**
  94539. * Execute the current task
  94540. * @param scene defines the scene where you want your assets to be loaded
  94541. * @param onSuccess is a callback called when the task is successfully executed
  94542. * @param onError is a callback called if an error occurs
  94543. */
  94544. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94545. var _this = this;
  94546. scene._loadFile(this.url, function (data) {
  94547. _this.data = data;
  94548. onSuccess();
  94549. }, undefined, true, true, function (request, exception) {
  94550. if (request) {
  94551. onError(request.status + " " + request.statusText, exception);
  94552. }
  94553. });
  94554. };
  94555. return BinaryFileAssetTask;
  94556. }(AbstractAssetTask));
  94557. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  94558. /**
  94559. * Define a task used by {BABYLON.AssetsManager} to load images
  94560. */
  94561. var ImageAssetTask = /** @class */ (function (_super) {
  94562. __extends(ImageAssetTask, _super);
  94563. /**
  94564. * Creates a new ImageAssetTask
  94565. * @param name defines the name of the task
  94566. * @param url defines the location of the image to load
  94567. */
  94568. function ImageAssetTask(
  94569. /**
  94570. * Defines the name of the task
  94571. */
  94572. name,
  94573. /**
  94574. * Defines the location of the image to load
  94575. */
  94576. url) {
  94577. var _this = _super.call(this, name) || this;
  94578. _this.name = name;
  94579. _this.url = url;
  94580. return _this;
  94581. }
  94582. /**
  94583. * Execute the current task
  94584. * @param scene defines the scene where you want your assets to be loaded
  94585. * @param onSuccess is a callback called when the task is successfully executed
  94586. * @param onError is a callback called if an error occurs
  94587. */
  94588. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94589. var _this = this;
  94590. var img = new Image();
  94591. BABYLON.Tools.SetCorsBehavior(this.url, img);
  94592. img.onload = function () {
  94593. _this.image = img;
  94594. onSuccess();
  94595. };
  94596. img.onerror = function (err) {
  94597. onError("Error loading image", err);
  94598. };
  94599. img.src = this.url;
  94600. };
  94601. return ImageAssetTask;
  94602. }(AbstractAssetTask));
  94603. BABYLON.ImageAssetTask = ImageAssetTask;
  94604. /**
  94605. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  94606. */
  94607. var TextureAssetTask = /** @class */ (function (_super) {
  94608. __extends(TextureAssetTask, _super);
  94609. /**
  94610. * Creates a new TextureAssetTask object
  94611. * @param name defines the name of the task
  94612. * @param url defines the location of the file to load
  94613. * @param noMipmap defines if mipmap should not be generated (default is false)
  94614. * @param invertY defines if texture must be inverted on Y axis (default is false)
  94615. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  94616. */
  94617. function TextureAssetTask(
  94618. /**
  94619. * Defines the name of the task
  94620. */
  94621. name,
  94622. /**
  94623. * Defines the location of the file to load
  94624. */
  94625. url,
  94626. /**
  94627. * Defines if mipmap should not be generated (default is false)
  94628. */
  94629. noMipmap,
  94630. /**
  94631. * Defines if texture must be inverted on Y axis (default is false)
  94632. */
  94633. invertY,
  94634. /**
  94635. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  94636. */
  94637. samplingMode) {
  94638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94639. var _this = _super.call(this, name) || this;
  94640. _this.name = name;
  94641. _this.url = url;
  94642. _this.noMipmap = noMipmap;
  94643. _this.invertY = invertY;
  94644. _this.samplingMode = samplingMode;
  94645. return _this;
  94646. }
  94647. /**
  94648. * Execute the current task
  94649. * @param scene defines the scene where you want your assets to be loaded
  94650. * @param onSuccess is a callback called when the task is successfully executed
  94651. * @param onError is a callback called if an error occurs
  94652. */
  94653. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94654. var onload = function () {
  94655. onSuccess();
  94656. };
  94657. var onerror = function (message, exception) {
  94658. onError(message, exception);
  94659. };
  94660. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  94661. };
  94662. return TextureAssetTask;
  94663. }(AbstractAssetTask));
  94664. BABYLON.TextureAssetTask = TextureAssetTask;
  94665. /**
  94666. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  94667. */
  94668. var CubeTextureAssetTask = /** @class */ (function (_super) {
  94669. __extends(CubeTextureAssetTask, _super);
  94670. /**
  94671. * Creates a new CubeTextureAssetTask
  94672. * @param name defines the name of the task
  94673. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  94674. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  94675. * @param noMipmap defines if mipmaps should not be generated (default is false)
  94676. * @param files defines the explicit list of files (undefined by default)
  94677. */
  94678. function CubeTextureAssetTask(
  94679. /**
  94680. * Defines the name of the task
  94681. */
  94682. name,
  94683. /**
  94684. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  94685. */
  94686. url,
  94687. /**
  94688. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  94689. */
  94690. extensions,
  94691. /**
  94692. * Defines if mipmaps should not be generated (default is false)
  94693. */
  94694. noMipmap,
  94695. /**
  94696. * Defines the explicit list of files (undefined by default)
  94697. */
  94698. files) {
  94699. var _this = _super.call(this, name) || this;
  94700. _this.name = name;
  94701. _this.url = url;
  94702. _this.extensions = extensions;
  94703. _this.noMipmap = noMipmap;
  94704. _this.files = files;
  94705. return _this;
  94706. }
  94707. /**
  94708. * Execute the current task
  94709. * @param scene defines the scene where you want your assets to be loaded
  94710. * @param onSuccess is a callback called when the task is successfully executed
  94711. * @param onError is a callback called if an error occurs
  94712. */
  94713. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  94714. var onload = function () {
  94715. onSuccess();
  94716. };
  94717. var onerror = function (message, exception) {
  94718. onError(message, exception);
  94719. };
  94720. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  94721. };
  94722. return CubeTextureAssetTask;
  94723. }(AbstractAssetTask));
  94724. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  94725. /**
  94726. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  94727. */
  94728. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  94729. __extends(HDRCubeTextureAssetTask, _super);
  94730. /**
  94731. * Creates a new HDRCubeTextureAssetTask object
  94732. * @param name defines the name of the task
  94733. * @param url defines the location of the file to load
  94734. * @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.
  94735. * @param noMipmap defines if mipmaps should not be generated (default is false)
  94736. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94737. * @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)
  94738. * @param reserved Internal use only
  94739. */
  94740. function HDRCubeTextureAssetTask(
  94741. /**
  94742. * Defines the name of the task
  94743. */
  94744. name,
  94745. /**
  94746. * Defines the location of the file to load
  94747. */
  94748. url,
  94749. /**
  94750. * Defines the desired size (the more it increases the longer the generation will be)
  94751. */
  94752. size,
  94753. /**
  94754. * Defines if mipmaps should not be generated (default is false)
  94755. */
  94756. noMipmap,
  94757. /**
  94758. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  94759. */
  94760. generateHarmonics,
  94761. /**
  94762. * 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)
  94763. */
  94764. gammaSpace,
  94765. /**
  94766. * Internal Use Only
  94767. */
  94768. reserved) {
  94769. if (noMipmap === void 0) { noMipmap = false; }
  94770. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94771. if (gammaSpace === void 0) { gammaSpace = false; }
  94772. if (reserved === void 0) { reserved = false; }
  94773. var _this = _super.call(this, name) || this;
  94774. _this.name = name;
  94775. _this.url = url;
  94776. _this.size = size;
  94777. _this.noMipmap = noMipmap;
  94778. _this.generateHarmonics = generateHarmonics;
  94779. _this.gammaSpace = gammaSpace;
  94780. _this.reserved = reserved;
  94781. return _this;
  94782. }
  94783. /**
  94784. * Execute the current task
  94785. * @param scene defines the scene where you want your assets to be loaded
  94786. * @param onSuccess is a callback called when the task is successfully executed
  94787. * @param onError is a callback called if an error occurs
  94788. */
  94789. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  94790. var onload = function () {
  94791. onSuccess();
  94792. };
  94793. var onerror = function (message, exception) {
  94794. onError(message, exception);
  94795. };
  94796. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  94797. };
  94798. return HDRCubeTextureAssetTask;
  94799. }(AbstractAssetTask));
  94800. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  94801. /**
  94802. * This class can be used to easily import assets into a scene
  94803. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  94804. */
  94805. var AssetsManager = /** @class */ (function () {
  94806. /**
  94807. * Creates a new AssetsManager
  94808. * @param scene defines the scene to work on
  94809. */
  94810. function AssetsManager(scene) {
  94811. this._isLoading = false;
  94812. this._tasks = new Array();
  94813. this._waitingTasksCount = 0;
  94814. this._totalTasksCount = 0;
  94815. /**
  94816. * Observable called when all tasks are processed
  94817. */
  94818. this.onTaskSuccessObservable = new BABYLON.Observable();
  94819. /**
  94820. * Observable called when a task had an error
  94821. */
  94822. this.onTaskErrorObservable = new BABYLON.Observable();
  94823. /**
  94824. * Observable called when a task is successful
  94825. */
  94826. this.onTasksDoneObservable = new BABYLON.Observable();
  94827. /**
  94828. * Observable called when a task is done (whatever the result is)
  94829. */
  94830. this.onProgressObservable = new BABYLON.Observable();
  94831. /**
  94832. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  94833. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  94834. */
  94835. this.useDefaultLoadingScreen = true;
  94836. this._scene = scene;
  94837. }
  94838. /**
  94839. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  94840. * @param taskName defines the name of the new task
  94841. * @param meshesNames defines the name of meshes to load
  94842. * @param rootUrl defines the root url to use to locate files
  94843. * @param sceneFilename defines the filename of the scene file
  94844. * @returns a new {BABYLON.MeshAssetTask} object
  94845. */
  94846. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  94847. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  94848. this._tasks.push(task);
  94849. return task;
  94850. };
  94851. /**
  94852. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  94853. * @param taskName defines the name of the new task
  94854. * @param url defines the url of the file to load
  94855. * @returns a new {BABYLON.TextFileAssetTask} object
  94856. */
  94857. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  94858. var task = new TextFileAssetTask(taskName, url);
  94859. this._tasks.push(task);
  94860. return task;
  94861. };
  94862. /**
  94863. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  94864. * @param taskName defines the name of the new task
  94865. * @param url defines the url of the file to load
  94866. * @returns a new {BABYLON.BinaryFileAssetTask} object
  94867. */
  94868. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  94869. var task = new BinaryFileAssetTask(taskName, url);
  94870. this._tasks.push(task);
  94871. return task;
  94872. };
  94873. /**
  94874. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  94875. * @param taskName defines the name of the new task
  94876. * @param url defines the url of the file to load
  94877. * @returns a new {BABYLON.ImageAssetTask} object
  94878. */
  94879. AssetsManager.prototype.addImageTask = function (taskName, url) {
  94880. var task = new ImageAssetTask(taskName, url);
  94881. this._tasks.push(task);
  94882. return task;
  94883. };
  94884. /**
  94885. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  94886. * @param taskName defines the name of the new task
  94887. * @param url defines the url of the file to load
  94888. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94889. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  94890. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  94891. * @returns a new {BABYLON.TextureAssetTask} object
  94892. */
  94893. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  94894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94895. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  94896. this._tasks.push(task);
  94897. return task;
  94898. };
  94899. /**
  94900. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  94901. * @param taskName defines the name of the new task
  94902. * @param url defines the url of the file to load
  94903. * @param extensions defines the extension to use to load the cube map (can be null)
  94904. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94905. * @param files defines the list of files to load (can be null)
  94906. * @returns a new {BABYLON.CubeTextureAssetTask} object
  94907. */
  94908. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  94909. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  94910. this._tasks.push(task);
  94911. return task;
  94912. };
  94913. /**
  94914. *
  94915. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  94916. * @param taskName defines the name of the new task
  94917. * @param url defines the url of the file to load
  94918. * @param size defines the size you want for the cubemap (can be null)
  94919. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  94920. * @param generateHarmonics defines if you want to automatically generate (true by default)
  94921. * @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)
  94922. * @param reserved Internal use only
  94923. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  94924. */
  94925. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  94926. if (noMipmap === void 0) { noMipmap = false; }
  94927. if (generateHarmonics === void 0) { generateHarmonics = true; }
  94928. if (gammaSpace === void 0) { gammaSpace = false; }
  94929. if (reserved === void 0) { reserved = false; }
  94930. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  94931. this._tasks.push(task);
  94932. return task;
  94933. };
  94934. /**
  94935. * Remove a task from the assets manager.
  94936. * @param task the task to remove
  94937. */
  94938. AssetsManager.prototype.removeTask = function (task) {
  94939. var index = this._tasks.indexOf(task);
  94940. if (index > -1) {
  94941. this._tasks.splice(index, 1);
  94942. }
  94943. };
  94944. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  94945. this._waitingTasksCount--;
  94946. try {
  94947. if (this.onProgress) {
  94948. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  94949. }
  94950. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  94951. }
  94952. catch (e) {
  94953. BABYLON.Tools.Error("Error running progress callbacks.");
  94954. console.log(e);
  94955. }
  94956. if (this._waitingTasksCount === 0) {
  94957. try {
  94958. if (this.onFinish) {
  94959. this.onFinish(this._tasks);
  94960. }
  94961. // Let's remove successfull tasks
  94962. var currentTasks = this._tasks.slice();
  94963. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  94964. var task = currentTasks_1[_i];
  94965. if (task.taskState === AssetTaskState.DONE) {
  94966. var index = this._tasks.indexOf(task);
  94967. if (index > -1) {
  94968. this._tasks.splice(index, 1);
  94969. }
  94970. }
  94971. }
  94972. this.onTasksDoneObservable.notifyObservers(this._tasks);
  94973. }
  94974. catch (e) {
  94975. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  94976. console.log(e);
  94977. }
  94978. this._isLoading = false;
  94979. this._scene.getEngine().hideLoadingUI();
  94980. }
  94981. };
  94982. AssetsManager.prototype._runTask = function (task) {
  94983. var _this = this;
  94984. var done = function () {
  94985. try {
  94986. if (_this.onTaskSuccess) {
  94987. _this.onTaskSuccess(task);
  94988. }
  94989. _this.onTaskSuccessObservable.notifyObservers(task);
  94990. _this._decreaseWaitingTasksCount(task);
  94991. }
  94992. catch (e) {
  94993. error("Error executing task success callbacks", e);
  94994. }
  94995. };
  94996. var error = function (message, exception) {
  94997. task._setErrorObject(message, exception);
  94998. if (_this.onTaskError) {
  94999. _this.onTaskError(task);
  95000. }
  95001. _this.onTaskErrorObservable.notifyObservers(task);
  95002. _this._decreaseWaitingTasksCount(task);
  95003. };
  95004. task.run(this._scene, done, error);
  95005. };
  95006. /**
  95007. * Reset the {BABYLON.AssetsManager} and remove all tasks
  95008. * @return the current instance of the {BABYLON.AssetsManager}
  95009. */
  95010. AssetsManager.prototype.reset = function () {
  95011. this._isLoading = false;
  95012. this._tasks = new Array();
  95013. return this;
  95014. };
  95015. /**
  95016. * Start the loading process
  95017. * @return the current instance of the {BABYLON.AssetsManager}
  95018. */
  95019. AssetsManager.prototype.load = function () {
  95020. if (this._isLoading) {
  95021. return this;
  95022. }
  95023. this._isLoading = true;
  95024. this._waitingTasksCount = this._tasks.length;
  95025. this._totalTasksCount = this._tasks.length;
  95026. if (this._waitingTasksCount === 0) {
  95027. this._isLoading = false;
  95028. if (this.onFinish) {
  95029. this.onFinish(this._tasks);
  95030. }
  95031. this.onTasksDoneObservable.notifyObservers(this._tasks);
  95032. return this;
  95033. }
  95034. if (this.useDefaultLoadingScreen) {
  95035. this._scene.getEngine().displayLoadingUI();
  95036. }
  95037. for (var index = 0; index < this._tasks.length; index++) {
  95038. var task = this._tasks[index];
  95039. if (task.taskState === AssetTaskState.INIT) {
  95040. this._runTask(task);
  95041. }
  95042. }
  95043. return this;
  95044. };
  95045. return AssetsManager;
  95046. }());
  95047. BABYLON.AssetsManager = AssetsManager;
  95048. })(BABYLON || (BABYLON = {}));
  95049. //# sourceMappingURL=babylon.assetsManager.js.map
  95050. var BABYLON;
  95051. (function (BABYLON) {
  95052. var serializedGeometries = [];
  95053. var serializeGeometry = function (geometry, serializationGeometries) {
  95054. if (serializedGeometries[geometry.id]) {
  95055. return;
  95056. }
  95057. if (geometry.doNotSerialize) {
  95058. return;
  95059. }
  95060. if (geometry instanceof BABYLON.BoxGeometry) {
  95061. serializationGeometries.boxes.push(geometry.serialize());
  95062. }
  95063. else if (geometry instanceof BABYLON.SphereGeometry) {
  95064. serializationGeometries.spheres.push(geometry.serialize());
  95065. }
  95066. else if (geometry instanceof BABYLON.CylinderGeometry) {
  95067. serializationGeometries.cylinders.push(geometry.serialize());
  95068. }
  95069. else if (geometry instanceof BABYLON.TorusGeometry) {
  95070. serializationGeometries.toruses.push(geometry.serialize());
  95071. }
  95072. else if (geometry instanceof BABYLON.GroundGeometry) {
  95073. serializationGeometries.grounds.push(geometry.serialize());
  95074. }
  95075. else if (geometry instanceof BABYLON.Plane) {
  95076. serializationGeometries.planes.push(geometry.serialize());
  95077. }
  95078. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  95079. serializationGeometries.torusKnots.push(geometry.serialize());
  95080. }
  95081. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  95082. throw new Error("Unknown primitive type");
  95083. }
  95084. else {
  95085. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  95086. }
  95087. serializedGeometries[geometry.id] = true;
  95088. };
  95089. var serializeMesh = function (mesh, serializationScene) {
  95090. var serializationObject = {};
  95091. // Geometry
  95092. var geometry = mesh._geometry;
  95093. if (geometry) {
  95094. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  95095. // 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
  95096. serializeGeometry(geometry, serializationScene.geometries);
  95097. }
  95098. }
  95099. // Custom
  95100. if (mesh.serialize) {
  95101. mesh.serialize(serializationObject);
  95102. }
  95103. return serializationObject;
  95104. };
  95105. var finalizeSingleMesh = function (mesh, serializationObject) {
  95106. //only works if the mesh is already loaded
  95107. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95108. //serialize material
  95109. if (mesh.material) {
  95110. if (mesh.material instanceof BABYLON.StandardMaterial) {
  95111. serializationObject.materials = serializationObject.materials || [];
  95112. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95113. serializationObject.materials.push(mesh.material.serialize());
  95114. }
  95115. }
  95116. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  95117. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  95118. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  95119. serializationObject.multiMaterials.push(mesh.material.serialize());
  95120. }
  95121. }
  95122. }
  95123. //serialize geometry
  95124. var geometry = mesh._geometry;
  95125. if (geometry) {
  95126. if (!serializationObject.geometries) {
  95127. serializationObject.geometries = {};
  95128. serializationObject.geometries.boxes = [];
  95129. serializationObject.geometries.spheres = [];
  95130. serializationObject.geometries.cylinders = [];
  95131. serializationObject.geometries.toruses = [];
  95132. serializationObject.geometries.grounds = [];
  95133. serializationObject.geometries.planes = [];
  95134. serializationObject.geometries.torusKnots = [];
  95135. serializationObject.geometries.vertexData = [];
  95136. }
  95137. serializeGeometry(geometry, serializationObject.geometries);
  95138. }
  95139. // Skeletons
  95140. if (mesh.skeleton) {
  95141. serializationObject.skeletons = serializationObject.skeletons || [];
  95142. serializationObject.skeletons.push(mesh.skeleton.serialize());
  95143. }
  95144. //serialize the actual mesh
  95145. serializationObject.meshes = serializationObject.meshes || [];
  95146. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95147. }
  95148. };
  95149. var SceneSerializer = /** @class */ (function () {
  95150. function SceneSerializer() {
  95151. }
  95152. SceneSerializer.ClearCache = function () {
  95153. serializedGeometries = [];
  95154. };
  95155. SceneSerializer.Serialize = function (scene) {
  95156. var serializationObject = {};
  95157. SceneSerializer.ClearCache();
  95158. // Scene
  95159. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  95160. serializationObject.autoClear = scene.autoClear;
  95161. serializationObject.clearColor = scene.clearColor.asArray();
  95162. serializationObject.ambientColor = scene.ambientColor.asArray();
  95163. serializationObject.gravity = scene.gravity.asArray();
  95164. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  95165. serializationObject.workerCollisions = scene.workerCollisions;
  95166. // Fog
  95167. if (scene.fogMode && scene.fogMode !== 0) {
  95168. serializationObject.fogMode = scene.fogMode;
  95169. serializationObject.fogColor = scene.fogColor.asArray();
  95170. serializationObject.fogStart = scene.fogStart;
  95171. serializationObject.fogEnd = scene.fogEnd;
  95172. serializationObject.fogDensity = scene.fogDensity;
  95173. }
  95174. //Physics
  95175. if (scene.isPhysicsEnabled()) {
  95176. var physicEngine = scene.getPhysicsEngine();
  95177. if (physicEngine) {
  95178. serializationObject.physicsEnabled = true;
  95179. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  95180. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  95181. }
  95182. }
  95183. // Metadata
  95184. if (scene.metadata) {
  95185. serializationObject.metadata = scene.metadata;
  95186. }
  95187. // Morph targets
  95188. serializationObject.morphTargetManagers = [];
  95189. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  95190. var abstractMesh = _a[_i];
  95191. var manager = abstractMesh.morphTargetManager;
  95192. if (manager) {
  95193. serializationObject.morphTargetManagers.push(manager.serialize());
  95194. }
  95195. }
  95196. // Lights
  95197. serializationObject.lights = [];
  95198. var index;
  95199. var light;
  95200. for (index = 0; index < scene.lights.length; index++) {
  95201. light = scene.lights[index];
  95202. if (!light.doNotSerialize) {
  95203. serializationObject.lights.push(light.serialize());
  95204. }
  95205. }
  95206. // Cameras
  95207. serializationObject.cameras = [];
  95208. for (index = 0; index < scene.cameras.length; index++) {
  95209. var camera = scene.cameras[index];
  95210. if (!camera.doNotSerialize) {
  95211. serializationObject.cameras.push(camera.serialize());
  95212. }
  95213. }
  95214. if (scene.activeCamera) {
  95215. serializationObject.activeCameraID = scene.activeCamera.id;
  95216. }
  95217. // Animations
  95218. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  95219. // Materials
  95220. serializationObject.materials = [];
  95221. serializationObject.multiMaterials = [];
  95222. var material;
  95223. for (index = 0; index < scene.materials.length; index++) {
  95224. material = scene.materials[index];
  95225. if (!material.doNotSerialize) {
  95226. serializationObject.materials.push(material.serialize());
  95227. }
  95228. }
  95229. // MultiMaterials
  95230. serializationObject.multiMaterials = [];
  95231. for (index = 0; index < scene.multiMaterials.length; index++) {
  95232. var multiMaterial = scene.multiMaterials[index];
  95233. serializationObject.multiMaterials.push(multiMaterial.serialize());
  95234. }
  95235. // Environment texture
  95236. if (scene.environmentTexture) {
  95237. serializationObject.environmentTexture = scene.environmentTexture.name;
  95238. }
  95239. // Skeletons
  95240. serializationObject.skeletons = [];
  95241. for (index = 0; index < scene.skeletons.length; index++) {
  95242. var skeleton = scene.skeletons[index];
  95243. if (!skeleton.doNotSerialize) {
  95244. serializationObject.skeletons.push(skeleton.serialize());
  95245. }
  95246. }
  95247. // Transform nodes
  95248. serializationObject.transformNodes = [];
  95249. for (index = 0; index < scene.transformNodes.length; index++) {
  95250. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  95251. }
  95252. // Geometries
  95253. serializationObject.geometries = {};
  95254. serializationObject.geometries.boxes = [];
  95255. serializationObject.geometries.spheres = [];
  95256. serializationObject.geometries.cylinders = [];
  95257. serializationObject.geometries.toruses = [];
  95258. serializationObject.geometries.grounds = [];
  95259. serializationObject.geometries.planes = [];
  95260. serializationObject.geometries.torusKnots = [];
  95261. serializationObject.geometries.vertexData = [];
  95262. serializedGeometries = [];
  95263. var geometries = scene.getGeometries();
  95264. for (index = 0; index < geometries.length; index++) {
  95265. var geometry = geometries[index];
  95266. if (geometry.isReady()) {
  95267. serializeGeometry(geometry, serializationObject.geometries);
  95268. }
  95269. }
  95270. // Meshes
  95271. serializationObject.meshes = [];
  95272. for (index = 0; index < scene.meshes.length; index++) {
  95273. var abstractMesh = scene.meshes[index];
  95274. if (abstractMesh instanceof BABYLON.Mesh) {
  95275. var mesh = abstractMesh;
  95276. if (!mesh.doNotSerialize) {
  95277. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  95278. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  95279. }
  95280. }
  95281. }
  95282. }
  95283. // Particles Systems
  95284. serializationObject.particleSystems = [];
  95285. for (index = 0; index < scene.particleSystems.length; index++) {
  95286. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  95287. }
  95288. // Lens flares
  95289. serializationObject.lensFlareSystems = [];
  95290. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  95291. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  95292. }
  95293. // Shadows
  95294. serializationObject.shadowGenerators = [];
  95295. for (index = 0; index < scene.lights.length; index++) {
  95296. light = scene.lights[index];
  95297. var shadowGenerator = light.getShadowGenerator();
  95298. if (shadowGenerator) {
  95299. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  95300. }
  95301. }
  95302. // Action Manager
  95303. if (scene.actionManager) {
  95304. serializationObject.actions = scene.actionManager.serialize("scene");
  95305. }
  95306. // Audio
  95307. serializationObject.sounds = [];
  95308. for (index = 0; index < scene.soundTracks.length; index++) {
  95309. var soundtrack = scene.soundTracks[index];
  95310. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  95311. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  95312. }
  95313. }
  95314. // Effect layers
  95315. serializationObject.effectLayers = [];
  95316. for (index = 0; index < scene.effectLayers.length; index++) {
  95317. var layer = scene.effectLayers[index];
  95318. if (layer.serialize) {
  95319. serializationObject.effectLayers.push(layer.serialize());
  95320. }
  95321. }
  95322. return serializationObject;
  95323. };
  95324. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  95325. if (withParents === void 0) { withParents = false; }
  95326. if (withChildren === void 0) { withChildren = false; }
  95327. var serializationObject = {};
  95328. SceneSerializer.ClearCache();
  95329. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  95330. if (withParents || withChildren) {
  95331. //deliberate for loop! not for each, appended should be processed as well.
  95332. for (var i = 0; i < toSerialize.length; ++i) {
  95333. if (withChildren) {
  95334. toSerialize[i].getDescendants().forEach(function (node) {
  95335. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  95336. toSerialize.push(node);
  95337. }
  95338. });
  95339. }
  95340. //make sure the array doesn't contain the object already
  95341. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  95342. toSerialize.push(toSerialize[i].parent);
  95343. }
  95344. }
  95345. }
  95346. toSerialize.forEach(function (mesh) {
  95347. finalizeSingleMesh(mesh, serializationObject);
  95348. });
  95349. return serializationObject;
  95350. };
  95351. return SceneSerializer;
  95352. }());
  95353. BABYLON.SceneSerializer = SceneSerializer;
  95354. })(BABYLON || (BABYLON = {}));
  95355. //# sourceMappingURL=babylon.sceneSerializer.js.map
  95356. var BABYLON;
  95357. (function (BABYLON) {
  95358. var ReflectionProbe = /** @class */ (function () {
  95359. function ReflectionProbe(name, size, scene, generateMipMaps) {
  95360. if (generateMipMaps === void 0) { generateMipMaps = true; }
  95361. var _this = this;
  95362. this.name = name;
  95363. this._viewMatrix = BABYLON.Matrix.Identity();
  95364. this._target = BABYLON.Vector3.Zero();
  95365. this._add = BABYLON.Vector3.Zero();
  95366. this._invertYAxis = false;
  95367. this.position = BABYLON.Vector3.Zero();
  95368. this._scene = scene;
  95369. this._scene.reflectionProbes.push(this);
  95370. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  95371. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  95372. switch (faceIndex) {
  95373. case 0:
  95374. _this._add.copyFromFloats(1, 0, 0);
  95375. break;
  95376. case 1:
  95377. _this._add.copyFromFloats(-1, 0, 0);
  95378. break;
  95379. case 2:
  95380. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  95381. break;
  95382. case 3:
  95383. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  95384. break;
  95385. case 4:
  95386. _this._add.copyFromFloats(0, 0, 1);
  95387. break;
  95388. case 5:
  95389. _this._add.copyFromFloats(0, 0, -1);
  95390. break;
  95391. }
  95392. if (_this._attachedMesh) {
  95393. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  95394. }
  95395. _this.position.addToRef(_this._add, _this._target);
  95396. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  95397. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  95398. scene._forcedViewPosition = _this.position;
  95399. });
  95400. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  95401. scene._forcedViewPosition = null;
  95402. scene.updateTransformMatrix(true);
  95403. });
  95404. if (scene.activeCamera) {
  95405. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  95406. }
  95407. }
  95408. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  95409. get: function () {
  95410. return this._renderTargetTexture.samples;
  95411. },
  95412. set: function (value) {
  95413. this._renderTargetTexture.samples = value;
  95414. },
  95415. enumerable: true,
  95416. configurable: true
  95417. });
  95418. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  95419. get: function () {
  95420. return this._renderTargetTexture.refreshRate;
  95421. },
  95422. set: function (value) {
  95423. this._renderTargetTexture.refreshRate = value;
  95424. },
  95425. enumerable: true,
  95426. configurable: true
  95427. });
  95428. ReflectionProbe.prototype.getScene = function () {
  95429. return this._scene;
  95430. };
  95431. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  95432. get: function () {
  95433. return this._renderTargetTexture;
  95434. },
  95435. enumerable: true,
  95436. configurable: true
  95437. });
  95438. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  95439. get: function () {
  95440. return this._renderTargetTexture.renderList;
  95441. },
  95442. enumerable: true,
  95443. configurable: true
  95444. });
  95445. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  95446. this._attachedMesh = mesh;
  95447. };
  95448. /**
  95449. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  95450. *
  95451. * @param renderingGroupId The rendering group id corresponding to its index
  95452. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  95453. */
  95454. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  95455. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  95456. };
  95457. ReflectionProbe.prototype.dispose = function () {
  95458. var index = this._scene.reflectionProbes.indexOf(this);
  95459. if (index !== -1) {
  95460. // Remove from the scene if found
  95461. this._scene.reflectionProbes.splice(index, 1);
  95462. }
  95463. if (this._renderTargetTexture) {
  95464. this._renderTargetTexture.dispose();
  95465. this._renderTargetTexture = null;
  95466. }
  95467. };
  95468. return ReflectionProbe;
  95469. }());
  95470. BABYLON.ReflectionProbe = ReflectionProbe;
  95471. })(BABYLON || (BABYLON = {}));
  95472. //# sourceMappingURL=babylon.reflectionProbe.js.map
  95473. var BABYLON;
  95474. (function (BABYLON) {
  95475. var Layer = /** @class */ (function () {
  95476. function Layer(name, imgUrl, scene, isBackground, color) {
  95477. this.name = name;
  95478. this.scale = new BABYLON.Vector2(1, 1);
  95479. this.offset = new BABYLON.Vector2(0, 0);
  95480. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  95481. this.layerMask = 0x0FFFFFFF;
  95482. this._vertexBuffers = {};
  95483. // Events
  95484. /**
  95485. * An event triggered when the layer is disposed.
  95486. */
  95487. this.onDisposeObservable = new BABYLON.Observable();
  95488. /**
  95489. * An event triggered before rendering the scene
  95490. */
  95491. this.onBeforeRenderObservable = new BABYLON.Observable();
  95492. /**
  95493. * An event triggered after rendering the scene
  95494. */
  95495. this.onAfterRenderObservable = new BABYLON.Observable();
  95496. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  95497. this.isBackground = isBackground === undefined ? true : isBackground;
  95498. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  95499. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  95500. this._scene.layers.push(this);
  95501. var engine = this._scene.getEngine();
  95502. // VBO
  95503. var vertices = [];
  95504. vertices.push(1, 1);
  95505. vertices.push(-1, 1);
  95506. vertices.push(-1, -1);
  95507. vertices.push(1, -1);
  95508. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95509. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95510. this._createIndexBuffer();
  95511. // Effects
  95512. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  95513. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  95514. }
  95515. Object.defineProperty(Layer.prototype, "onDispose", {
  95516. set: function (callback) {
  95517. if (this._onDisposeObserver) {
  95518. this.onDisposeObservable.remove(this._onDisposeObserver);
  95519. }
  95520. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  95521. },
  95522. enumerable: true,
  95523. configurable: true
  95524. });
  95525. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  95526. set: function (callback) {
  95527. if (this._onBeforeRenderObserver) {
  95528. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  95529. }
  95530. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  95531. },
  95532. enumerable: true,
  95533. configurable: true
  95534. });
  95535. Object.defineProperty(Layer.prototype, "onAfterRender", {
  95536. set: function (callback) {
  95537. if (this._onAfterRenderObserver) {
  95538. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95539. }
  95540. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  95541. },
  95542. enumerable: true,
  95543. configurable: true
  95544. });
  95545. Layer.prototype._createIndexBuffer = function () {
  95546. var engine = this._scene.getEngine();
  95547. // Indices
  95548. var indices = [];
  95549. indices.push(0);
  95550. indices.push(1);
  95551. indices.push(2);
  95552. indices.push(0);
  95553. indices.push(2);
  95554. indices.push(3);
  95555. this._indexBuffer = engine.createIndexBuffer(indices);
  95556. };
  95557. Layer.prototype._rebuild = function () {
  95558. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95559. if (vb) {
  95560. vb._rebuild();
  95561. }
  95562. this._createIndexBuffer();
  95563. };
  95564. Layer.prototype.render = function () {
  95565. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  95566. // Check
  95567. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  95568. return;
  95569. var engine = this._scene.getEngine();
  95570. this.onBeforeRenderObservable.notifyObservers(this);
  95571. // Render
  95572. engine.enableEffect(currentEffect);
  95573. engine.setState(false);
  95574. // Texture
  95575. currentEffect.setTexture("textureSampler", this.texture);
  95576. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  95577. // Color
  95578. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  95579. // Scale / offset
  95580. currentEffect.setVector2("offset", this.offset);
  95581. currentEffect.setVector2("scale", this.scale);
  95582. // VBOs
  95583. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95584. // Draw order
  95585. if (!this.alphaTest) {
  95586. engine.setAlphaMode(this.alphaBlendingMode);
  95587. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95588. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  95589. }
  95590. else {
  95591. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95592. }
  95593. this.onAfterRenderObservable.notifyObservers(this);
  95594. };
  95595. Layer.prototype.dispose = function () {
  95596. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95597. if (vertexBuffer) {
  95598. vertexBuffer.dispose();
  95599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95600. }
  95601. if (this._indexBuffer) {
  95602. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95603. this._indexBuffer = null;
  95604. }
  95605. if (this.texture) {
  95606. this.texture.dispose();
  95607. this.texture = null;
  95608. }
  95609. // Remove from scene
  95610. var index = this._scene.layers.indexOf(this);
  95611. this._scene.layers.splice(index, 1);
  95612. // Callback
  95613. this.onDisposeObservable.notifyObservers(this);
  95614. this.onDisposeObservable.clear();
  95615. this.onAfterRenderObservable.clear();
  95616. this.onBeforeRenderObservable.clear();
  95617. };
  95618. return Layer;
  95619. }());
  95620. BABYLON.Layer = Layer;
  95621. })(BABYLON || (BABYLON = {}));
  95622. //# sourceMappingURL=babylon.layer.js.map
  95623. var BABYLON;
  95624. (function (BABYLON) {
  95625. var TextureTools = /** @class */ (function () {
  95626. function TextureTools() {
  95627. }
  95628. /**
  95629. * Uses the GPU to create a copy texture rescaled at a given size
  95630. * @param texture Texture to copy from
  95631. * @param width Desired width
  95632. * @param height Desired height
  95633. * @return Generated texture
  95634. */
  95635. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  95636. if (useBilinearMode === void 0) { useBilinearMode = true; }
  95637. var scene = texture.getScene();
  95638. var engine = scene.getEngine();
  95639. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  95640. rtt.wrapU = texture.wrapU;
  95641. rtt.wrapV = texture.wrapV;
  95642. rtt.uOffset = texture.uOffset;
  95643. rtt.vOffset = texture.vOffset;
  95644. rtt.uScale = texture.uScale;
  95645. rtt.vScale = texture.vScale;
  95646. rtt.uAng = texture.uAng;
  95647. rtt.vAng = texture.vAng;
  95648. rtt.wAng = texture.wAng;
  95649. rtt.coordinatesIndex = texture.coordinatesIndex;
  95650. rtt.level = texture.level;
  95651. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  95652. rtt._texture.isReady = false;
  95653. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95654. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95655. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95656. passPostProcess.getEffect().executeWhenCompiled(function () {
  95657. passPostProcess.onApply = function (effect) {
  95658. effect.setTexture("textureSampler", texture);
  95659. };
  95660. var internalTexture = rtt.getInternalTexture();
  95661. if (internalTexture) {
  95662. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  95663. engine.unBindFramebuffer(internalTexture);
  95664. rtt.disposeFramebufferObjects();
  95665. passPostProcess.dispose();
  95666. internalTexture.isReady = true;
  95667. }
  95668. });
  95669. return rtt;
  95670. };
  95671. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  95672. if (!scene._environmentBRDFTexture) {
  95673. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95674. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95675. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95676. scene._environmentBRDFTexture = texture;
  95677. }
  95678. return scene._environmentBRDFTexture;
  95679. };
  95680. 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=";
  95681. return TextureTools;
  95682. }());
  95683. BABYLON.TextureTools = TextureTools;
  95684. })(BABYLON || (BABYLON = {}));
  95685. //# sourceMappingURL=babylon.textureTools.js.map
  95686. var BABYLON;
  95687. (function (BABYLON) {
  95688. var FramingBehavior = /** @class */ (function () {
  95689. function FramingBehavior() {
  95690. this._mode = FramingBehavior.FitFrustumSidesMode;
  95691. this._radiusScale = 1.0;
  95692. this._positionScale = 0.5;
  95693. this._defaultElevation = 0.3;
  95694. this._elevationReturnTime = 1500;
  95695. this._elevationReturnWaitTime = 1000;
  95696. this._zoomStopsAnimation = false;
  95697. this._framingTime = 1500;
  95698. this._isPointerDown = false;
  95699. this._lastInteractionTime = -Infinity;
  95700. // Framing control
  95701. this._animatables = new Array();
  95702. this._betaIsAnimating = false;
  95703. }
  95704. Object.defineProperty(FramingBehavior.prototype, "name", {
  95705. get: function () {
  95706. return "Framing";
  95707. },
  95708. enumerable: true,
  95709. configurable: true
  95710. });
  95711. Object.defineProperty(FramingBehavior.prototype, "mode", {
  95712. /**
  95713. * Gets current mode used by the behavior.
  95714. */
  95715. get: function () {
  95716. return this._mode;
  95717. },
  95718. /**
  95719. * Sets the current mode used by the behavior
  95720. */
  95721. set: function (mode) {
  95722. this._mode = mode;
  95723. },
  95724. enumerable: true,
  95725. configurable: true
  95726. });
  95727. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  95728. /**
  95729. * Gets the scale applied to the radius
  95730. */
  95731. get: function () {
  95732. return this._radiusScale;
  95733. },
  95734. /**
  95735. * Sets the scale applied to the radius (1 by default)
  95736. */
  95737. set: function (radius) {
  95738. this._radiusScale = radius;
  95739. },
  95740. enumerable: true,
  95741. configurable: true
  95742. });
  95743. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  95744. /**
  95745. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95746. */
  95747. get: function () {
  95748. return this._positionScale;
  95749. },
  95750. /**
  95751. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  95752. */
  95753. set: function (scale) {
  95754. this._positionScale = scale;
  95755. },
  95756. enumerable: true,
  95757. configurable: true
  95758. });
  95759. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  95760. /**
  95761. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95762. * behaviour is triggered, in radians.
  95763. */
  95764. get: function () {
  95765. return this._defaultElevation;
  95766. },
  95767. /**
  95768. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  95769. * behaviour is triggered, in radians.
  95770. */
  95771. set: function (elevation) {
  95772. this._defaultElevation = elevation;
  95773. },
  95774. enumerable: true,
  95775. configurable: true
  95776. });
  95777. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  95778. /**
  95779. * Gets the time (in milliseconds) taken to return to the default beta position.
  95780. * Negative value indicates camera should not return to default.
  95781. */
  95782. get: function () {
  95783. return this._elevationReturnTime;
  95784. },
  95785. /**
  95786. * Sets the time (in milliseconds) taken to return to the default beta position.
  95787. * Negative value indicates camera should not return to default.
  95788. */
  95789. set: function (speed) {
  95790. this._elevationReturnTime = speed;
  95791. },
  95792. enumerable: true,
  95793. configurable: true
  95794. });
  95795. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  95796. /**
  95797. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95798. */
  95799. get: function () {
  95800. return this._elevationReturnWaitTime;
  95801. },
  95802. /**
  95803. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  95804. */
  95805. set: function (time) {
  95806. this._elevationReturnWaitTime = time;
  95807. },
  95808. enumerable: true,
  95809. configurable: true
  95810. });
  95811. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  95812. /**
  95813. * Gets the flag that indicates if user zooming should stop animation.
  95814. */
  95815. get: function () {
  95816. return this._zoomStopsAnimation;
  95817. },
  95818. /**
  95819. * Sets the flag that indicates if user zooming should stop animation.
  95820. */
  95821. set: function (flag) {
  95822. this._zoomStopsAnimation = flag;
  95823. },
  95824. enumerable: true,
  95825. configurable: true
  95826. });
  95827. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  95828. /**
  95829. * Gets the transition time when framing the mesh, in milliseconds
  95830. */
  95831. get: function () {
  95832. return this._framingTime;
  95833. },
  95834. /**
  95835. * Sets the transition time when framing the mesh, in milliseconds
  95836. */
  95837. set: function (time) {
  95838. this._framingTime = time;
  95839. },
  95840. enumerable: true,
  95841. configurable: true
  95842. });
  95843. FramingBehavior.prototype.init = function () {
  95844. // Do notihng
  95845. };
  95846. FramingBehavior.prototype.attach = function (camera) {
  95847. var _this = this;
  95848. this._attachedCamera = camera;
  95849. var scene = this._attachedCamera.getScene();
  95850. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  95851. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95852. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95853. _this._isPointerDown = true;
  95854. return;
  95855. }
  95856. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95857. _this._isPointerDown = false;
  95858. }
  95859. });
  95860. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  95861. if (mesh) {
  95862. _this.zoomOnMesh(mesh);
  95863. }
  95864. });
  95865. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95866. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95867. _this._applyUserInteraction();
  95868. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  95869. // back to the default position after a given timeout
  95870. _this._maintainCameraAboveGround();
  95871. });
  95872. };
  95873. FramingBehavior.prototype.detach = function () {
  95874. if (!this._attachedCamera) {
  95875. return;
  95876. }
  95877. var scene = this._attachedCamera.getScene();
  95878. if (this._onPrePointerObservableObserver) {
  95879. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95880. }
  95881. if (this._onAfterCheckInputsObserver) {
  95882. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95883. }
  95884. if (this._onMeshTargetChangedObserver) {
  95885. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  95886. }
  95887. this._attachedCamera = null;
  95888. };
  95889. /**
  95890. * Targets the given mesh and updates zoom level accordingly.
  95891. * @param mesh The mesh to target.
  95892. * @param radius Optional. If a cached radius position already exists, overrides default.
  95893. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95894. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95895. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95896. */
  95897. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95898. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95899. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95900. mesh.computeWorldMatrix(true);
  95901. var boundingBox = mesh.getBoundingInfo().boundingBox;
  95902. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  95903. };
  95904. /**
  95905. * Targets the given mesh with its children and updates zoom level accordingly.
  95906. * @param mesh The mesh to target.
  95907. * @param radius Optional. If a cached radius position already exists, overrides default.
  95908. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95909. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95910. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95911. */
  95912. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  95913. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95914. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95915. mesh.computeWorldMatrix(true);
  95916. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  95917. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  95918. };
  95919. /**
  95920. * Targets the given meshes with their children and updates zoom level accordingly.
  95921. * @param meshes The mesh to target.
  95922. * @param radius Optional. If a cached radius position already exists, overrides default.
  95923. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95924. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95925. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95926. */
  95927. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  95928. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95929. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95930. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  95931. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  95932. for (var i = 0; i < meshes.length; i++) {
  95933. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  95934. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  95935. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  95936. }
  95937. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  95938. };
  95939. /**
  95940. * Targets the given mesh and updates zoom level accordingly.
  95941. * @param mesh The mesh to target.
  95942. * @param radius Optional. If a cached radius position already exists, overrides default.
  95943. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  95944. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  95945. * @param onAnimationEnd Callback triggered at the end of the framing animation
  95946. */
  95947. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  95948. var _this = this;
  95949. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  95950. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  95951. var zoomTarget;
  95952. if (!this._attachedCamera) {
  95953. return;
  95954. }
  95955. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  95956. var bottom = minimumWorld.y;
  95957. var top = maximumWorld.y;
  95958. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  95959. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  95960. if (focusOnOriginXZ) {
  95961. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  95962. }
  95963. else {
  95964. var centerWorld = minimumWorld.add(radiusWorld);
  95965. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  95966. }
  95967. if (!this._vectorTransition) {
  95968. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  95969. }
  95970. this._betaIsAnimating = true;
  95971. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  95972. if (animatable) {
  95973. this._animatables.push(animatable);
  95974. }
  95975. // sets the radius and lower radius bounds
  95976. // Small delta ensures camera is not always at lower zoom limit.
  95977. var radius = 0;
  95978. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  95979. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95980. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  95981. radius = position;
  95982. }
  95983. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  95984. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  95985. if (this._attachedCamera.lowerRadiusLimit === null) {
  95986. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  95987. }
  95988. }
  95989. // Set sensibilities
  95990. var extend = maximumWorld.subtract(minimumWorld).length();
  95991. this._attachedCamera.panningSensibility = 5000 / extend;
  95992. this._attachedCamera.wheelPrecision = 100 / radius;
  95993. // transition to new radius
  95994. if (!this._radiusTransition) {
  95995. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  95996. }
  95997. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  95998. _this.stopAllAnimations();
  95999. if (onAnimationEnd) {
  96000. onAnimationEnd();
  96001. }
  96002. if (_this._attachedCamera) {
  96003. _this._attachedCamera.storeState();
  96004. }
  96005. });
  96006. if (animatable) {
  96007. this._animatables.push(animatable);
  96008. }
  96009. };
  96010. /**
  96011. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  96012. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  96013. * frustum width.
  96014. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  96015. * to fully enclose the mesh in the viewing frustum.
  96016. */
  96017. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  96018. var size = maximumWorld.subtract(minimumWorld);
  96019. var boxVectorGlobalDiagonal = size.length();
  96020. var frustumSlope = this._getFrustumSlope();
  96021. // Formula for setting distance
  96022. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  96023. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  96024. // Horizon distance
  96025. var radius = radiusWithoutFraming * this._radiusScale;
  96026. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  96027. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  96028. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  96029. var camera = this._attachedCamera;
  96030. if (!camera) {
  96031. return 0;
  96032. }
  96033. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  96034. // Don't exceed the requested limit
  96035. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  96036. }
  96037. // Don't exceed the upper radius limit
  96038. if (camera.upperRadiusLimit) {
  96039. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  96040. }
  96041. return distance;
  96042. };
  96043. /**
  96044. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  96045. * is automatically returned to its default position (expected to be above ground plane).
  96046. */
  96047. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  96048. var _this = this;
  96049. if (this._elevationReturnTime < 0) {
  96050. return;
  96051. }
  96052. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  96053. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  96054. var limitBeta = Math.PI * 0.5;
  96055. // Bring the camera back up if below the ground plane
  96056. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  96057. this._betaIsAnimating = true;
  96058. //Transition to new position
  96059. this.stopAllAnimations();
  96060. if (!this._betaTransition) {
  96061. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  96062. }
  96063. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  96064. _this._clearAnimationLocks();
  96065. _this.stopAllAnimations();
  96066. });
  96067. if (animatabe) {
  96068. this._animatables.push(animatabe);
  96069. }
  96070. }
  96071. };
  96072. /**
  96073. * Returns the frustum slope based on the canvas ratio and camera FOV
  96074. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  96075. */
  96076. FramingBehavior.prototype._getFrustumSlope = function () {
  96077. // Calculate the viewport ratio
  96078. // Aspect Ratio is Height/Width.
  96079. var camera = this._attachedCamera;
  96080. if (!camera) {
  96081. return BABYLON.Vector2.Zero();
  96082. }
  96083. var engine = camera.getScene().getEngine();
  96084. var aspectRatio = engine.getAspectRatio(camera);
  96085. // Camera FOV is the vertical field of view (top-bottom) in radians.
  96086. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  96087. var frustumSlopeY = Math.tan(camera.fov / 2);
  96088. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  96089. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  96090. // along the forward vector.
  96091. var frustumSlopeX = frustumSlopeY * aspectRatio;
  96092. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  96093. };
  96094. /**
  96095. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  96096. */
  96097. FramingBehavior.prototype._clearAnimationLocks = function () {
  96098. this._betaIsAnimating = false;
  96099. };
  96100. /**
  96101. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96102. */
  96103. FramingBehavior.prototype._applyUserInteraction = function () {
  96104. if (this.isUserIsMoving) {
  96105. this._lastInteractionTime = BABYLON.Tools.Now;
  96106. this.stopAllAnimations();
  96107. this._clearAnimationLocks();
  96108. }
  96109. };
  96110. /**
  96111. * Stops and removes all animations that have been applied to the camera
  96112. */
  96113. FramingBehavior.prototype.stopAllAnimations = function () {
  96114. if (this._attachedCamera) {
  96115. this._attachedCamera.animations = [];
  96116. }
  96117. while (this._animatables.length) {
  96118. if (this._animatables[0]) {
  96119. this._animatables[0].onAnimationEnd = null;
  96120. this._animatables[0].stop();
  96121. }
  96122. this._animatables.shift();
  96123. }
  96124. };
  96125. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  96126. /**
  96127. * Gets a value indicating if the user is moving the camera
  96128. */
  96129. get: function () {
  96130. if (!this._attachedCamera) {
  96131. return false;
  96132. }
  96133. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96134. this._attachedCamera.inertialBetaOffset !== 0 ||
  96135. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96136. this._attachedCamera.inertialPanningX !== 0 ||
  96137. this._attachedCamera.inertialPanningY !== 0 ||
  96138. this._isPointerDown;
  96139. },
  96140. enumerable: true,
  96141. configurable: true
  96142. });
  96143. /**
  96144. * The easing function used by animations
  96145. */
  96146. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  96147. /**
  96148. * The easing mode used by animations
  96149. */
  96150. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  96151. // Statics
  96152. /**
  96153. * The camera can move all the way towards the mesh.
  96154. */
  96155. FramingBehavior.IgnoreBoundsSizeMode = 0;
  96156. /**
  96157. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  96158. */
  96159. FramingBehavior.FitFrustumSidesMode = 1;
  96160. return FramingBehavior;
  96161. }());
  96162. BABYLON.FramingBehavior = FramingBehavior;
  96163. })(BABYLON || (BABYLON = {}));
  96164. //# sourceMappingURL=babylon.framingBehavior.js.map
  96165. var BABYLON;
  96166. (function (BABYLON) {
  96167. /**
  96168. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  96169. */
  96170. var BouncingBehavior = /** @class */ (function () {
  96171. function BouncingBehavior() {
  96172. /**
  96173. * The duration of the animation, in milliseconds
  96174. */
  96175. this.transitionDuration = 450;
  96176. /**
  96177. * Length of the distance animated by the transition when lower radius is reached
  96178. */
  96179. this.lowerRadiusTransitionRange = 2;
  96180. /**
  96181. * Length of the distance animated by the transition when upper radius is reached
  96182. */
  96183. this.upperRadiusTransitionRange = -2;
  96184. this._autoTransitionRange = false;
  96185. // Animations
  96186. this._radiusIsAnimating = false;
  96187. this._radiusBounceTransition = null;
  96188. this._animatables = new Array();
  96189. }
  96190. Object.defineProperty(BouncingBehavior.prototype, "name", {
  96191. get: function () {
  96192. return "Bouncing";
  96193. },
  96194. enumerable: true,
  96195. configurable: true
  96196. });
  96197. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  96198. /**
  96199. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96200. */
  96201. get: function () {
  96202. return this._autoTransitionRange;
  96203. },
  96204. /**
  96205. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  96206. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  96207. */
  96208. set: function (value) {
  96209. var _this = this;
  96210. if (this._autoTransitionRange === value) {
  96211. return;
  96212. }
  96213. this._autoTransitionRange = value;
  96214. var camera = this._attachedCamera;
  96215. if (!camera) {
  96216. return;
  96217. }
  96218. if (value) {
  96219. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  96220. if (!mesh) {
  96221. return;
  96222. }
  96223. mesh.computeWorldMatrix(true);
  96224. var diagonal = mesh.getBoundingInfo().diagonalLength;
  96225. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  96226. _this.upperRadiusTransitionRange = diagonal * 0.05;
  96227. });
  96228. }
  96229. else if (this._onMeshTargetChangedObserver) {
  96230. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96231. }
  96232. },
  96233. enumerable: true,
  96234. configurable: true
  96235. });
  96236. BouncingBehavior.prototype.init = function () {
  96237. // Do notihng
  96238. };
  96239. BouncingBehavior.prototype.attach = function (camera) {
  96240. var _this = this;
  96241. this._attachedCamera = camera;
  96242. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96243. if (!_this._attachedCamera) {
  96244. return;
  96245. }
  96246. // Add the bounce animation to the lower radius limit
  96247. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  96248. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  96249. }
  96250. // Add the bounce animation to the upper radius limit
  96251. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  96252. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  96253. }
  96254. });
  96255. };
  96256. BouncingBehavior.prototype.detach = function () {
  96257. if (!this._attachedCamera) {
  96258. return;
  96259. }
  96260. if (this._onAfterCheckInputsObserver) {
  96261. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96262. }
  96263. if (this._onMeshTargetChangedObserver) {
  96264. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  96265. }
  96266. this._attachedCamera = null;
  96267. };
  96268. /**
  96269. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  96270. * @param radiusLimit The limit to check against.
  96271. * @return Bool to indicate if at limit.
  96272. */
  96273. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  96274. if (!this._attachedCamera) {
  96275. return false;
  96276. }
  96277. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  96278. return true;
  96279. }
  96280. return false;
  96281. };
  96282. /**
  96283. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  96284. * @param radiusDelta The delta by which to animate to. Can be negative.
  96285. */
  96286. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  96287. var _this = this;
  96288. if (!this._attachedCamera) {
  96289. return;
  96290. }
  96291. if (!this._radiusBounceTransition) {
  96292. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  96293. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  96294. }
  96295. // Prevent zoom until bounce has completed
  96296. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  96297. this._attachedCamera.wheelPrecision = Infinity;
  96298. this._attachedCamera.inertialRadiusOffset = 0;
  96299. // Animate to the radius limit
  96300. this.stopAllAnimations();
  96301. this._radiusIsAnimating = true;
  96302. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  96303. if (animatable) {
  96304. this._animatables.push(animatable);
  96305. }
  96306. };
  96307. /**
  96308. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  96309. */
  96310. BouncingBehavior.prototype._clearAnimationLocks = function () {
  96311. this._radiusIsAnimating = false;
  96312. if (this._attachedCamera) {
  96313. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  96314. }
  96315. };
  96316. /**
  96317. * Stops and removes all animations that have been applied to the camera
  96318. */
  96319. BouncingBehavior.prototype.stopAllAnimations = function () {
  96320. if (this._attachedCamera) {
  96321. this._attachedCamera.animations = [];
  96322. }
  96323. while (this._animatables.length) {
  96324. this._animatables[0].onAnimationEnd = null;
  96325. this._animatables[0].stop();
  96326. this._animatables.shift();
  96327. }
  96328. };
  96329. /**
  96330. * The easing function used by animations
  96331. */
  96332. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  96333. /**
  96334. * The easing mode used by animations
  96335. */
  96336. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  96337. return BouncingBehavior;
  96338. }());
  96339. BABYLON.BouncingBehavior = BouncingBehavior;
  96340. })(BABYLON || (BABYLON = {}));
  96341. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  96342. var BABYLON;
  96343. (function (BABYLON) {
  96344. var AutoRotationBehavior = /** @class */ (function () {
  96345. function AutoRotationBehavior() {
  96346. this._zoomStopsAnimation = false;
  96347. this._idleRotationSpeed = 0.05;
  96348. this._idleRotationWaitTime = 2000;
  96349. this._idleRotationSpinupTime = 2000;
  96350. this._isPointerDown = false;
  96351. this._lastFrameTime = null;
  96352. this._lastInteractionTime = -Infinity;
  96353. this._cameraRotationSpeed = 0;
  96354. this._lastFrameRadius = 0;
  96355. }
  96356. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  96357. get: function () {
  96358. return "AutoRotation";
  96359. },
  96360. enumerable: true,
  96361. configurable: true
  96362. });
  96363. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  96364. /**
  96365. * Gets the flag that indicates if user zooming should stop animation.
  96366. */
  96367. get: function () {
  96368. return this._zoomStopsAnimation;
  96369. },
  96370. /**
  96371. * Sets the flag that indicates if user zooming should stop animation.
  96372. */
  96373. set: function (flag) {
  96374. this._zoomStopsAnimation = flag;
  96375. },
  96376. enumerable: true,
  96377. configurable: true
  96378. });
  96379. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  96380. /**
  96381. * Gets the default speed at which the camera rotates around the model.
  96382. */
  96383. get: function () {
  96384. return this._idleRotationSpeed;
  96385. },
  96386. /**
  96387. * Sets the default speed at which the camera rotates around the model.
  96388. */
  96389. set: function (speed) {
  96390. this._idleRotationSpeed = speed;
  96391. },
  96392. enumerable: true,
  96393. configurable: true
  96394. });
  96395. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  96396. /**
  96397. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  96398. */
  96399. get: function () {
  96400. return this._idleRotationWaitTime;
  96401. },
  96402. /**
  96403. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  96404. */
  96405. set: function (time) {
  96406. this._idleRotationWaitTime = time;
  96407. },
  96408. enumerable: true,
  96409. configurable: true
  96410. });
  96411. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  96412. /**
  96413. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  96414. */
  96415. get: function () {
  96416. return this._idleRotationSpinupTime;
  96417. },
  96418. /**
  96419. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  96420. */
  96421. set: function (time) {
  96422. this._idleRotationSpinupTime = time;
  96423. },
  96424. enumerable: true,
  96425. configurable: true
  96426. });
  96427. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  96428. /**
  96429. * Gets a value indicating if the camera is currently rotating because of this behavior
  96430. */
  96431. get: function () {
  96432. return Math.abs(this._cameraRotationSpeed) > 0;
  96433. },
  96434. enumerable: true,
  96435. configurable: true
  96436. });
  96437. AutoRotationBehavior.prototype.init = function () {
  96438. // Do notihng
  96439. };
  96440. AutoRotationBehavior.prototype.attach = function (camera) {
  96441. var _this = this;
  96442. this._attachedCamera = camera;
  96443. var scene = this._attachedCamera.getScene();
  96444. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  96445. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  96446. _this._isPointerDown = true;
  96447. return;
  96448. }
  96449. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  96450. _this._isPointerDown = false;
  96451. }
  96452. });
  96453. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  96454. var now = BABYLON.Tools.Now;
  96455. var dt = 0;
  96456. if (_this._lastFrameTime != null) {
  96457. dt = now - _this._lastFrameTime;
  96458. }
  96459. _this._lastFrameTime = now;
  96460. // Stop the animation if there is user interaction and the animation should stop for this interaction
  96461. _this._applyUserInteraction();
  96462. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  96463. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  96464. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  96465. // Step camera rotation by rotation speed
  96466. if (_this._attachedCamera) {
  96467. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  96468. }
  96469. });
  96470. };
  96471. AutoRotationBehavior.prototype.detach = function () {
  96472. if (!this._attachedCamera) {
  96473. return;
  96474. }
  96475. var scene = this._attachedCamera.getScene();
  96476. if (this._onPrePointerObservableObserver) {
  96477. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  96478. }
  96479. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  96480. this._attachedCamera = null;
  96481. };
  96482. /**
  96483. * Returns true if user is scrolling.
  96484. * @return true if user is scrolling.
  96485. */
  96486. AutoRotationBehavior.prototype._userIsZooming = function () {
  96487. if (!this._attachedCamera) {
  96488. return false;
  96489. }
  96490. return this._attachedCamera.inertialRadiusOffset !== 0;
  96491. };
  96492. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  96493. if (!this._attachedCamera) {
  96494. return false;
  96495. }
  96496. var zoomHasHitLimit = false;
  96497. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  96498. zoomHasHitLimit = true;
  96499. }
  96500. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  96501. this._lastFrameRadius = this._attachedCamera.radius;
  96502. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  96503. };
  96504. /**
  96505. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  96506. */
  96507. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  96508. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  96509. this._lastInteractionTime = BABYLON.Tools.Now;
  96510. }
  96511. };
  96512. // Tools
  96513. AutoRotationBehavior.prototype._userIsMoving = function () {
  96514. if (!this._attachedCamera) {
  96515. return false;
  96516. }
  96517. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  96518. this._attachedCamera.inertialBetaOffset !== 0 ||
  96519. this._attachedCamera.inertialRadiusOffset !== 0 ||
  96520. this._attachedCamera.inertialPanningX !== 0 ||
  96521. this._attachedCamera.inertialPanningY !== 0 ||
  96522. this._isPointerDown;
  96523. };
  96524. return AutoRotationBehavior;
  96525. }());
  96526. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  96527. })(BABYLON || (BABYLON = {}));
  96528. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  96529. var BABYLON;
  96530. (function (BABYLON) {
  96531. var NullEngineOptions = /** @class */ (function () {
  96532. function NullEngineOptions() {
  96533. this.renderWidth = 512;
  96534. this.renderHeight = 256;
  96535. this.textureSize = 512;
  96536. this.deterministicLockstep = false;
  96537. this.lockstepMaxSteps = 4;
  96538. }
  96539. return NullEngineOptions;
  96540. }());
  96541. BABYLON.NullEngineOptions = NullEngineOptions;
  96542. /**
  96543. * The null engine class provides support for headless version of babylon.js.
  96544. * This can be used in server side scenario or for testing purposes
  96545. */
  96546. var NullEngine = /** @class */ (function (_super) {
  96547. __extends(NullEngine, _super);
  96548. function NullEngine(options) {
  96549. if (options === void 0) { options = new NullEngineOptions(); }
  96550. var _this = _super.call(this, null) || this;
  96551. if (options.deterministicLockstep === undefined) {
  96552. options.deterministicLockstep = false;
  96553. }
  96554. if (options.lockstepMaxSteps === undefined) {
  96555. options.lockstepMaxSteps = 4;
  96556. }
  96557. _this._options = options;
  96558. // Init caps
  96559. // We consider we are on a webgl1 capable device
  96560. _this._caps = new BABYLON.EngineCapabilities();
  96561. _this._caps.maxTexturesImageUnits = 16;
  96562. _this._caps.maxVertexTextureImageUnits = 16;
  96563. _this._caps.maxTextureSize = 512;
  96564. _this._caps.maxCubemapTextureSize = 512;
  96565. _this._caps.maxRenderTextureSize = 512;
  96566. _this._caps.maxVertexAttribs = 16;
  96567. _this._caps.maxVaryingVectors = 16;
  96568. _this._caps.maxFragmentUniformVectors = 16;
  96569. _this._caps.maxVertexUniformVectors = 16;
  96570. // Extensions
  96571. _this._caps.standardDerivatives = false;
  96572. _this._caps.astc = null;
  96573. _this._caps.s3tc = null;
  96574. _this._caps.pvrtc = null;
  96575. _this._caps.etc1 = null;
  96576. _this._caps.etc2 = null;
  96577. _this._caps.textureAnisotropicFilterExtension = null;
  96578. _this._caps.maxAnisotropy = 0;
  96579. _this._caps.uintIndices = false;
  96580. _this._caps.fragmentDepthSupported = false;
  96581. _this._caps.highPrecisionShaderSupported = true;
  96582. _this._caps.colorBufferFloat = false;
  96583. _this._caps.textureFloat = false;
  96584. _this._caps.textureFloatLinearFiltering = false;
  96585. _this._caps.textureFloatRender = false;
  96586. _this._caps.textureHalfFloat = false;
  96587. _this._caps.textureHalfFloatLinearFiltering = false;
  96588. _this._caps.textureHalfFloatRender = false;
  96589. _this._caps.textureLOD = false;
  96590. _this._caps.drawBuffersExtension = false;
  96591. _this._caps.depthTextureExtension = false;
  96592. _this._caps.vertexArrayObject = false;
  96593. _this._caps.instancedArrays = false;
  96594. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  96595. // Wrappers
  96596. if (typeof URL === "undefined") {
  96597. URL = {
  96598. createObjectURL: function () { },
  96599. revokeObjectURL: function () { }
  96600. };
  96601. }
  96602. if (typeof Blob === "undefined") {
  96603. Blob = function () { };
  96604. }
  96605. return _this;
  96606. }
  96607. NullEngine.prototype.isDeterministicLockStep = function () {
  96608. return this._options.deterministicLockstep;
  96609. };
  96610. NullEngine.prototype.getLockstepMaxSteps = function () {
  96611. return this._options.lockstepMaxSteps;
  96612. };
  96613. NullEngine.prototype.getHardwareScalingLevel = function () {
  96614. return 1.0;
  96615. };
  96616. NullEngine.prototype.createVertexBuffer = function (vertices) {
  96617. return {
  96618. capacity: 0,
  96619. references: 1,
  96620. is32Bits: false
  96621. };
  96622. };
  96623. NullEngine.prototype.createIndexBuffer = function (indices) {
  96624. return {
  96625. capacity: 0,
  96626. references: 1,
  96627. is32Bits: false
  96628. };
  96629. };
  96630. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  96631. if (stencil === void 0) { stencil = false; }
  96632. };
  96633. NullEngine.prototype.getRenderWidth = function (useScreen) {
  96634. if (useScreen === void 0) { useScreen = false; }
  96635. if (!useScreen && this._currentRenderTarget) {
  96636. return this._currentRenderTarget.width;
  96637. }
  96638. return this._options.renderWidth;
  96639. };
  96640. NullEngine.prototype.getRenderHeight = function (useScreen) {
  96641. if (useScreen === void 0) { useScreen = false; }
  96642. if (!useScreen && this._currentRenderTarget) {
  96643. return this._currentRenderTarget.height;
  96644. }
  96645. return this._options.renderHeight;
  96646. };
  96647. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  96648. this._cachedViewport = viewport;
  96649. };
  96650. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  96651. return {
  96652. transformFeedback: null,
  96653. __SPECTOR_rebuildProgram: null
  96654. };
  96655. };
  96656. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  96657. return [];
  96658. };
  96659. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  96660. return [];
  96661. };
  96662. NullEngine.prototype.bindSamplers = function (effect) {
  96663. this._currentEffect = null;
  96664. };
  96665. NullEngine.prototype.enableEffect = function (effect) {
  96666. this._currentEffect = effect;
  96667. if (effect.onBind) {
  96668. effect.onBind(effect);
  96669. }
  96670. effect.onBindObservable.notifyObservers(effect);
  96671. };
  96672. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  96673. if (zOffset === void 0) { zOffset = 0; }
  96674. if (reverseSide === void 0) { reverseSide = false; }
  96675. };
  96676. NullEngine.prototype.setIntArray = function (uniform, array) {
  96677. };
  96678. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  96679. };
  96680. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  96681. };
  96682. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  96683. };
  96684. NullEngine.prototype.setFloatArray = function (uniform, array) {
  96685. };
  96686. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  96687. };
  96688. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  96689. };
  96690. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  96691. };
  96692. NullEngine.prototype.setArray = function (uniform, array) {
  96693. };
  96694. NullEngine.prototype.setArray2 = function (uniform, array) {
  96695. };
  96696. NullEngine.prototype.setArray3 = function (uniform, array) {
  96697. };
  96698. NullEngine.prototype.setArray4 = function (uniform, array) {
  96699. };
  96700. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  96701. };
  96702. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  96703. };
  96704. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  96705. };
  96706. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  96707. };
  96708. NullEngine.prototype.setFloat = function (uniform, value) {
  96709. };
  96710. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  96711. };
  96712. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  96713. };
  96714. NullEngine.prototype.setBool = function (uniform, bool) {
  96715. };
  96716. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  96717. };
  96718. NullEngine.prototype.setColor3 = function (uniform, color3) {
  96719. };
  96720. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  96721. };
  96722. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  96723. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  96724. if (this._alphaMode === mode) {
  96725. return;
  96726. }
  96727. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  96728. if (!noDepthWriteChange) {
  96729. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  96730. }
  96731. this._alphaMode = mode;
  96732. };
  96733. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  96734. };
  96735. NullEngine.prototype.wipeCaches = function (bruteForce) {
  96736. if (this.preventCacheWipeBetweenFrames) {
  96737. return;
  96738. }
  96739. this.resetTextureCache();
  96740. this._currentEffect = null;
  96741. if (bruteForce) {
  96742. this._currentProgram = null;
  96743. this._stencilState.reset();
  96744. this._depthCullingState.reset();
  96745. this._alphaState.reset();
  96746. }
  96747. this._cachedVertexBuffers = null;
  96748. this._cachedIndexBuffer = null;
  96749. this._cachedEffectForVertexBuffers = null;
  96750. };
  96751. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  96752. };
  96753. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  96754. };
  96755. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  96756. };
  96757. NullEngine.prototype._createTexture = function () {
  96758. return {};
  96759. };
  96760. NullEngine.prototype._releaseTexture = function (texture) {
  96761. };
  96762. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  96763. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96764. if (onLoad === void 0) { onLoad = null; }
  96765. if (onError === void 0) { onError = null; }
  96766. if (buffer === void 0) { buffer = null; }
  96767. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  96768. var url = String(urlArg);
  96769. texture.url = url;
  96770. texture.generateMipMaps = !noMipmap;
  96771. texture.samplingMode = samplingMode;
  96772. texture.invertY = invertY;
  96773. texture.baseWidth = this._options.textureSize;
  96774. texture.baseHeight = this._options.textureSize;
  96775. texture.width = this._options.textureSize;
  96776. texture.height = this._options.textureSize;
  96777. if (format) {
  96778. texture.format = format;
  96779. }
  96780. texture.isReady = true;
  96781. if (onLoad) {
  96782. onLoad();
  96783. }
  96784. this._internalTexturesCache.push(texture);
  96785. return texture;
  96786. };
  96787. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  96788. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  96789. if (options !== undefined && typeof options === "object") {
  96790. fullOptions.generateMipMaps = options.generateMipMaps;
  96791. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  96792. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  96793. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  96794. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  96795. }
  96796. else {
  96797. fullOptions.generateMipMaps = options;
  96798. fullOptions.generateDepthBuffer = true;
  96799. fullOptions.generateStencilBuffer = false;
  96800. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96801. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  96802. }
  96803. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  96804. var width = size.width || size;
  96805. var height = size.height || size;
  96806. texture._depthStencilBuffer = {};
  96807. texture._framebuffer = {};
  96808. texture.baseWidth = width;
  96809. texture.baseHeight = height;
  96810. texture.width = width;
  96811. texture.height = height;
  96812. texture.isReady = true;
  96813. texture.samples = 1;
  96814. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  96815. texture.samplingMode = fullOptions.samplingMode;
  96816. texture.type = fullOptions.type;
  96817. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  96818. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  96819. this._internalTexturesCache.push(texture);
  96820. return texture;
  96821. };
  96822. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  96823. texture.samplingMode = samplingMode;
  96824. };
  96825. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  96826. if (this._currentRenderTarget) {
  96827. this.unBindFramebuffer(this._currentRenderTarget);
  96828. }
  96829. this._currentRenderTarget = texture;
  96830. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  96831. if (this._cachedViewport && !forceFullscreenViewport) {
  96832. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  96833. }
  96834. };
  96835. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  96836. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  96837. this._currentRenderTarget = null;
  96838. if (onBeforeUnbind) {
  96839. if (texture._MSAAFramebuffer) {
  96840. this._currentFramebuffer = texture._framebuffer;
  96841. }
  96842. onBeforeUnbind();
  96843. }
  96844. this._currentFramebuffer = null;
  96845. };
  96846. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  96847. var vbo = {
  96848. capacity: 1,
  96849. references: 1,
  96850. is32Bits: false
  96851. };
  96852. return vbo;
  96853. };
  96854. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  96855. if (offset === void 0) { offset = 0; }
  96856. };
  96857. /**
  96858. * Updates a dynamic vertex buffer.
  96859. * @param vertexBuffer the vertex buffer to update
  96860. * @param data the data used to update the vertex buffer
  96861. * @param byteOffset the byte offset of the data (optional)
  96862. * @param byteLength the byte length of the data (optional)
  96863. */
  96864. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  96865. };
  96866. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  96867. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  96868. this._boundTexturesCache[this._activeChannel] = texture;
  96869. }
  96870. };
  96871. NullEngine.prototype._bindTexture = function (channel, texture) {
  96872. if (channel < 0) {
  96873. return;
  96874. }
  96875. this._bindTextureDirectly(0, texture);
  96876. };
  96877. NullEngine.prototype._releaseBuffer = function (buffer) {
  96878. buffer.references--;
  96879. if (buffer.references === 0) {
  96880. return true;
  96881. }
  96882. return false;
  96883. };
  96884. NullEngine.prototype.releaseEffects = function () {
  96885. };
  96886. return NullEngine;
  96887. }(BABYLON.Engine));
  96888. BABYLON.NullEngine = NullEngine;
  96889. })(BABYLON || (BABYLON = {}));
  96890. //# sourceMappingURL=babylon.nullEngine.js.map
  96891. var BABYLON;
  96892. (function (BABYLON) {
  96893. /**
  96894. * This class can be used to get instrumentation data from a Babylon engine
  96895. */
  96896. var EngineInstrumentation = /** @class */ (function () {
  96897. function EngineInstrumentation(engine) {
  96898. this.engine = engine;
  96899. this._captureGPUFrameTime = false;
  96900. this._gpuFrameTime = new BABYLON.PerfCounter();
  96901. this._captureShaderCompilationTime = false;
  96902. this._shaderCompilationTime = new BABYLON.PerfCounter();
  96903. // Observers
  96904. this._onBeginFrameObserver = null;
  96905. this._onEndFrameObserver = null;
  96906. this._onBeforeShaderCompilationObserver = null;
  96907. this._onAfterShaderCompilationObserver = null;
  96908. }
  96909. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  96910. // Properties
  96911. /**
  96912. * Gets the perf counter used for GPU frame time
  96913. */
  96914. get: function () {
  96915. return this._gpuFrameTime;
  96916. },
  96917. enumerable: true,
  96918. configurable: true
  96919. });
  96920. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  96921. /**
  96922. * Gets the GPU frame time capture status
  96923. */
  96924. get: function () {
  96925. return this._captureGPUFrameTime;
  96926. },
  96927. /**
  96928. * Enable or disable the GPU frame time capture
  96929. */
  96930. set: function (value) {
  96931. var _this = this;
  96932. if (value === this._captureGPUFrameTime) {
  96933. return;
  96934. }
  96935. this._captureGPUFrameTime = value;
  96936. if (value) {
  96937. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  96938. if (!_this._gpuFrameTimeToken) {
  96939. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  96940. }
  96941. });
  96942. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  96943. if (!_this._gpuFrameTimeToken) {
  96944. return;
  96945. }
  96946. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  96947. if (time > -1) {
  96948. _this._gpuFrameTimeToken = null;
  96949. _this._gpuFrameTime.fetchNewFrame();
  96950. _this._gpuFrameTime.addCount(time, true);
  96951. }
  96952. });
  96953. }
  96954. else {
  96955. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  96956. this._onBeginFrameObserver = null;
  96957. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  96958. this._onEndFrameObserver = null;
  96959. }
  96960. },
  96961. enumerable: true,
  96962. configurable: true
  96963. });
  96964. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  96965. /**
  96966. * Gets the perf counter used for shader compilation time
  96967. */
  96968. get: function () {
  96969. return this._shaderCompilationTime;
  96970. },
  96971. enumerable: true,
  96972. configurable: true
  96973. });
  96974. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  96975. /**
  96976. * Gets the shader compilation time capture status
  96977. */
  96978. get: function () {
  96979. return this._captureShaderCompilationTime;
  96980. },
  96981. /**
  96982. * Enable or disable the shader compilation time capture
  96983. */
  96984. set: function (value) {
  96985. var _this = this;
  96986. if (value === this._captureShaderCompilationTime) {
  96987. return;
  96988. }
  96989. this._captureShaderCompilationTime = value;
  96990. if (value) {
  96991. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  96992. _this._shaderCompilationTime.fetchNewFrame();
  96993. _this._shaderCompilationTime.beginMonitoring();
  96994. });
  96995. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  96996. _this._shaderCompilationTime.endMonitoring();
  96997. });
  96998. }
  96999. else {
  97000. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97001. this._onBeforeShaderCompilationObserver = null;
  97002. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97003. this._onAfterShaderCompilationObserver = null;
  97004. }
  97005. },
  97006. enumerable: true,
  97007. configurable: true
  97008. });
  97009. EngineInstrumentation.prototype.dispose = function () {
  97010. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  97011. this._onBeginFrameObserver = null;
  97012. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  97013. this._onEndFrameObserver = null;
  97014. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  97015. this._onBeforeShaderCompilationObserver = null;
  97016. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  97017. this._onAfterShaderCompilationObserver = null;
  97018. this.engine = null;
  97019. };
  97020. return EngineInstrumentation;
  97021. }());
  97022. BABYLON.EngineInstrumentation = EngineInstrumentation;
  97023. })(BABYLON || (BABYLON = {}));
  97024. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  97025. var BABYLON;
  97026. (function (BABYLON) {
  97027. /**
  97028. * This class can be used to get instrumentation data from a Babylon engine
  97029. */
  97030. var SceneInstrumentation = /** @class */ (function () {
  97031. function SceneInstrumentation(scene) {
  97032. var _this = this;
  97033. this.scene = scene;
  97034. this._captureActiveMeshesEvaluationTime = false;
  97035. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  97036. this._captureRenderTargetsRenderTime = false;
  97037. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  97038. this._captureFrameTime = false;
  97039. this._frameTime = new BABYLON.PerfCounter();
  97040. this._captureRenderTime = false;
  97041. this._renderTime = new BABYLON.PerfCounter();
  97042. this._captureInterFrameTime = false;
  97043. this._interFrameTime = new BABYLON.PerfCounter();
  97044. this._captureParticlesRenderTime = false;
  97045. this._particlesRenderTime = new BABYLON.PerfCounter();
  97046. this._captureSpritesRenderTime = false;
  97047. this._spritesRenderTime = new BABYLON.PerfCounter();
  97048. this._capturePhysicsTime = false;
  97049. this._physicsTime = new BABYLON.PerfCounter();
  97050. this._captureAnimationsTime = false;
  97051. this._animationsTime = new BABYLON.PerfCounter();
  97052. // Observers
  97053. this._onBeforeActiveMeshesEvaluationObserver = null;
  97054. this._onAfterActiveMeshesEvaluationObserver = null;
  97055. this._onBeforeRenderTargetsRenderObserver = null;
  97056. this._onAfterRenderTargetsRenderObserver = null;
  97057. this._onAfterRenderObserver = null;
  97058. this._onBeforeDrawPhaseObserver = null;
  97059. this._onAfterDrawPhaseObserver = null;
  97060. this._onBeforeAnimationsObserver = null;
  97061. this._onBeforeParticlesRenderingObserver = null;
  97062. this._onAfterParticlesRenderingObserver = null;
  97063. this._onBeforeSpritesRenderingObserver = null;
  97064. this._onAfterSpritesRenderingObserver = null;
  97065. this._onBeforePhysicsObserver = null;
  97066. this._onAfterPhysicsObserver = null;
  97067. this._onAfterAnimationsObserver = null;
  97068. // Before render
  97069. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  97070. if (_this._captureActiveMeshesEvaluationTime) {
  97071. _this._activeMeshesEvaluationTime.fetchNewFrame();
  97072. }
  97073. if (_this._captureRenderTargetsRenderTime) {
  97074. _this._renderTargetsRenderTime.fetchNewFrame();
  97075. }
  97076. if (_this._captureFrameTime) {
  97077. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  97078. _this._frameTime.beginMonitoring();
  97079. }
  97080. if (_this._captureInterFrameTime) {
  97081. _this._interFrameTime.endMonitoring();
  97082. }
  97083. if (_this._captureParticlesRenderTime) {
  97084. _this._particlesRenderTime.fetchNewFrame();
  97085. }
  97086. if (_this._captureSpritesRenderTime) {
  97087. _this._spritesRenderTime.fetchNewFrame();
  97088. }
  97089. if (_this._captureAnimationsTime) {
  97090. _this._animationsTime.beginMonitoring();
  97091. }
  97092. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  97093. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  97094. });
  97095. // After render
  97096. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  97097. if (_this._captureFrameTime) {
  97098. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  97099. _this._frameTime.endMonitoring();
  97100. }
  97101. if (_this._captureRenderTime) {
  97102. _this._renderTime.endMonitoring(false);
  97103. }
  97104. if (_this._captureInterFrameTime) {
  97105. _this._interFrameTime.beginMonitoring();
  97106. }
  97107. });
  97108. }
  97109. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  97110. // Properties
  97111. /**
  97112. * Gets the perf counter used for active meshes evaluation time
  97113. */
  97114. get: function () {
  97115. return this._activeMeshesEvaluationTime;
  97116. },
  97117. enumerable: true,
  97118. configurable: true
  97119. });
  97120. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  97121. /**
  97122. * Gets the active meshes evaluation time capture status
  97123. */
  97124. get: function () {
  97125. return this._captureActiveMeshesEvaluationTime;
  97126. },
  97127. /**
  97128. * Enable or disable the active meshes evaluation time capture
  97129. */
  97130. set: function (value) {
  97131. var _this = this;
  97132. if (value === this._captureActiveMeshesEvaluationTime) {
  97133. return;
  97134. }
  97135. this._captureActiveMeshesEvaluationTime = value;
  97136. if (value) {
  97137. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  97138. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  97139. _this._activeMeshesEvaluationTime.beginMonitoring();
  97140. });
  97141. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  97142. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  97143. _this._activeMeshesEvaluationTime.endMonitoring();
  97144. });
  97145. }
  97146. else {
  97147. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97148. this._onBeforeActiveMeshesEvaluationObserver = null;
  97149. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97150. this._onAfterActiveMeshesEvaluationObserver = null;
  97151. }
  97152. },
  97153. enumerable: true,
  97154. configurable: true
  97155. });
  97156. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  97157. /**
  97158. * Gets the perf counter used for render targets render time
  97159. */
  97160. get: function () {
  97161. return this._renderTargetsRenderTime;
  97162. },
  97163. enumerable: true,
  97164. configurable: true
  97165. });
  97166. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  97167. /**
  97168. * Gets the render targets render time capture status
  97169. */
  97170. get: function () {
  97171. return this._captureRenderTargetsRenderTime;
  97172. },
  97173. /**
  97174. * Enable or disable the render targets render time capture
  97175. */
  97176. set: function (value) {
  97177. var _this = this;
  97178. if (value === this._captureRenderTargetsRenderTime) {
  97179. return;
  97180. }
  97181. this._captureRenderTargetsRenderTime = value;
  97182. if (value) {
  97183. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  97184. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  97185. _this._renderTargetsRenderTime.beginMonitoring();
  97186. });
  97187. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  97188. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  97189. _this._renderTargetsRenderTime.endMonitoring(false);
  97190. });
  97191. }
  97192. else {
  97193. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97194. this._onBeforeRenderTargetsRenderObserver = null;
  97195. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97196. this._onAfterRenderTargetsRenderObserver = null;
  97197. }
  97198. },
  97199. enumerable: true,
  97200. configurable: true
  97201. });
  97202. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  97203. /**
  97204. * Gets the perf counter used for particles render time
  97205. */
  97206. get: function () {
  97207. return this._particlesRenderTime;
  97208. },
  97209. enumerable: true,
  97210. configurable: true
  97211. });
  97212. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  97213. /**
  97214. * Gets the particles render time capture status
  97215. */
  97216. get: function () {
  97217. return this._captureParticlesRenderTime;
  97218. },
  97219. /**
  97220. * Enable or disable the particles render time capture
  97221. */
  97222. set: function (value) {
  97223. var _this = this;
  97224. if (value === this._captureParticlesRenderTime) {
  97225. return;
  97226. }
  97227. this._captureParticlesRenderTime = value;
  97228. if (value) {
  97229. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  97230. BABYLON.Tools.StartPerformanceCounter("Particles");
  97231. _this._particlesRenderTime.beginMonitoring();
  97232. });
  97233. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  97234. BABYLON.Tools.EndPerformanceCounter("Particles");
  97235. _this._particlesRenderTime.endMonitoring(false);
  97236. });
  97237. }
  97238. else {
  97239. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97240. this._onBeforeParticlesRenderingObserver = null;
  97241. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97242. this._onAfterParticlesRenderingObserver = null;
  97243. }
  97244. },
  97245. enumerable: true,
  97246. configurable: true
  97247. });
  97248. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  97249. /**
  97250. * Gets the perf counter used for sprites render time
  97251. */
  97252. get: function () {
  97253. return this._spritesRenderTime;
  97254. },
  97255. enumerable: true,
  97256. configurable: true
  97257. });
  97258. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  97259. /**
  97260. * Gets the sprites render time capture status
  97261. */
  97262. get: function () {
  97263. return this._captureSpritesRenderTime;
  97264. },
  97265. /**
  97266. * Enable or disable the sprites render time capture
  97267. */
  97268. set: function (value) {
  97269. var _this = this;
  97270. if (value === this._captureSpritesRenderTime) {
  97271. return;
  97272. }
  97273. this._captureSpritesRenderTime = value;
  97274. if (value) {
  97275. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  97276. BABYLON.Tools.StartPerformanceCounter("Sprites");
  97277. _this._spritesRenderTime.beginMonitoring();
  97278. });
  97279. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  97280. BABYLON.Tools.EndPerformanceCounter("Sprites");
  97281. _this._spritesRenderTime.endMonitoring(false);
  97282. });
  97283. }
  97284. else {
  97285. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97286. this._onBeforeSpritesRenderingObserver = null;
  97287. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97288. this._onAfterSpritesRenderingObserver = null;
  97289. }
  97290. },
  97291. enumerable: true,
  97292. configurable: true
  97293. });
  97294. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  97295. /**
  97296. * Gets the perf counter used for physics time
  97297. */
  97298. get: function () {
  97299. return this._physicsTime;
  97300. },
  97301. enumerable: true,
  97302. configurable: true
  97303. });
  97304. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  97305. /**
  97306. * Gets the physics time capture status
  97307. */
  97308. get: function () {
  97309. return this._capturePhysicsTime;
  97310. },
  97311. /**
  97312. * Enable or disable the physics time capture
  97313. */
  97314. set: function (value) {
  97315. var _this = this;
  97316. if (value === this._capturePhysicsTime) {
  97317. return;
  97318. }
  97319. this._capturePhysicsTime = value;
  97320. if (value) {
  97321. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  97322. BABYLON.Tools.StartPerformanceCounter("Physics");
  97323. _this._physicsTime.beginMonitoring();
  97324. });
  97325. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  97326. BABYLON.Tools.EndPerformanceCounter("Physics");
  97327. _this._physicsTime.endMonitoring();
  97328. });
  97329. }
  97330. else {
  97331. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  97332. this._onBeforePhysicsObserver = null;
  97333. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  97334. this._onAfterPhysicsObserver = null;
  97335. }
  97336. },
  97337. enumerable: true,
  97338. configurable: true
  97339. });
  97340. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  97341. /**
  97342. * Gets the perf counter used for animations time
  97343. */
  97344. get: function () {
  97345. return this._animationsTime;
  97346. },
  97347. enumerable: true,
  97348. configurable: true
  97349. });
  97350. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  97351. /**
  97352. * Gets the animations time capture status
  97353. */
  97354. get: function () {
  97355. return this._captureAnimationsTime;
  97356. },
  97357. /**
  97358. * Enable or disable the animations time capture
  97359. */
  97360. set: function (value) {
  97361. var _this = this;
  97362. if (value === this._captureAnimationsTime) {
  97363. return;
  97364. }
  97365. this._captureAnimationsTime = value;
  97366. if (value) {
  97367. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  97368. _this._animationsTime.endMonitoring();
  97369. });
  97370. }
  97371. else {
  97372. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  97373. this._onAfterAnimationsObserver = null;
  97374. }
  97375. },
  97376. enumerable: true,
  97377. configurable: true
  97378. });
  97379. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  97380. /**
  97381. * Gets the perf counter used for frame time capture
  97382. */
  97383. get: function () {
  97384. return this._frameTime;
  97385. },
  97386. enumerable: true,
  97387. configurable: true
  97388. });
  97389. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  97390. /**
  97391. * Gets the frame time capture status
  97392. */
  97393. get: function () {
  97394. return this._captureFrameTime;
  97395. },
  97396. /**
  97397. * Enable or disable the frame time capture
  97398. */
  97399. set: function (value) {
  97400. this._captureFrameTime = value;
  97401. },
  97402. enumerable: true,
  97403. configurable: true
  97404. });
  97405. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  97406. /**
  97407. * Gets the perf counter used for inter-frames time capture
  97408. */
  97409. get: function () {
  97410. return this._interFrameTime;
  97411. },
  97412. enumerable: true,
  97413. configurable: true
  97414. });
  97415. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  97416. /**
  97417. * Gets the inter-frames time capture status
  97418. */
  97419. get: function () {
  97420. return this._captureInterFrameTime;
  97421. },
  97422. /**
  97423. * Enable or disable the inter-frames time capture
  97424. */
  97425. set: function (value) {
  97426. this._captureInterFrameTime = value;
  97427. },
  97428. enumerable: true,
  97429. configurable: true
  97430. });
  97431. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  97432. /**
  97433. * Gets the perf counter used for render time capture
  97434. */
  97435. get: function () {
  97436. return this._renderTime;
  97437. },
  97438. enumerable: true,
  97439. configurable: true
  97440. });
  97441. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  97442. /**
  97443. * Gets the render time capture status
  97444. */
  97445. get: function () {
  97446. return this._captureRenderTime;
  97447. },
  97448. /**
  97449. * Enable or disable the render time capture
  97450. */
  97451. set: function (value) {
  97452. var _this = this;
  97453. if (value === this._captureRenderTime) {
  97454. return;
  97455. }
  97456. this._captureRenderTime = value;
  97457. if (value) {
  97458. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  97459. _this._renderTime.beginMonitoring();
  97460. BABYLON.Tools.StartPerformanceCounter("Main render");
  97461. });
  97462. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  97463. _this._renderTime.endMonitoring(false);
  97464. BABYLON.Tools.EndPerformanceCounter("Main render");
  97465. });
  97466. }
  97467. else {
  97468. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  97469. this._onBeforeDrawPhaseObserver = null;
  97470. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  97471. this._onAfterDrawPhaseObserver = null;
  97472. }
  97473. },
  97474. enumerable: true,
  97475. configurable: true
  97476. });
  97477. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  97478. /**
  97479. * Gets the perf counter used for draw calls
  97480. */
  97481. get: function () {
  97482. return this.scene.getEngine()._drawCalls;
  97483. },
  97484. enumerable: true,
  97485. configurable: true
  97486. });
  97487. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  97488. /**
  97489. * Gets the perf counter used for texture collisions
  97490. */
  97491. get: function () {
  97492. return this.scene.getEngine()._textureCollisions;
  97493. },
  97494. enumerable: true,
  97495. configurable: true
  97496. });
  97497. SceneInstrumentation.prototype.dispose = function () {
  97498. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97499. this._onAfterRenderObserver = null;
  97500. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  97501. this._onBeforeActiveMeshesEvaluationObserver = null;
  97502. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  97503. this._onAfterActiveMeshesEvaluationObserver = null;
  97504. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  97505. this._onBeforeRenderTargetsRenderObserver = null;
  97506. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  97507. this._onAfterRenderTargetsRenderObserver = null;
  97508. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  97509. this._onBeforeAnimationsObserver = null;
  97510. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  97511. this._onBeforeParticlesRenderingObserver = null;
  97512. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  97513. this._onAfterParticlesRenderingObserver = null;
  97514. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  97515. this._onBeforeSpritesRenderingObserver = null;
  97516. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  97517. this._onAfterSpritesRenderingObserver = null;
  97518. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  97519. this._onBeforeDrawPhaseObserver = null;
  97520. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  97521. this._onAfterDrawPhaseObserver = null;
  97522. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  97523. this._onBeforePhysicsObserver = null;
  97524. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  97525. this._onAfterPhysicsObserver = null;
  97526. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  97527. this._onAfterAnimationsObserver = null;
  97528. this.scene = null;
  97529. };
  97530. return SceneInstrumentation;
  97531. }());
  97532. BABYLON.SceneInstrumentation = SceneInstrumentation;
  97533. })(BABYLON || (BABYLON = {}));
  97534. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  97535. var BABYLON;
  97536. (function (BABYLON) {
  97537. /**
  97538. * @hidden
  97539. **/
  97540. var _TimeToken = /** @class */ (function () {
  97541. function _TimeToken() {
  97542. this._timeElapsedQueryEnded = false;
  97543. }
  97544. return _TimeToken;
  97545. }());
  97546. BABYLON._TimeToken = _TimeToken;
  97547. })(BABYLON || (BABYLON = {}));
  97548. //# sourceMappingURL=babylon.timeToken.js.map
  97549. var BABYLON;
  97550. (function (BABYLON) {
  97551. /**
  97552. * Background material defines definition.
  97553. * @hidden Mainly internal Use
  97554. */
  97555. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  97556. __extends(BackgroundMaterialDefines, _super);
  97557. /**
  97558. * Constructor of the defines.
  97559. */
  97560. function BackgroundMaterialDefines() {
  97561. var _this = _super.call(this) || this;
  97562. /**
  97563. * True if the diffuse texture is in use.
  97564. */
  97565. _this.DIFFUSE = false;
  97566. /**
  97567. * The direct UV channel to use.
  97568. */
  97569. _this.DIFFUSEDIRECTUV = 0;
  97570. /**
  97571. * True if the diffuse texture is in gamma space.
  97572. */
  97573. _this.GAMMADIFFUSE = false;
  97574. /**
  97575. * True if the diffuse texture has opacity in the alpha channel.
  97576. */
  97577. _this.DIFFUSEHASALPHA = false;
  97578. /**
  97579. * True if you want the material to fade to transparent at grazing angle.
  97580. */
  97581. _this.OPACITYFRESNEL = false;
  97582. /**
  97583. * True if an extra blur needs to be added in the reflection.
  97584. */
  97585. _this.REFLECTIONBLUR = false;
  97586. /**
  97587. * True if you want the material to fade to reflection at grazing angle.
  97588. */
  97589. _this.REFLECTIONFRESNEL = false;
  97590. /**
  97591. * True if you want the material to falloff as far as you move away from the scene center.
  97592. */
  97593. _this.REFLECTIONFALLOFF = false;
  97594. /**
  97595. * False if the current Webgl implementation does not support the texture lod extension.
  97596. */
  97597. _this.TEXTURELODSUPPORT = false;
  97598. /**
  97599. * True to ensure the data are premultiplied.
  97600. */
  97601. _this.PREMULTIPLYALPHA = false;
  97602. /**
  97603. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  97604. */
  97605. _this.USERGBCOLOR = false;
  97606. /**
  97607. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  97608. * stays aligned with the desired configuration.
  97609. */
  97610. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  97611. /**
  97612. * True to add noise in order to reduce the banding effect.
  97613. */
  97614. _this.NOISE = false;
  97615. /**
  97616. * is the reflection texture in BGR color scheme?
  97617. * Mainly used to solve a bug in ios10 video tag
  97618. */
  97619. _this.REFLECTIONBGR = false;
  97620. _this.IMAGEPROCESSING = false;
  97621. _this.VIGNETTE = false;
  97622. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  97623. _this.VIGNETTEBLENDMODEOPAQUE = false;
  97624. _this.TONEMAPPING = false;
  97625. _this.CONTRAST = false;
  97626. _this.COLORCURVES = false;
  97627. _this.COLORGRADING = false;
  97628. _this.COLORGRADING3D = false;
  97629. _this.SAMPLER3DGREENDEPTH = false;
  97630. _this.SAMPLER3DBGRMAP = false;
  97631. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  97632. _this.EXPOSURE = false;
  97633. // Reflection.
  97634. _this.REFLECTION = false;
  97635. _this.REFLECTIONMAP_3D = false;
  97636. _this.REFLECTIONMAP_SPHERICAL = false;
  97637. _this.REFLECTIONMAP_PLANAR = false;
  97638. _this.REFLECTIONMAP_CUBIC = false;
  97639. _this.REFLECTIONMAP_PROJECTION = false;
  97640. _this.REFLECTIONMAP_SKYBOX = false;
  97641. _this.REFLECTIONMAP_EXPLICIT = false;
  97642. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  97643. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  97644. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  97645. _this.INVERTCUBICMAP = false;
  97646. _this.REFLECTIONMAP_OPPOSITEZ = false;
  97647. _this.LODINREFLECTIONALPHA = false;
  97648. _this.GAMMAREFLECTION = false;
  97649. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  97650. // Default BJS.
  97651. _this.MAINUV1 = false;
  97652. _this.MAINUV2 = false;
  97653. _this.UV1 = false;
  97654. _this.UV2 = false;
  97655. _this.CLIPPLANE = false;
  97656. _this.POINTSIZE = false;
  97657. _this.FOG = false;
  97658. _this.NORMAL = false;
  97659. _this.NUM_BONE_INFLUENCERS = 0;
  97660. _this.BonesPerMesh = 0;
  97661. _this.INSTANCES = false;
  97662. _this.SHADOWFLOAT = false;
  97663. _this.rebuild();
  97664. return _this;
  97665. }
  97666. return BackgroundMaterialDefines;
  97667. }(BABYLON.MaterialDefines));
  97668. /**
  97669. * Background material used to create an efficient environement around your scene.
  97670. */
  97671. var BackgroundMaterial = /** @class */ (function (_super) {
  97672. __extends(BackgroundMaterial, _super);
  97673. /**
  97674. * Instantiates a Background Material in the given scene
  97675. * @param name The friendly name of the material
  97676. * @param scene The scene to add the material to
  97677. */
  97678. function BackgroundMaterial(name, scene) {
  97679. var _this = _super.call(this, name, scene) || this;
  97680. /**
  97681. * Key light Color (multiply against the environement texture)
  97682. */
  97683. _this.primaryColor = BABYLON.Color3.White();
  97684. _this._primaryColorShadowLevel = 0;
  97685. _this._primaryColorHighlightLevel = 0;
  97686. /**
  97687. * Reflection Texture used in the material.
  97688. * Should be author in a specific way for the best result (refer to the documentation).
  97689. */
  97690. _this.reflectionTexture = null;
  97691. /**
  97692. * Reflection Texture level of blur.
  97693. *
  97694. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  97695. * texture twice.
  97696. */
  97697. _this.reflectionBlur = 0;
  97698. /**
  97699. * Diffuse Texture used in the material.
  97700. * Should be author in a specific way for the best result (refer to the documentation).
  97701. */
  97702. _this.diffuseTexture = null;
  97703. _this._shadowLights = null;
  97704. /**
  97705. * Specify the list of lights casting shadow on the material.
  97706. * All scene shadow lights will be included if null.
  97707. */
  97708. _this.shadowLights = null;
  97709. /**
  97710. * Helps adjusting the shadow to a softer level if required.
  97711. * 0 means black shadows and 1 means no shadows.
  97712. */
  97713. _this.shadowLevel = 0;
  97714. /**
  97715. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  97716. * It is usually zero but might be interesting to modify according to your setup.
  97717. */
  97718. _this.sceneCenter = BABYLON.Vector3.Zero();
  97719. /**
  97720. * This helps specifying that the material is falling off to the sky box at grazing angle.
  97721. * This helps ensuring a nice transition when the camera goes under the ground.
  97722. */
  97723. _this.opacityFresnel = true;
  97724. /**
  97725. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  97726. * This helps adding a mirror texture on the ground.
  97727. */
  97728. _this.reflectionFresnel = false;
  97729. /**
  97730. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  97731. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  97732. */
  97733. _this.reflectionFalloffDistance = 0.0;
  97734. /**
  97735. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  97736. */
  97737. _this.reflectionAmount = 1.0;
  97738. /**
  97739. * This specifies the weight of the reflection at grazing angle.
  97740. */
  97741. _this.reflectionReflectance0 = 0.05;
  97742. /**
  97743. * This specifies the weight of the reflection at a perpendicular point of view.
  97744. */
  97745. _this.reflectionReflectance90 = 0.5;
  97746. /**
  97747. * Helps to directly use the maps channels instead of their level.
  97748. */
  97749. _this.useRGBColor = true;
  97750. /**
  97751. * This helps reducing the banding effect that could occur on the background.
  97752. */
  97753. _this.enableNoise = false;
  97754. _this._fovMultiplier = 1.0;
  97755. /**
  97756. * Enable the FOV adjustment feature controlled by fovMultiplier.
  97757. */
  97758. _this.useEquirectangularFOV = false;
  97759. _this._maxSimultaneousLights = 4;
  97760. /**
  97761. * Number of Simultaneous lights allowed on the material.
  97762. */
  97763. _this.maxSimultaneousLights = 4;
  97764. /**
  97765. * Keep track of the image processing observer to allow dispose and replace.
  97766. */
  97767. _this._imageProcessingObserver = null;
  97768. /**
  97769. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  97770. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  97771. */
  97772. _this.switchToBGR = false;
  97773. // Temp values kept as cache in the material.
  97774. _this._renderTargets = new BABYLON.SmartArray(16);
  97775. _this._reflectionControls = BABYLON.Vector4.Zero();
  97776. _this._white = BABYLON.Color3.White();
  97777. _this._primaryShadowColor = BABYLON.Color3.Black();
  97778. _this._primaryHighlightColor = BABYLON.Color3.Black();
  97779. // Setup the default processing configuration to the scene.
  97780. _this._attachImageProcessingConfiguration(null);
  97781. _this.getRenderTargetTextures = function () {
  97782. _this._renderTargets.reset();
  97783. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  97784. _this._renderTargets.push(_this._diffuseTexture);
  97785. }
  97786. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  97787. _this._renderTargets.push(_this._reflectionTexture);
  97788. }
  97789. return _this._renderTargets;
  97790. };
  97791. return _this;
  97792. }
  97793. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  97794. /**
  97795. * Experimental Internal Use Only.
  97796. *
  97797. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  97798. * This acts as a helper to set the primary color to a more "human friendly" value.
  97799. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  97800. * output color as close as possible from the chosen value.
  97801. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  97802. * part of lighting setup.)
  97803. */
  97804. get: function () {
  97805. return this.__perceptualColor;
  97806. },
  97807. set: function (value) {
  97808. this.__perceptualColor = value;
  97809. this._computePrimaryColorFromPerceptualColor();
  97810. this._markAllSubMeshesAsLightsDirty();
  97811. },
  97812. enumerable: true,
  97813. configurable: true
  97814. });
  97815. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  97816. /**
  97817. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  97818. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  97819. */
  97820. get: function () {
  97821. return this._primaryColorShadowLevel;
  97822. },
  97823. set: function (value) {
  97824. this._primaryColorShadowLevel = value;
  97825. this._computePrimaryColors();
  97826. this._markAllSubMeshesAsLightsDirty();
  97827. },
  97828. enumerable: true,
  97829. configurable: true
  97830. });
  97831. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  97832. /**
  97833. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  97834. * The primary color is used at the level chosen to define what the white area would look.
  97835. */
  97836. get: function () {
  97837. return this._primaryColorHighlightLevel;
  97838. },
  97839. set: function (value) {
  97840. this._primaryColorHighlightLevel = value;
  97841. this._computePrimaryColors();
  97842. this._markAllSubMeshesAsLightsDirty();
  97843. },
  97844. enumerable: true,
  97845. configurable: true
  97846. });
  97847. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  97848. /**
  97849. * Sets the reflection reflectance fresnel values according to the default standard
  97850. * empirically know to work well :-)
  97851. */
  97852. set: function (value) {
  97853. var reflectionWeight = value;
  97854. if (reflectionWeight < 0.5) {
  97855. reflectionWeight = reflectionWeight * 2.0;
  97856. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  97857. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  97858. }
  97859. else {
  97860. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  97861. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  97862. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  97863. }
  97864. },
  97865. enumerable: true,
  97866. configurable: true
  97867. });
  97868. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  97869. /**
  97870. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97871. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  97872. * Recommended to be keep at 1.0 except for special cases.
  97873. */
  97874. get: function () {
  97875. return this._fovMultiplier;
  97876. },
  97877. set: function (value) {
  97878. if (isNaN(value)) {
  97879. value = 1.0;
  97880. }
  97881. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  97882. },
  97883. enumerable: true,
  97884. configurable: true
  97885. });
  97886. /**
  97887. * Attaches a new image processing configuration to the PBR Material.
  97888. * @param configuration (if null the scene configuration will be use)
  97889. */
  97890. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  97891. var _this = this;
  97892. if (configuration === this._imageProcessingConfiguration) {
  97893. return;
  97894. }
  97895. // Detaches observer.
  97896. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97897. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97898. }
  97899. // Pick the scene configuration if needed.
  97900. if (!configuration) {
  97901. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  97902. }
  97903. else {
  97904. this._imageProcessingConfiguration = configuration;
  97905. }
  97906. // Attaches observer.
  97907. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  97908. _this._computePrimaryColorFromPerceptualColor();
  97909. _this._markAllSubMeshesAsImageProcessingDirty();
  97910. });
  97911. };
  97912. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  97913. /**
  97914. * Gets the image processing configuration used either in this material.
  97915. */
  97916. get: function () {
  97917. return this._imageProcessingConfiguration;
  97918. },
  97919. /**
  97920. * Sets the Default image processing configuration used either in the this material.
  97921. *
  97922. * If sets to null, the scene one is in use.
  97923. */
  97924. set: function (value) {
  97925. this._attachImageProcessingConfiguration(value);
  97926. // Ensure the effect will be rebuilt.
  97927. this._markAllSubMeshesAsTexturesDirty();
  97928. },
  97929. enumerable: true,
  97930. configurable: true
  97931. });
  97932. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  97933. /**
  97934. * Gets wether the color curves effect is enabled.
  97935. */
  97936. get: function () {
  97937. return this.imageProcessingConfiguration.colorCurvesEnabled;
  97938. },
  97939. /**
  97940. * Sets wether the color curves effect is enabled.
  97941. */
  97942. set: function (value) {
  97943. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  97944. },
  97945. enumerable: true,
  97946. configurable: true
  97947. });
  97948. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  97949. /**
  97950. * Gets wether the color grading effect is enabled.
  97951. */
  97952. get: function () {
  97953. return this.imageProcessingConfiguration.colorGradingEnabled;
  97954. },
  97955. /**
  97956. * Gets wether the color grading effect is enabled.
  97957. */
  97958. set: function (value) {
  97959. this.imageProcessingConfiguration.colorGradingEnabled = value;
  97960. },
  97961. enumerable: true,
  97962. configurable: true
  97963. });
  97964. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  97965. /**
  97966. * Gets wether tonemapping is enabled or not.
  97967. */
  97968. get: function () {
  97969. return this._imageProcessingConfiguration.toneMappingEnabled;
  97970. },
  97971. /**
  97972. * Sets wether tonemapping is enabled or not
  97973. */
  97974. set: function (value) {
  97975. this._imageProcessingConfiguration.toneMappingEnabled = value;
  97976. },
  97977. enumerable: true,
  97978. configurable: true
  97979. });
  97980. ;
  97981. ;
  97982. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  97983. /**
  97984. * The camera exposure used on this material.
  97985. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97986. * This corresponds to a photographic exposure.
  97987. */
  97988. get: function () {
  97989. return this._imageProcessingConfiguration.exposure;
  97990. },
  97991. /**
  97992. * The camera exposure used on this material.
  97993. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  97994. * This corresponds to a photographic exposure.
  97995. */
  97996. set: function (value) {
  97997. this._imageProcessingConfiguration.exposure = value;
  97998. },
  97999. enumerable: true,
  98000. configurable: true
  98001. });
  98002. ;
  98003. ;
  98004. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  98005. /**
  98006. * Gets The camera contrast used on this material.
  98007. */
  98008. get: function () {
  98009. return this._imageProcessingConfiguration.contrast;
  98010. },
  98011. /**
  98012. * Sets The camera contrast used on this material.
  98013. */
  98014. set: function (value) {
  98015. this._imageProcessingConfiguration.contrast = value;
  98016. },
  98017. enumerable: true,
  98018. configurable: true
  98019. });
  98020. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  98021. /**
  98022. * Gets the Color Grading 2D Lookup Texture.
  98023. */
  98024. get: function () {
  98025. return this._imageProcessingConfiguration.colorGradingTexture;
  98026. },
  98027. /**
  98028. * Sets the Color Grading 2D Lookup Texture.
  98029. */
  98030. set: function (value) {
  98031. this.imageProcessingConfiguration.colorGradingTexture = value;
  98032. },
  98033. enumerable: true,
  98034. configurable: true
  98035. });
  98036. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  98037. /**
  98038. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98039. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98040. * 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;
  98041. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98042. */
  98043. get: function () {
  98044. return this.imageProcessingConfiguration.colorCurves;
  98045. },
  98046. /**
  98047. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  98048. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  98049. * 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;
  98050. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  98051. */
  98052. set: function (value) {
  98053. this.imageProcessingConfiguration.colorCurves = value;
  98054. },
  98055. enumerable: true,
  98056. configurable: true
  98057. });
  98058. /**
  98059. * The entire material has been created in order to prevent overdraw.
  98060. * @returns false
  98061. */
  98062. BackgroundMaterial.prototype.needAlphaTesting = function () {
  98063. return true;
  98064. };
  98065. /**
  98066. * The entire material has been created in order to prevent overdraw.
  98067. * @returns true if blending is enable
  98068. */
  98069. BackgroundMaterial.prototype.needAlphaBlending = function () {
  98070. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  98071. };
  98072. /**
  98073. * Checks wether the material is ready to be rendered for a given mesh.
  98074. * @param mesh The mesh to render
  98075. * @param subMesh The submesh to check against
  98076. * @param useInstances Specify wether or not the material is used with instances
  98077. * @returns true if all the dependencies are ready (Textures, Effects...)
  98078. */
  98079. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  98080. var _this = this;
  98081. if (useInstances === void 0) { useInstances = false; }
  98082. if (subMesh.effect && this.isFrozen) {
  98083. if (this._wasPreviouslyReady) {
  98084. return true;
  98085. }
  98086. }
  98087. if (!subMesh._materialDefines) {
  98088. subMesh._materialDefines = new BackgroundMaterialDefines();
  98089. }
  98090. var scene = this.getScene();
  98091. var defines = subMesh._materialDefines;
  98092. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  98093. if (defines._renderId === scene.getRenderId()) {
  98094. return true;
  98095. }
  98096. }
  98097. var engine = scene.getEngine();
  98098. // Lights
  98099. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  98100. defines._needNormals = true;
  98101. // Textures
  98102. if (defines._areTexturesDirty) {
  98103. defines._needUVs = false;
  98104. if (scene.texturesEnabled) {
  98105. if (scene.getEngine().getCaps().textureLOD) {
  98106. defines.TEXTURELODSUPPORT = true;
  98107. }
  98108. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98109. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  98110. return false;
  98111. }
  98112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  98113. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  98114. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  98115. defines.OPACITYFRESNEL = this._opacityFresnel;
  98116. }
  98117. else {
  98118. defines.DIFFUSE = false;
  98119. defines.DIFFUSEHASALPHA = false;
  98120. defines.GAMMADIFFUSE = false;
  98121. defines.OPACITYFRESNEL = false;
  98122. }
  98123. var reflectionTexture = this._reflectionTexture;
  98124. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98125. if (!reflectionTexture.isReadyOrNotBlocking()) {
  98126. return false;
  98127. }
  98128. defines.REFLECTION = true;
  98129. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  98130. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  98131. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  98132. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  98133. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  98134. defines.REFLECTIONBGR = this.switchToBGR;
  98135. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  98136. defines.INVERTCUBICMAP = true;
  98137. }
  98138. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  98139. switch (reflectionTexture.coordinatesMode) {
  98140. case BABYLON.Texture.EXPLICIT_MODE:
  98141. defines.REFLECTIONMAP_EXPLICIT = true;
  98142. break;
  98143. case BABYLON.Texture.PLANAR_MODE:
  98144. defines.REFLECTIONMAP_PLANAR = true;
  98145. break;
  98146. case BABYLON.Texture.PROJECTION_MODE:
  98147. defines.REFLECTIONMAP_PROJECTION = true;
  98148. break;
  98149. case BABYLON.Texture.SKYBOX_MODE:
  98150. defines.REFLECTIONMAP_SKYBOX = true;
  98151. break;
  98152. case BABYLON.Texture.SPHERICAL_MODE:
  98153. defines.REFLECTIONMAP_SPHERICAL = true;
  98154. break;
  98155. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  98156. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  98157. break;
  98158. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  98159. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  98160. break;
  98161. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  98162. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  98163. break;
  98164. case BABYLON.Texture.CUBIC_MODE:
  98165. case BABYLON.Texture.INVCUBIC_MODE:
  98166. default:
  98167. defines.REFLECTIONMAP_CUBIC = true;
  98168. break;
  98169. }
  98170. if (this.reflectionFresnel) {
  98171. defines.REFLECTIONFRESNEL = true;
  98172. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  98173. this._reflectionControls.x = this.reflectionAmount;
  98174. this._reflectionControls.y = this.reflectionReflectance0;
  98175. this._reflectionControls.z = this.reflectionReflectance90;
  98176. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  98177. }
  98178. else {
  98179. defines.REFLECTIONFRESNEL = false;
  98180. defines.REFLECTIONFALLOFF = false;
  98181. }
  98182. }
  98183. else {
  98184. defines.REFLECTION = false;
  98185. defines.REFLECTIONFRESNEL = false;
  98186. defines.REFLECTIONFALLOFF = false;
  98187. defines.REFLECTIONBLUR = false;
  98188. defines.REFLECTIONMAP_3D = false;
  98189. defines.REFLECTIONMAP_SPHERICAL = false;
  98190. defines.REFLECTIONMAP_PLANAR = false;
  98191. defines.REFLECTIONMAP_CUBIC = false;
  98192. defines.REFLECTIONMAP_PROJECTION = false;
  98193. defines.REFLECTIONMAP_SKYBOX = false;
  98194. defines.REFLECTIONMAP_EXPLICIT = false;
  98195. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  98196. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  98197. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  98198. defines.INVERTCUBICMAP = false;
  98199. defines.REFLECTIONMAP_OPPOSITEZ = false;
  98200. defines.LODINREFLECTIONALPHA = false;
  98201. defines.GAMMAREFLECTION = false;
  98202. }
  98203. }
  98204. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  98205. defines.USERGBCOLOR = this._useRGBColor;
  98206. defines.NOISE = this._enableNoise;
  98207. }
  98208. if (defines._areLightsDirty) {
  98209. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  98210. }
  98211. if (defines._areImageProcessingDirty) {
  98212. if (!this._imageProcessingConfiguration.isReady()) {
  98213. return false;
  98214. }
  98215. this._imageProcessingConfiguration.prepareDefines(defines);
  98216. }
  98217. // Misc.
  98218. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  98219. // Values that need to be evaluated on every frame
  98220. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  98221. // Attribs
  98222. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  98223. if (mesh) {
  98224. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  98225. mesh.createNormals(true);
  98226. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  98227. }
  98228. }
  98229. }
  98230. // Get correct effect
  98231. if (defines.isDirty) {
  98232. defines.markAsProcessed();
  98233. scene.resetCachedMaterial();
  98234. // Fallbacks
  98235. var fallbacks = new BABYLON.EffectFallbacks();
  98236. if (defines.FOG) {
  98237. fallbacks.addFallback(0, "FOG");
  98238. }
  98239. if (defines.POINTSIZE) {
  98240. fallbacks.addFallback(1, "POINTSIZE");
  98241. }
  98242. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  98243. if (defines.NUM_BONE_INFLUENCERS > 0) {
  98244. fallbacks.addCPUSkinningFallback(0, mesh);
  98245. }
  98246. //Attributes
  98247. var attribs = [BABYLON.VertexBuffer.PositionKind];
  98248. if (defines.NORMAL) {
  98249. attribs.push(BABYLON.VertexBuffer.NormalKind);
  98250. }
  98251. if (defines.UV1) {
  98252. attribs.push(BABYLON.VertexBuffer.UVKind);
  98253. }
  98254. if (defines.UV2) {
  98255. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98256. }
  98257. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  98258. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  98259. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  98260. "vFogInfos", "vFogColor", "pointSize",
  98261. "vClipPlane", "mBones",
  98262. "vPrimaryColor", "vPrimaryColorShadow",
  98263. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  98264. "shadowLevel", "alpha",
  98265. "vBackgroundCenter", "vReflectionControl",
  98266. "vDiffuseInfos", "diffuseMatrix",
  98267. ];
  98268. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  98269. var uniformBuffers = ["Material", "Scene"];
  98270. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  98271. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  98272. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  98273. uniformsNames: uniforms,
  98274. uniformBuffersNames: uniformBuffers,
  98275. samplers: samplers,
  98276. defines: defines,
  98277. maxSimultaneousLights: this._maxSimultaneousLights
  98278. });
  98279. var onCompiled = function (effect) {
  98280. if (_this.onCompiled) {
  98281. _this.onCompiled(effect);
  98282. }
  98283. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  98284. };
  98285. var join = defines.toString();
  98286. subMesh.setEffect(scene.getEngine().createEffect("background", {
  98287. attributes: attribs,
  98288. uniformsNames: uniforms,
  98289. uniformBuffersNames: uniformBuffers,
  98290. samplers: samplers,
  98291. defines: join,
  98292. fallbacks: fallbacks,
  98293. onCompiled: onCompiled,
  98294. onError: this.onError,
  98295. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  98296. }, engine), defines);
  98297. this.buildUniformLayout();
  98298. }
  98299. if (!subMesh.effect || !subMesh.effect.isReady()) {
  98300. return false;
  98301. }
  98302. defines._renderId = scene.getRenderId();
  98303. this._wasPreviouslyReady = true;
  98304. return true;
  98305. };
  98306. /**
  98307. * Compute the primary color according to the chosen perceptual color.
  98308. */
  98309. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  98310. if (!this.__perceptualColor) {
  98311. return;
  98312. }
  98313. this._primaryColor.copyFrom(this.__perceptualColor);
  98314. // Revert gamma space.
  98315. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  98316. // Revert image processing configuration.
  98317. if (this._imageProcessingConfiguration) {
  98318. // Revert Exposure.
  98319. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  98320. }
  98321. this._computePrimaryColors();
  98322. };
  98323. /**
  98324. * Compute the highlights and shadow colors according to their chosen levels.
  98325. */
  98326. BackgroundMaterial.prototype._computePrimaryColors = function () {
  98327. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  98328. return;
  98329. }
  98330. // Find the highlight color based on the configuration.
  98331. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  98332. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  98333. // Find the shadow color based on the configuration.
  98334. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  98335. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  98336. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  98337. };
  98338. /**
  98339. * Build the uniform buffer used in the material.
  98340. */
  98341. BackgroundMaterial.prototype.buildUniformLayout = function () {
  98342. // Order is important !
  98343. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  98344. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  98345. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  98346. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  98347. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  98348. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  98349. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  98350. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  98351. this._uniformBuffer.addUniform("pointSize", 1);
  98352. this._uniformBuffer.addUniform("shadowLevel", 1);
  98353. this._uniformBuffer.addUniform("alpha", 1);
  98354. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  98355. this._uniformBuffer.addUniform("vReflectionControl", 4);
  98356. this._uniformBuffer.create();
  98357. };
  98358. /**
  98359. * Unbind the material.
  98360. */
  98361. BackgroundMaterial.prototype.unbind = function () {
  98362. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  98363. this._uniformBuffer.setTexture("diffuseSampler", null);
  98364. }
  98365. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  98366. this._uniformBuffer.setTexture("reflectionSampler", null);
  98367. }
  98368. _super.prototype.unbind.call(this);
  98369. };
  98370. /**
  98371. * Bind only the world matrix to the material.
  98372. * @param world The world matrix to bind.
  98373. */
  98374. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  98375. this._activeEffect.setMatrix("world", world);
  98376. };
  98377. /**
  98378. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  98379. * @param world The world matrix to bind.
  98380. * @param subMesh The submesh to bind for.
  98381. */
  98382. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  98383. var scene = this.getScene();
  98384. var defines = subMesh._materialDefines;
  98385. if (!defines) {
  98386. return;
  98387. }
  98388. var effect = subMesh.effect;
  98389. if (!effect) {
  98390. return;
  98391. }
  98392. this._activeEffect = effect;
  98393. // Matrices
  98394. this.bindOnlyWorldMatrix(world);
  98395. // Bones
  98396. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  98397. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  98398. if (mustRebind) {
  98399. this._uniformBuffer.bindToEffect(effect, "Material");
  98400. this.bindViewProjection(effect);
  98401. var reflectionTexture = this._reflectionTexture;
  98402. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  98403. // Texture uniforms
  98404. if (scene.texturesEnabled) {
  98405. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98406. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  98407. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  98408. }
  98409. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98410. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  98411. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  98412. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  98413. }
  98414. }
  98415. if (this.shadowLevel > 0) {
  98416. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  98417. }
  98418. this._uniformBuffer.updateFloat("alpha", this.alpha);
  98419. // Point size
  98420. if (this.pointsCloud) {
  98421. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  98422. }
  98423. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  98424. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  98425. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  98426. }
  98427. else {
  98428. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  98429. }
  98430. }
  98431. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  98432. // Textures
  98433. if (scene.texturesEnabled) {
  98434. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  98435. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  98436. }
  98437. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  98438. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  98439. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  98440. }
  98441. else if (!defines.REFLECTIONBLUR) {
  98442. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  98443. }
  98444. else {
  98445. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  98446. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  98447. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  98448. }
  98449. if (defines.REFLECTIONFRESNEL) {
  98450. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  98451. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  98452. }
  98453. }
  98454. }
  98455. // Clip plane
  98456. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  98457. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  98458. }
  98459. if (mustRebind || !this.isFrozen) {
  98460. if (scene.lightsEnabled) {
  98461. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  98462. }
  98463. // View
  98464. this.bindView(effect);
  98465. // Fog
  98466. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  98467. // image processing
  98468. this._imageProcessingConfiguration.bind(this._activeEffect);
  98469. }
  98470. this._uniformBuffer.update();
  98471. this._afterBind(mesh);
  98472. };
  98473. /**
  98474. * Dispose the material.
  98475. * @param forceDisposeEffect Force disposal of the associated effect.
  98476. * @param forceDisposeTextures Force disposal of the associated textures.
  98477. */
  98478. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  98479. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  98480. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  98481. if (forceDisposeTextures) {
  98482. if (this.diffuseTexture) {
  98483. this.diffuseTexture.dispose();
  98484. }
  98485. if (this.reflectionTexture) {
  98486. this.reflectionTexture.dispose();
  98487. }
  98488. }
  98489. this._renderTargets.dispose();
  98490. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  98491. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  98492. }
  98493. _super.prototype.dispose.call(this, forceDisposeEffect);
  98494. };
  98495. /**
  98496. * Clones the material.
  98497. * @param name The cloned name.
  98498. * @returns The cloned material.
  98499. */
  98500. BackgroundMaterial.prototype.clone = function (name) {
  98501. var _this = this;
  98502. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  98503. };
  98504. /**
  98505. * Serializes the current material to its JSON representation.
  98506. * @returns The JSON representation.
  98507. */
  98508. BackgroundMaterial.prototype.serialize = function () {
  98509. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98510. serializationObject.customType = "BABYLON.BackgroundMaterial";
  98511. return serializationObject;
  98512. };
  98513. /**
  98514. * Gets the class name of the material
  98515. * @returns "BackgroundMaterial"
  98516. */
  98517. BackgroundMaterial.prototype.getClassName = function () {
  98518. return "BackgroundMaterial";
  98519. };
  98520. /**
  98521. * Parse a JSON input to create back a background material.
  98522. * @param source The JSON data to parse
  98523. * @param scene The scene to create the parsed material in
  98524. * @param rootUrl The root url of the assets the material depends upon
  98525. * @returns the instantiated BackgroundMaterial.
  98526. */
  98527. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  98528. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  98529. };
  98530. /**
  98531. * Standard reflectance value at parallel view angle.
  98532. */
  98533. BackgroundMaterial.StandardReflectance0 = 0.05;
  98534. /**
  98535. * Standard reflectance value at grazing angle.
  98536. */
  98537. BackgroundMaterial.StandardReflectance90 = 0.5;
  98538. __decorate([
  98539. BABYLON.serializeAsColor3()
  98540. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  98541. __decorate([
  98542. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98543. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  98544. __decorate([
  98545. BABYLON.serializeAsColor3()
  98546. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  98547. __decorate([
  98548. BABYLON.serialize()
  98549. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  98550. __decorate([
  98551. BABYLON.serialize()
  98552. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  98553. __decorate([
  98554. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  98555. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  98556. __decorate([
  98557. BABYLON.serializeAsTexture()
  98558. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  98559. __decorate([
  98560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98561. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  98562. __decorate([
  98563. BABYLON.serialize()
  98564. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  98565. __decorate([
  98566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98567. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  98568. __decorate([
  98569. BABYLON.serializeAsTexture()
  98570. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  98571. __decorate([
  98572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98573. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  98574. __decorate([
  98575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98576. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  98577. __decorate([
  98578. BABYLON.serialize()
  98579. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  98580. __decorate([
  98581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98582. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  98583. __decorate([
  98584. BABYLON.serializeAsVector3()
  98585. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  98586. __decorate([
  98587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98588. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  98589. __decorate([
  98590. BABYLON.serialize()
  98591. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  98592. __decorate([
  98593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98594. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  98595. __decorate([
  98596. BABYLON.serialize()
  98597. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  98598. __decorate([
  98599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98600. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  98601. __decorate([
  98602. BABYLON.serialize()
  98603. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  98604. __decorate([
  98605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98606. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  98607. __decorate([
  98608. BABYLON.serialize()
  98609. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  98610. __decorate([
  98611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98612. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  98613. __decorate([
  98614. BABYLON.serialize()
  98615. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  98616. __decorate([
  98617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98618. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  98619. __decorate([
  98620. BABYLON.serialize()
  98621. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  98622. __decorate([
  98623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98624. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  98625. __decorate([
  98626. BABYLON.serialize()
  98627. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  98628. __decorate([
  98629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98630. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  98631. __decorate([
  98632. BABYLON.serialize()
  98633. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  98634. __decorate([
  98635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98636. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  98637. __decorate([
  98638. BABYLON.serialize()
  98639. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  98640. __decorate([
  98641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  98642. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  98643. __decorate([
  98644. BABYLON.serializeAsImageProcessingConfiguration()
  98645. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  98646. return BackgroundMaterial;
  98647. }(BABYLON.PushMaterial));
  98648. BABYLON.BackgroundMaterial = BackgroundMaterial;
  98649. })(BABYLON || (BABYLON = {}));
  98650. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  98651. var __assign = (this && this.__assign) || Object.assign || function(t) {
  98652. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98653. s = arguments[i];
  98654. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98655. t[p] = s[p];
  98656. }
  98657. return t;
  98658. };
  98659. var BABYLON;
  98660. (function (BABYLON) {
  98661. /**
  98662. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  98663. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  98664. * It also helps with the default setup of your imageProcessing configuration.
  98665. */
  98666. var EnvironmentHelper = /** @class */ (function () {
  98667. /**
  98668. * constructor
  98669. * @param options
  98670. * @param scene The scene to add the material to
  98671. */
  98672. function EnvironmentHelper(options, scene) {
  98673. var _this = this;
  98674. this._errorHandler = function (message, exception) {
  98675. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  98676. };
  98677. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  98678. this._scene = scene;
  98679. this.onErrorObservable = new BABYLON.Observable();
  98680. this._setupBackground();
  98681. this._setupImageProcessing();
  98682. }
  98683. /**
  98684. * Creates the default options for the helper.
  98685. */
  98686. EnvironmentHelper._getDefaultOptions = function () {
  98687. return {
  98688. createGround: true,
  98689. groundSize: 15,
  98690. groundTexture: this._groundTextureCDNUrl,
  98691. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98692. groundOpacity: 0.9,
  98693. enableGroundShadow: true,
  98694. groundShadowLevel: 0.5,
  98695. enableGroundMirror: false,
  98696. groundMirrorSizeRatio: 0.3,
  98697. groundMirrorBlurKernel: 64,
  98698. groundMirrorAmount: 1,
  98699. groundMirrorFresnelWeight: 1,
  98700. groundMirrorFallOffDistance: 0,
  98701. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  98702. groundYBias: 0.00001,
  98703. createSkybox: true,
  98704. skyboxSize: 20,
  98705. skyboxTexture: this._skyboxTextureCDNUrl,
  98706. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  98707. backgroundYRotation: 0,
  98708. sizeAuto: true,
  98709. rootPosition: BABYLON.Vector3.Zero(),
  98710. setupImageProcessing: true,
  98711. environmentTexture: this._environmentTextureCDNUrl,
  98712. cameraExposure: 0.8,
  98713. cameraContrast: 1.2,
  98714. toneMappingEnabled: true,
  98715. };
  98716. };
  98717. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  98718. /**
  98719. * Gets the root mesh created by the helper.
  98720. */
  98721. get: function () {
  98722. return this._rootMesh;
  98723. },
  98724. enumerable: true,
  98725. configurable: true
  98726. });
  98727. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  98728. /**
  98729. * Gets the skybox created by the helper.
  98730. */
  98731. get: function () {
  98732. return this._skybox;
  98733. },
  98734. enumerable: true,
  98735. configurable: true
  98736. });
  98737. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  98738. /**
  98739. * Gets the skybox texture created by the helper.
  98740. */
  98741. get: function () {
  98742. return this._skyboxTexture;
  98743. },
  98744. enumerable: true,
  98745. configurable: true
  98746. });
  98747. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  98748. /**
  98749. * Gets the skybox material created by the helper.
  98750. */
  98751. get: function () {
  98752. return this._skyboxMaterial;
  98753. },
  98754. enumerable: true,
  98755. configurable: true
  98756. });
  98757. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  98758. /**
  98759. * Gets the ground mesh created by the helper.
  98760. */
  98761. get: function () {
  98762. return this._ground;
  98763. },
  98764. enumerable: true,
  98765. configurable: true
  98766. });
  98767. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  98768. /**
  98769. * Gets the ground texture created by the helper.
  98770. */
  98771. get: function () {
  98772. return this._groundTexture;
  98773. },
  98774. enumerable: true,
  98775. configurable: true
  98776. });
  98777. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  98778. /**
  98779. * Gets the ground mirror created by the helper.
  98780. */
  98781. get: function () {
  98782. return this._groundMirror;
  98783. },
  98784. enumerable: true,
  98785. configurable: true
  98786. });
  98787. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  98788. /**
  98789. * Gets the ground mirror render list to helps pushing the meshes
  98790. * you wish in the ground reflection.
  98791. */
  98792. get: function () {
  98793. if (this._groundMirror) {
  98794. return this._groundMirror.renderList;
  98795. }
  98796. return null;
  98797. },
  98798. enumerable: true,
  98799. configurable: true
  98800. });
  98801. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  98802. /**
  98803. * Gets the ground material created by the helper.
  98804. */
  98805. get: function () {
  98806. return this._groundMaterial;
  98807. },
  98808. enumerable: true,
  98809. configurable: true
  98810. });
  98811. /**
  98812. * Updates the background according to the new options
  98813. * @param options
  98814. */
  98815. EnvironmentHelper.prototype.updateOptions = function (options) {
  98816. var newOptions = __assign({}, this._options, options);
  98817. if (this._ground && !newOptions.createGround) {
  98818. this._ground.dispose();
  98819. this._ground = null;
  98820. }
  98821. if (this._groundMaterial && !newOptions.createGround) {
  98822. this._groundMaterial.dispose();
  98823. this._groundMaterial = null;
  98824. }
  98825. if (this._groundTexture) {
  98826. if (this._options.groundTexture != newOptions.groundTexture) {
  98827. this._groundTexture.dispose();
  98828. this._groundTexture = null;
  98829. }
  98830. }
  98831. if (this._skybox && !newOptions.createSkybox) {
  98832. this._skybox.dispose();
  98833. this._skybox = null;
  98834. }
  98835. if (this._skyboxMaterial && !newOptions.createSkybox) {
  98836. this._skyboxMaterial.dispose();
  98837. this._skyboxMaterial = null;
  98838. }
  98839. if (this._skyboxTexture) {
  98840. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  98841. this._skyboxTexture.dispose();
  98842. this._skyboxTexture = null;
  98843. }
  98844. }
  98845. if (this._groundMirror && !newOptions.enableGroundMirror) {
  98846. this._groundMirror.dispose();
  98847. this._groundMirror = null;
  98848. }
  98849. if (this._scene.environmentTexture) {
  98850. if (this._options.environmentTexture != newOptions.environmentTexture) {
  98851. this._scene.environmentTexture.dispose();
  98852. }
  98853. }
  98854. this._options = newOptions;
  98855. this._setupBackground();
  98856. this._setupImageProcessing();
  98857. };
  98858. /**
  98859. * Sets the primary color of all the available elements.
  98860. * @param color the main color to affect to the ground and the background
  98861. */
  98862. EnvironmentHelper.prototype.setMainColor = function (color) {
  98863. if (this.groundMaterial) {
  98864. this.groundMaterial.primaryColor = color;
  98865. }
  98866. if (this.skyboxMaterial) {
  98867. this.skyboxMaterial.primaryColor = color;
  98868. }
  98869. if (this.groundMirror) {
  98870. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  98871. }
  98872. };
  98873. /**
  98874. * Setup the image processing according to the specified options.
  98875. */
  98876. EnvironmentHelper.prototype._setupImageProcessing = function () {
  98877. if (this._options.setupImageProcessing) {
  98878. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  98879. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  98880. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  98881. this._setupEnvironmentTexture();
  98882. }
  98883. };
  98884. /**
  98885. * Setup the environment texture according to the specified options.
  98886. */
  98887. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  98888. if (this._scene.environmentTexture) {
  98889. return;
  98890. }
  98891. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  98892. this._scene.environmentTexture = this._options.environmentTexture;
  98893. return;
  98894. }
  98895. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  98896. this._scene.environmentTexture = environmentTexture;
  98897. };
  98898. /**
  98899. * Setup the background according to the specified options.
  98900. */
  98901. EnvironmentHelper.prototype._setupBackground = function () {
  98902. if (!this._rootMesh) {
  98903. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  98904. }
  98905. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  98906. var sceneSize = this._getSceneSize();
  98907. if (this._options.createGround) {
  98908. this._setupGround(sceneSize);
  98909. this._setupGroundMaterial();
  98910. this._setupGroundDiffuseTexture();
  98911. if (this._options.enableGroundMirror) {
  98912. this._setupGroundMirrorTexture(sceneSize);
  98913. }
  98914. this._setupMirrorInGroundMaterial();
  98915. }
  98916. if (this._options.createSkybox) {
  98917. this._setupSkybox(sceneSize);
  98918. this._setupSkyboxMaterial();
  98919. this._setupSkyboxReflectionTexture();
  98920. }
  98921. this._rootMesh.position.x = sceneSize.rootPosition.x;
  98922. this._rootMesh.position.z = sceneSize.rootPosition.z;
  98923. this._rootMesh.position.y = sceneSize.rootPosition.y;
  98924. };
  98925. /**
  98926. * Get the scene sizes according to the setup.
  98927. */
  98928. EnvironmentHelper.prototype._getSceneSize = function () {
  98929. var _this = this;
  98930. var groundSize = this._options.groundSize;
  98931. var skyboxSize = this._options.skyboxSize;
  98932. var rootPosition = this._options.rootPosition;
  98933. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  98934. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98935. }
  98936. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  98937. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  98938. });
  98939. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  98940. if (this._options.sizeAuto) {
  98941. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  98942. this._scene.activeCamera.upperRadiusLimit) {
  98943. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  98944. skyboxSize = groundSize;
  98945. }
  98946. var sceneDiagonalLenght = sceneDiagonal.length();
  98947. if (sceneDiagonalLenght > groundSize) {
  98948. groundSize = sceneDiagonalLenght * 2;
  98949. skyboxSize = groundSize;
  98950. }
  98951. // 10 % bigger.
  98952. groundSize *= 1.1;
  98953. skyboxSize *= 1.5;
  98954. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  98955. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  98956. }
  98957. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  98958. };
  98959. /**
  98960. * Setup the ground according to the specified options.
  98961. */
  98962. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  98963. var _this = this;
  98964. if (!this._ground) {
  98965. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  98966. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  98967. this._ground.parent = this._rootMesh;
  98968. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  98969. }
  98970. this._ground.receiveShadows = this._options.enableGroundShadow;
  98971. };
  98972. /**
  98973. * Setup the ground material according to the specified options.
  98974. */
  98975. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  98976. if (!this._groundMaterial) {
  98977. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  98978. }
  98979. this._groundMaterial.alpha = this._options.groundOpacity;
  98980. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  98981. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  98982. this._groundMaterial.primaryColor = this._options.groundColor;
  98983. this._groundMaterial.useRGBColor = false;
  98984. this._groundMaterial.enableNoise = true;
  98985. if (this._ground) {
  98986. this._ground.material = this._groundMaterial;
  98987. }
  98988. };
  98989. /**
  98990. * Setup the ground diffuse texture according to the specified options.
  98991. */
  98992. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  98993. if (!this._groundMaterial) {
  98994. return;
  98995. }
  98996. if (this._groundTexture) {
  98997. return;
  98998. }
  98999. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  99000. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  99001. return;
  99002. }
  99003. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99004. diffuseTexture.gammaSpace = false;
  99005. diffuseTexture.hasAlpha = true;
  99006. this._groundMaterial.diffuseTexture = diffuseTexture;
  99007. };
  99008. /**
  99009. * Setup the ground mirror texture according to the specified options.
  99010. */
  99011. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  99012. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99013. if (!this._groundMirror) {
  99014. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  99015. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  99016. this._groundMirror.anisotropicFilteringLevel = 1;
  99017. this._groundMirror.wrapU = wrapping;
  99018. this._groundMirror.wrapV = wrapping;
  99019. this._groundMirror.gammaSpace = false;
  99020. if (this._groundMirror.renderList) {
  99021. for (var i = 0; i < this._scene.meshes.length; i++) {
  99022. var mesh = this._scene.meshes[i];
  99023. if (mesh !== this._ground &&
  99024. mesh !== this._skybox &&
  99025. mesh !== this._rootMesh) {
  99026. this._groundMirror.renderList.push(mesh);
  99027. }
  99028. }
  99029. }
  99030. }
  99031. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  99032. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  99033. };
  99034. /**
  99035. * Setup the ground to receive the mirror texture.
  99036. */
  99037. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  99038. if (this._groundMaterial) {
  99039. this._groundMaterial.reflectionTexture = this._groundMirror;
  99040. this._groundMaterial.reflectionFresnel = true;
  99041. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  99042. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  99043. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  99044. }
  99045. };
  99046. /**
  99047. * Setup the skybox according to the specified options.
  99048. */
  99049. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  99050. var _this = this;
  99051. if (!this._skybox) {
  99052. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  99053. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  99054. }
  99055. this._skybox.parent = this._rootMesh;
  99056. };
  99057. /**
  99058. * Setup the skybox material according to the specified options.
  99059. */
  99060. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  99061. if (!this._skybox) {
  99062. return;
  99063. }
  99064. if (!this._skyboxMaterial) {
  99065. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  99066. }
  99067. this._skyboxMaterial.useRGBColor = false;
  99068. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  99069. this._skyboxMaterial.enableNoise = true;
  99070. this._skybox.material = this._skyboxMaterial;
  99071. };
  99072. /**
  99073. * Setup the skybox reflection texture according to the specified options.
  99074. */
  99075. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  99076. if (!this._skyboxMaterial) {
  99077. return;
  99078. }
  99079. if (this._skyboxTexture) {
  99080. return;
  99081. }
  99082. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  99083. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  99084. return;
  99085. }
  99086. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  99087. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  99088. this._skyboxTexture.gammaSpace = false;
  99089. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  99090. };
  99091. /**
  99092. * Dispose all the elements created by the Helper.
  99093. */
  99094. EnvironmentHelper.prototype.dispose = function () {
  99095. if (this._groundMaterial) {
  99096. this._groundMaterial.dispose(true, true);
  99097. }
  99098. if (this._skyboxMaterial) {
  99099. this._skyboxMaterial.dispose(true, true);
  99100. }
  99101. this._rootMesh.dispose(false);
  99102. };
  99103. /**
  99104. * Default ground texture URL.
  99105. */
  99106. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  99107. /**
  99108. * Default skybox texture URL.
  99109. */
  99110. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  99111. /**
  99112. * Default environment texture URL.
  99113. */
  99114. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  99115. return EnvironmentHelper;
  99116. }());
  99117. BABYLON.EnvironmentHelper = EnvironmentHelper;
  99118. })(BABYLON || (BABYLON = {}));
  99119. //# sourceMappingURL=babylon.environmentHelper.js.map
  99120. var BABYLON;
  99121. (function (BABYLON) {
  99122. /**
  99123. * This class is made for on one-liner static method to help creating particle systems.
  99124. */
  99125. var ParticleHelper = /** @class */ (function () {
  99126. function ParticleHelper() {
  99127. }
  99128. /**
  99129. * This is the main static method (one-liner) of this helper to create different particle systems.
  99130. * @param type This string represents the type to the particle system to create
  99131. * @param emitter The object where the particle system will start to emit from.
  99132. * @param scene The scene where the particle system should live.
  99133. * @param gpu If the system will use gpu.
  99134. * @returns the ParticleSystem created.
  99135. */
  99136. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  99137. var _this = this;
  99138. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  99139. if (gpu === void 0) { gpu = false; }
  99140. return new Promise(function (resolve, reject) {
  99141. if (scene) {
  99142. _this._scene = scene;
  99143. }
  99144. else {
  99145. return reject("A particle system need a scene.");
  99146. }
  99147. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  99148. return reject("Particle system with GPU is not supported.");
  99149. }
  99150. _this._emitter = emitter;
  99151. BABYLON.Tools.LoadFile(_this._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  99152. var newData = JSON.parse(data.toString());
  99153. return resolve(_this._createSystem(newData));
  99154. }, undefined, undefined, undefined, function (req, exception) {
  99155. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  99156. });
  99157. });
  99158. };
  99159. ParticleHelper._createSystem = function (data) {
  99160. // Create a particle system
  99161. var system = new BABYLON.ParticleSystem(data.type, data.capacity, this._scene);
  99162. // Texture of each particle
  99163. system.particleTexture = new BABYLON.Texture(this._baseAssetsUrl + "/textures/" + data.textureFile, this._scene);
  99164. // Where the particles come from
  99165. system.emitter = this._emitter; // the starting object, the emitter
  99166. // Colors of all particles
  99167. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  99168. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  99169. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  99170. // Size of each particle (random between...
  99171. system.minSize = data.minSize;
  99172. system.maxSize = data.maxSize;
  99173. // Life time of each particle (random between...
  99174. system.minLifeTime = data.minLifeTime;
  99175. system.maxLifeTime = data.maxLifeTime;
  99176. // Emission rate
  99177. system.emitRate = data.emitRate;
  99178. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  99179. system.blendMode = data.blendMode;
  99180. // Set the gravity of all particles
  99181. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  99182. // Angular speed, in radians
  99183. system.minAngularSpeed = data.minAngularSpeed;
  99184. system.maxAngularSpeed = data.maxAngularSpeed;
  99185. // Speed
  99186. system.minEmitPower = data.minEmitPower;
  99187. system.maxEmitPower = data.maxEmitPower;
  99188. system.updateSpeed = data.updateSpeed;
  99189. switch (data.emitterType) {
  99190. case "box":
  99191. if (!data.direction1 || !data.direction2) {
  99192. throw new Error("Directions are missing in this particle system.");
  99193. }
  99194. if (!data.minEmitBox || !data.maxEmitBox) {
  99195. throw new Error("EmitBox is missing in this particle system.");
  99196. }
  99197. 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));
  99198. break;
  99199. case "sphere":
  99200. system.createSphereEmitter(data.radius);
  99201. break;
  99202. case "directed_sphere":
  99203. if (!data.direction1 || !data.direction2) {
  99204. throw new Error("Directions are missing in this particle system.");
  99205. }
  99206. 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));
  99207. break;
  99208. case "cone":
  99209. system.createConeEmitter(data.radius, data.angle);
  99210. break;
  99211. default:
  99212. break;
  99213. }
  99214. return system;
  99215. };
  99216. /**
  99217. * Base Assets URL.
  99218. */
  99219. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  99220. return ParticleHelper;
  99221. }());
  99222. BABYLON.ParticleHelper = ParticleHelper;
  99223. })(BABYLON || (BABYLON = {}));
  99224. //# sourceMappingURL=babylon.particleHelper.js.map
  99225. var BABYLON;
  99226. (function (BABYLON) {
  99227. /**
  99228. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  99229. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  99230. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  99231. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  99232. */
  99233. var VideoDome = /** @class */ (function (_super) {
  99234. __extends(VideoDome, _super);
  99235. /**
  99236. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  99237. * @param name Element's name, child elements will append suffixes for their own names.
  99238. * @param urlsOrVideo
  99239. * @param options An object containing optional or exposed sub element properties:
  99240. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  99241. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  99242. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  99243. * @param options **loop=true** Automatically loop video on end.
  99244. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  99245. */
  99246. function VideoDome(name, urlsOrVideo, options, scene) {
  99247. var _this = _super.call(this, name, scene) || this;
  99248. // set defaults and manage values
  99249. name = name || "videoDome";
  99250. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  99251. options.clickToPlay = Boolean(options.clickToPlay);
  99252. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  99253. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  99254. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  99255. // create
  99256. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  99257. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  99258. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  99259. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  99260. flat: false,
  99261. radius: options.size,
  99262. subdivisions: options.resolution,
  99263. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  99264. }, scene);
  99265. // configure material
  99266. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  99267. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  99268. material.reflectionTexture = _this._videoTexture;
  99269. material.useEquirectangularFOV = true;
  99270. material.fovMultiplier = 1.0;
  99271. // configure mesh
  99272. _this._mesh.material = material;
  99273. _this._mesh.parent = _this;
  99274. // optional configuration
  99275. if (options.clickToPlay) {
  99276. scene.onPointerUp = function () {
  99277. _this._videoTexture.video.play();
  99278. };
  99279. }
  99280. return _this;
  99281. }
  99282. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  99283. /**
  99284. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  99285. * Also see the options.resolution property.
  99286. */
  99287. get: function () {
  99288. return this._material.fovMultiplier;
  99289. },
  99290. set: function (value) {
  99291. this._material.fovMultiplier = value;
  99292. },
  99293. enumerable: true,
  99294. configurable: true
  99295. });
  99296. /**
  99297. * Releases resources associated with this node.
  99298. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  99299. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  99300. */
  99301. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  99302. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  99303. this._videoTexture.dispose();
  99304. this._mesh.dispose();
  99305. this._material.dispose();
  99306. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  99307. };
  99308. return VideoDome;
  99309. }(BABYLON.Node));
  99310. BABYLON.VideoDome = VideoDome;
  99311. })(BABYLON || (BABYLON = {}));
  99312. //# sourceMappingURL=babylon.videoDome.js.map
  99313. 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"};
  99314. 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};"};
  99315. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  99316. globalObject["BABYLON"] = BABYLON;
  99317. //backwards compatibility
  99318. if(typeof earcut !== 'undefined') {
  99319. globalObject["Earcut"] = {
  99320. earcut: earcut
  99321. };
  99322. }
  99323. return BABYLON;
  99324. });
  99325. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(25)))
  99326. /***/ }),
  99327. /* 1 */
  99328. /***/ (function(module, exports, __webpack_require__) {
  99329. (function (global, factory) {
  99330. true ? module.exports = factory() :
  99331. typeof define === 'function' && define.amd ? define(factory) :
  99332. (global.deepmerge = factory());
  99333. }(this, (function () { 'use strict';
  99334. var isMergeableObject = function isMergeableObject(value) {
  99335. return isNonNullObject(value)
  99336. && !isSpecial(value)
  99337. };
  99338. function isNonNullObject(value) {
  99339. return !!value && typeof value === 'object'
  99340. }
  99341. function isSpecial(value) {
  99342. var stringValue = Object.prototype.toString.call(value);
  99343. return stringValue === '[object RegExp]'
  99344. || stringValue === '[object Date]'
  99345. || isReactElement(value)
  99346. }
  99347. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  99348. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  99349. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  99350. function isReactElement(value) {
  99351. return value.$$typeof === REACT_ELEMENT_TYPE
  99352. }
  99353. function emptyTarget(val) {
  99354. return Array.isArray(val) ? [] : {}
  99355. }
  99356. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  99357. var clone = !optionsArgument || optionsArgument.clone !== false;
  99358. return (clone && isMergeableObject(value))
  99359. ? deepmerge(emptyTarget(value), value, optionsArgument)
  99360. : value
  99361. }
  99362. function defaultArrayMerge(target, source, optionsArgument) {
  99363. return target.concat(source).map(function(element) {
  99364. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  99365. })
  99366. }
  99367. function mergeObject(target, source, optionsArgument) {
  99368. var destination = {};
  99369. if (isMergeableObject(target)) {
  99370. Object.keys(target).forEach(function(key) {
  99371. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  99372. });
  99373. }
  99374. Object.keys(source).forEach(function(key) {
  99375. if (!isMergeableObject(source[key]) || !target[key]) {
  99376. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  99377. } else {
  99378. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  99379. }
  99380. });
  99381. return destination
  99382. }
  99383. function deepmerge(target, source, optionsArgument) {
  99384. var sourceIsArray = Array.isArray(source);
  99385. var targetIsArray = Array.isArray(target);
  99386. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  99387. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  99388. if (!sourceAndTargetTypesMatch) {
  99389. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  99390. } else if (sourceIsArray) {
  99391. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  99392. return arrayMerge(target, source, optionsArgument)
  99393. } else {
  99394. return mergeObject(target, source, optionsArgument)
  99395. }
  99396. }
  99397. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  99398. if (!Array.isArray(array)) {
  99399. throw new Error('first argument should be an array')
  99400. }
  99401. return array.reduce(function(prev, next) {
  99402. return deepmerge(prev, next, optionsArgument)
  99403. }, {})
  99404. };
  99405. var deepmerge_1 = deepmerge;
  99406. return deepmerge_1;
  99407. })));
  99408. /***/ }),
  99409. /* 2 */
  99410. /***/ (function(module, exports, __webpack_require__) {
  99411. "use strict";
  99412. Object.defineProperty(exports, "__esModule", { value: true });
  99413. /**
  99414. * Is the provided string a URL?
  99415. *
  99416. * @param urlToCheck the url to inspect
  99417. */
  99418. function isUrl(urlToCheck) {
  99419. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  99420. return true;
  99421. }
  99422. return false;
  99423. }
  99424. exports.isUrl = isUrl;
  99425. /**
  99426. * Convert a string from kebab-case to camelCase
  99427. * @param s string to convert
  99428. */
  99429. function kebabToCamel(s) {
  99430. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  99431. }
  99432. exports.kebabToCamel = kebabToCamel;
  99433. //https://gist.github.com/youssman/745578062609e8acac9f
  99434. /**
  99435. * Convert a string from camelCase to kebab-case
  99436. * @param str string to convert
  99437. */
  99438. function camelToKebab(str) {
  99439. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  99440. }
  99441. exports.camelToKebab = camelToKebab;
  99442. /**
  99443. * This will extend an object with configuration values.
  99444. * What it practically does it take the keys from the configuration and set them on the object.
  99445. * I the configuration is a tree, it will traverse into the tree.
  99446. * @param object the object to extend
  99447. * @param config the configuration object that will extend the object
  99448. */
  99449. function extendClassWithConfig(object, config) {
  99450. if (!config)
  99451. return;
  99452. Object.keys(config).forEach(function (key) {
  99453. if (key in object && typeof object[key] !== 'function') {
  99454. // if (typeof object[key] === 'function') return;
  99455. // if it is an object, iterate internally until reaching basic types
  99456. if (typeof object[key] === 'object') {
  99457. extendClassWithConfig(object[key], config[key]);
  99458. }
  99459. else {
  99460. if (config[key] !== undefined) {
  99461. object[key] = config[key];
  99462. }
  99463. }
  99464. }
  99465. });
  99466. }
  99467. exports.extendClassWithConfig = extendClassWithConfig;
  99468. /***/ }),
  99469. /* 3 */
  99470. /***/ (function(module, exports, __webpack_require__) {
  99471. "use strict";
  99472. Object.defineProperty(exports, "__esModule", { value: true });
  99473. var babylonjs_1 = __webpack_require__(0);
  99474. var helper_1 = __webpack_require__(2);
  99475. /**
  99476. * This is a simple HTML mapper.
  99477. * This mapper parses a single HTML element and returns the configuration from its attributes.
  99478. * it parses numbers and boolean values to the corresponding variable types.
  99479. * The following HTML element:
  99480. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  99481. *
  99482. * {
  99483. * test: 1, //a number!
  99484. * randomFlag: boolean, //camelCase and boolean
  99485. * a: {
  99486. * string: {
  99487. * object: "test" //dot-separated object levels
  99488. * }
  99489. * }
  99490. * }
  99491. */
  99492. var HTMLMapper = /** @class */ (function () {
  99493. function HTMLMapper() {
  99494. }
  99495. /**
  99496. * Map a specific element and get configuration from it
  99497. * @param element the HTML element to analyze.
  99498. */
  99499. HTMLMapper.prototype.map = function (element) {
  99500. var config = {};
  99501. var _loop_1 = function (attrIdx) {
  99502. var attr = element.attributes.item(attrIdx);
  99503. if (!attr) {
  99504. return "continue";
  99505. }
  99506. // map "object.property" to the right configuration place.
  99507. var split = attr.nodeName.split('.');
  99508. split.reduce(function (currentConfig, key, idx) {
  99509. //convert html-style to json-style
  99510. var camelKey = helper_1.kebabToCamel(key);
  99511. if (idx === split.length - 1) {
  99512. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  99513. if (val === "true") {
  99514. val = true;
  99515. }
  99516. else if (val === "false") {
  99517. val = false;
  99518. }
  99519. else {
  99520. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  99521. if (isnum) {
  99522. var number = parseFloat(val);
  99523. if (!isNaN(number)) {
  99524. val = number;
  99525. }
  99526. }
  99527. }
  99528. currentConfig[camelKey] = val;
  99529. }
  99530. else {
  99531. currentConfig[camelKey] = currentConfig[camelKey] || {};
  99532. }
  99533. return currentConfig[camelKey];
  99534. }, config);
  99535. };
  99536. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  99537. _loop_1(attrIdx);
  99538. }
  99539. return config;
  99540. };
  99541. return HTMLMapper;
  99542. }());
  99543. /**
  99544. * A simple string-to-JSON mapper.
  99545. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  99546. */
  99547. var JSONMapper = /** @class */ (function () {
  99548. function JSONMapper() {
  99549. }
  99550. JSONMapper.prototype.map = function (rawSource) {
  99551. return JSON.parse(rawSource);
  99552. };
  99553. return JSONMapper;
  99554. }());
  99555. /**
  99556. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  99557. * DOM elements and attributes.
  99558. */
  99559. var DOMMapper = /** @class */ (function () {
  99560. function DOMMapper() {
  99561. }
  99562. /**
  99563. * The mapping function that will convert HTML data to a viewer configuration object
  99564. * @param baseElement the baseElement from which to start traversing
  99565. * @returns a ViewerCOnfiguration object from the provided HTML Element
  99566. */
  99567. DOMMapper.prototype.map = function (baseElement) {
  99568. var htmlMapper = new HTMLMapper();
  99569. var config = htmlMapper.map(baseElement);
  99570. var traverseChildren = function (element, partConfig) {
  99571. var children = element.children;
  99572. if (children.length) {
  99573. for (var i = 0; i < children.length; ++i) {
  99574. var item = children.item(i);
  99575. // use the HTML Mapper to read configuration from a single element
  99576. var configMapped = htmlMapper.map(item);
  99577. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  99578. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  99579. partConfig[key] = [];
  99580. }
  99581. else {
  99582. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  99583. partConfig.push(configMapped);
  99584. }
  99585. else if (partConfig[key]) {
  99586. //exists already! probably an array
  99587. element.setAttribute('array', 'true');
  99588. var oldItem = partConfig[key];
  99589. partConfig = [oldItem, configMapped];
  99590. }
  99591. else {
  99592. partConfig[key] = configMapped;
  99593. }
  99594. }
  99595. traverseChildren(item, partConfig[key] || configMapped);
  99596. }
  99597. }
  99598. return partConfig;
  99599. };
  99600. traverseChildren(baseElement, config);
  99601. return config;
  99602. };
  99603. return DOMMapper;
  99604. }());
  99605. /**
  99606. * The MapperManager manages the different implemented mappers.
  99607. * It allows the user to register new mappers as well and use them to parse their own configuration data
  99608. */
  99609. var MapperManager = /** @class */ (function () {
  99610. function MapperManager() {
  99611. this._mappers = {
  99612. "html": new HTMLMapper(),
  99613. "json": new JSONMapper(),
  99614. "dom": new DOMMapper()
  99615. };
  99616. }
  99617. /**
  99618. * Get a specific configuration mapper.
  99619. *
  99620. * @param type the name of the mapper to load
  99621. */
  99622. MapperManager.prototype.getMapper = function (type) {
  99623. if (!this._mappers[type]) {
  99624. babylonjs_1.Tools.Error("No mapper defined for " + type);
  99625. }
  99626. return this._mappers[type];
  99627. };
  99628. /**
  99629. * Use this functio to register your own configuration mapper.
  99630. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  99631. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  99632. * @param mapper The implemented mapper
  99633. */
  99634. MapperManager.prototype.registerMapper = function (type, mapper) {
  99635. this._mappers[type] = mapper;
  99636. };
  99637. /**
  99638. * Dispose the mapper manager and all of its mappers.
  99639. */
  99640. MapperManager.prototype.dispose = function () {
  99641. this._mappers = {};
  99642. };
  99643. /**
  99644. * The default mapper is the JSON mapper.
  99645. */
  99646. MapperManager.DefaultMapper = 'json';
  99647. return MapperManager;
  99648. }());
  99649. exports.MapperManager = MapperManager;
  99650. /**
  99651. * mapperManager is a singleton of the type MapperManager.
  99652. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  99653. * or indirectly with using BabylonViewer.disposeAll()
  99654. */
  99655. exports.mapperManager = new MapperManager();
  99656. /***/ }),
  99657. /* 4 */
  99658. /***/ (function(module, exports, __webpack_require__) {
  99659. "use strict";
  99660. Object.defineProperty(exports, "__esModule", { value: true });
  99661. var babylonjs_1 = __webpack_require__(0);
  99662. var modelAnimation_1 = __webpack_require__(30);
  99663. var deepmerge = __webpack_require__(1);
  99664. var helper_1 = __webpack_require__(2);
  99665. /**
  99666. * The current state of the model
  99667. */
  99668. var ModelState;
  99669. (function (ModelState) {
  99670. ModelState[ModelState["INIT"] = 0] = "INIT";
  99671. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  99672. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  99673. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  99674. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  99675. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  99676. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  99677. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  99678. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  99679. /**
  99680. * The viewer model is a container for all assets representing a sngle loaded model.
  99681. */
  99682. var ViewerModel = /** @class */ (function () {
  99683. function ViewerModel(_viewer, modelConfiguration) {
  99684. var _this = this;
  99685. this._viewer = _viewer;
  99686. /**
  99687. * the list of meshes that are a part of this model
  99688. */
  99689. this._meshes = [];
  99690. /**
  99691. * ParticleSystems connected to this model
  99692. */
  99693. this.particleSystems = [];
  99694. /**
  99695. * Skeletons defined in this model
  99696. */
  99697. this.skeletons = [];
  99698. this._loaderDone = false;
  99699. this._animatables = [];
  99700. this._frameRate = 60;
  99701. this._shadowsRenderedAfterLoad = false;
  99702. this.onLoadedObservable = new babylonjs_1.Observable();
  99703. this.onLoadErrorObservable = new babylonjs_1.Observable();
  99704. this.onLoadProgressObservable = new babylonjs_1.Observable();
  99705. this.onCompleteObservable = new babylonjs_1.Observable();
  99706. this.onAfterConfigure = new babylonjs_1.Observable();
  99707. this.state = ModelState.INIT;
  99708. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  99709. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", this._viewer.sceneManager.scene);
  99710. this._pivotMesh.parent = this.rootMesh;
  99711. // rotate 180, gltf fun
  99712. this._pivotMesh.rotation.y += Math.PI;
  99713. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  99714. this._animations = [];
  99715. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  99716. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  99717. this._viewer.sceneManager.models.push(this);
  99718. this._viewer.onModelAddedObservable.notifyObservers(this);
  99719. if (this._modelConfiguration.entryAnimation) {
  99720. this.rootMesh.setEnabled(false);
  99721. }
  99722. this.onLoadedObservable.add(function () {
  99723. _this.updateConfiguration(_this._modelConfiguration);
  99724. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  99725. _this._initAnimations();
  99726. });
  99727. this.onCompleteObservable.add(function () {
  99728. _this.state = ModelState.COMPLETE;
  99729. });
  99730. }
  99731. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  99732. get: function () {
  99733. return this._shadowsRenderedAfterLoad;
  99734. },
  99735. set: function (rendered) {
  99736. if (!rendered) {
  99737. throw new Error("can only be enabled");
  99738. }
  99739. else {
  99740. this._shadowsRenderedAfterLoad = rendered;
  99741. }
  99742. },
  99743. enumerable: true,
  99744. configurable: true
  99745. });
  99746. Object.defineProperty(ViewerModel.prototype, "enabled", {
  99747. /**
  99748. * Is this model enabled?
  99749. */
  99750. get: function () {
  99751. return this.rootMesh.isEnabled();
  99752. },
  99753. /**
  99754. * Set whether this model is enabled or not.
  99755. */
  99756. set: function (enable) {
  99757. this.rootMesh.setEnabled(enable);
  99758. },
  99759. enumerable: true,
  99760. configurable: true
  99761. });
  99762. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  99763. set: function (done) {
  99764. this._loaderDone = done;
  99765. this._checkCompleteState();
  99766. },
  99767. enumerable: true,
  99768. configurable: true
  99769. });
  99770. ViewerModel.prototype._checkCompleteState = function () {
  99771. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  99772. this._modelComplete();
  99773. }
  99774. };
  99775. /**
  99776. * Get the viewer showing this model
  99777. */
  99778. ViewerModel.prototype.getViewer = function () {
  99779. return this._viewer;
  99780. };
  99781. /**
  99782. * Add a mesh to this model.
  99783. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  99784. *
  99785. * @param mesh the new mesh to add
  99786. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  99787. */
  99788. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  99789. if (!mesh.parent) {
  99790. mesh.parent = this._pivotMesh;
  99791. }
  99792. mesh.receiveShadows = !!this.configuration.receiveShadows;
  99793. this._meshes.push(mesh);
  99794. if (triggerLoaded) {
  99795. return this.onLoadedObservable.notifyObserversWithPromise(this);
  99796. }
  99797. };
  99798. Object.defineProperty(ViewerModel.prototype, "meshes", {
  99799. /**
  99800. * get the list of meshes (excluding the root mesh)
  99801. */
  99802. get: function () {
  99803. return this._meshes;
  99804. },
  99805. enumerable: true,
  99806. configurable: true
  99807. });
  99808. Object.defineProperty(ViewerModel.prototype, "configuration", {
  99809. /**
  99810. * Get the model's configuration
  99811. */
  99812. get: function () {
  99813. return this._modelConfiguration;
  99814. },
  99815. /**
  99816. * (Re-)set the model's entire configuration
  99817. * @param newConfiguration the new configuration to replace the new one
  99818. */
  99819. set: function (newConfiguration) {
  99820. this._modelConfiguration = newConfiguration;
  99821. this._configureModel();
  99822. },
  99823. enumerable: true,
  99824. configurable: true
  99825. });
  99826. /**
  99827. * Update the current configuration with new values.
  99828. * Configuration will not be overwritten, but merged with the new configuration.
  99829. * Priority is to the new configuration
  99830. * @param newConfiguration the configuration to be merged into the current configuration;
  99831. */
  99832. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  99833. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  99834. this._configureModel();
  99835. };
  99836. ViewerModel.prototype._initAnimations = function () {
  99837. var _this = this;
  99838. // check if this is not a gltf loader and init the animations
  99839. if (this.skeletons.length) {
  99840. this.skeletons.forEach(function (skeleton, idx) {
  99841. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  99842. skeleton.getAnimatables().forEach(function (a) {
  99843. if (a.animations[0]) {
  99844. ag.addTargetedAnimation(a.animations[0], a);
  99845. }
  99846. });
  99847. _this.addAnimationGroup(ag);
  99848. });
  99849. }
  99850. var completeCallback = function () {
  99851. };
  99852. if (this._modelConfiguration.animation) {
  99853. if (this._modelConfiguration.animation.playOnce) {
  99854. this._animations.forEach(function (a) {
  99855. a.playMode = 0 /* ONCE */;
  99856. });
  99857. }
  99858. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  99859. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  99860. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  99861. completeCallback = function () {
  99862. _this.playAnimation(animationName_1);
  99863. };
  99864. }
  99865. }
  99866. this._enterScene(completeCallback);
  99867. };
  99868. /**
  99869. * Animates the model from the current position to the default position
  99870. * @param completeCallback A function to call when the animation has completed
  99871. */
  99872. ViewerModel.prototype._enterScene = function (completeCallback) {
  99873. var _this = this;
  99874. var callback = function () {
  99875. _this.state = ModelState.ENTRYDONE;
  99876. _this._viewer.sceneManager.animationBlendingEnabled = true;
  99877. _this._checkCompleteState();
  99878. if (completeCallback)
  99879. completeCallback();
  99880. };
  99881. if (!this._entryAnimation) {
  99882. callback();
  99883. return;
  99884. }
  99885. this.rootMesh.setEnabled(true);
  99886. // disable blending for the sake of the entry animation;
  99887. this._viewer.sceneManager.animationBlendingEnabled = false;
  99888. this._applyAnimation(this._entryAnimation, true, callback);
  99889. };
  99890. /**
  99891. * Animates the model from the current position to the exit-screen position
  99892. * @param completeCallback A function to call when the animation has completed
  99893. */
  99894. ViewerModel.prototype._exitScene = function (completeCallback) {
  99895. if (!this._exitAnimation) {
  99896. completeCallback();
  99897. return;
  99898. }
  99899. this._applyAnimation(this._exitAnimation, false, completeCallback);
  99900. };
  99901. ViewerModel.prototype._modelComplete = function () {
  99902. var _this = this;
  99903. //reapply material defines to be sure:
  99904. var meshes = this._pivotMesh.getChildMeshes(false);
  99905. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  99906. _this._applyModelMaterialConfiguration(mesh.material);
  99907. });
  99908. this.state = ModelState.COMPLETE;
  99909. this.onCompleteObservable.notifyObservers(this);
  99910. };
  99911. /**
  99912. * Add a new animation group to this model.
  99913. * @param animationGroup the new animation group to be added
  99914. */
  99915. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  99916. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  99917. };
  99918. /**
  99919. * Get the ModelAnimation array
  99920. */
  99921. ViewerModel.prototype.getAnimations = function () {
  99922. return this._animations;
  99923. };
  99924. /**
  99925. * Get the animations' names. Using the names you can play a specific animation.
  99926. */
  99927. ViewerModel.prototype.getAnimationNames = function () {
  99928. return this._animations.map(function (a) { return a.name; });
  99929. };
  99930. /**
  99931. * Get an animation by the provided name. Used mainly when playing n animation.
  99932. * @param name the name of the animation to find
  99933. */
  99934. ViewerModel.prototype._getAnimationByName = function (name) {
  99935. // can't use .find, noe available on IE
  99936. var filtered = this._animations.filter(function (a) { return a.name === name; });
  99937. // what the next line means - if two animations have the same name, they will not be returned!
  99938. if (filtered.length === 1) {
  99939. return filtered[0];
  99940. }
  99941. else {
  99942. return null;
  99943. }
  99944. };
  99945. /**
  99946. * Choose an initialized animation using its name and start playing it
  99947. * @param name the name of the animation to play
  99948. * @returns The model aniamtion to be played.
  99949. */
  99950. ViewerModel.prototype.playAnimation = function (name) {
  99951. var animation = this.setCurrentAnimationByName(name);
  99952. if (animation) {
  99953. animation.start();
  99954. }
  99955. return animation;
  99956. };
  99957. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  99958. var animation = this._getAnimationByName(name);
  99959. if (animation) {
  99960. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  99961. this.currentAnimation.stop();
  99962. }
  99963. this.currentAnimation = animation;
  99964. return animation;
  99965. }
  99966. else {
  99967. throw new Error("animation not found - " + name);
  99968. }
  99969. };
  99970. ViewerModel.prototype._configureModel = function () {
  99971. var _this = this;
  99972. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  99973. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  99974. var updateMeshesWithNoParent = function (variable, value, param) {
  99975. meshesWithNoParent.forEach(function (mesh) {
  99976. if (param) {
  99977. mesh[variable][param] = value;
  99978. }
  99979. else {
  99980. mesh[variable] = value;
  99981. }
  99982. });
  99983. };
  99984. var updateXYZ = function (variable, configValues) {
  99985. if (configValues.x !== undefined) {
  99986. updateMeshesWithNoParent(variable, configValues.x, 'x');
  99987. }
  99988. if (configValues.y !== undefined) {
  99989. updateMeshesWithNoParent(variable, configValues.y, 'y');
  99990. }
  99991. if (configValues.z !== undefined) {
  99992. updateMeshesWithNoParent(variable, configValues.z, 'z');
  99993. }
  99994. if (configValues.w !== undefined) {
  99995. updateMeshesWithNoParent(variable, configValues.w, 'w');
  99996. }
  99997. };
  99998. if (this._modelConfiguration.normalize) {
  99999. var center = false;
  100000. var unitSize = false;
  100001. var parentIndex = void 0;
  100002. if (this._modelConfiguration.normalize === true) {
  100003. center = true;
  100004. unitSize = true;
  100005. }
  100006. else {
  100007. center = !!this._modelConfiguration.normalize.center;
  100008. unitSize = !!this._modelConfiguration.normalize.unitSize;
  100009. parentIndex = this._modelConfiguration.normalize.parentIndex;
  100010. }
  100011. var meshesToNormalize = [];
  100012. if (parentIndex !== undefined) {
  100013. meshesToNormalize.push(this._meshes[parentIndex]);
  100014. }
  100015. else {
  100016. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  100017. }
  100018. if (unitSize) {
  100019. meshesToNormalize.forEach(function (mesh) {
  100020. mesh.normalizeToUnitCube(true);
  100021. mesh.computeWorldMatrix(true);
  100022. });
  100023. }
  100024. if (center) {
  100025. meshesToNormalize.forEach(function (mesh) {
  100026. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  100027. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  100028. var halfSizeVec = sizeVec.scale(0.5);
  100029. var center = boundingInfo.min.add(halfSizeVec);
  100030. mesh.position = center.scale(-1);
  100031. mesh.position.y += halfSizeVec.y;
  100032. // Recompute Info.
  100033. mesh.computeWorldMatrix(true);
  100034. });
  100035. }
  100036. }
  100037. else {
  100038. // if centered, should be done here
  100039. }
  100040. // position?
  100041. if (this._modelConfiguration.position) {
  100042. updateXYZ('position', this._modelConfiguration.position);
  100043. }
  100044. if (this._modelConfiguration.rotation) {
  100045. //quaternion?
  100046. if (this._modelConfiguration.rotation.w) {
  100047. meshesWithNoParent.forEach(function (mesh) {
  100048. if (!mesh.rotationQuaternion) {
  100049. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  100050. }
  100051. });
  100052. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  100053. }
  100054. else {
  100055. updateXYZ('rotation', this._modelConfiguration.rotation);
  100056. }
  100057. }
  100058. if (this._modelConfiguration.rotationOffsetAxis) {
  100059. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  100060. meshesWithNoParent.forEach(function (m) {
  100061. if (_this._modelConfiguration.rotationOffsetAngle) {
  100062. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  100063. }
  100064. });
  100065. }
  100066. if (this._modelConfiguration.scaling) {
  100067. updateXYZ('scaling', this._modelConfiguration.scaling);
  100068. }
  100069. if (this._modelConfiguration.castShadow) {
  100070. this._meshes.forEach(function (mesh) {
  100071. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  100072. });
  100073. }
  100074. var meshes = this._pivotMesh.getChildMeshes(false);
  100075. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  100076. _this._applyModelMaterialConfiguration(mesh.material);
  100077. });
  100078. if (this._modelConfiguration.entryAnimation) {
  100079. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  100080. }
  100081. if (this._modelConfiguration.exitAnimation) {
  100082. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  100083. }
  100084. this.onAfterConfigure.notifyObservers(this);
  100085. };
  100086. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  100087. var anim = {
  100088. time: 0.5
  100089. };
  100090. if (animConfig.scaling) {
  100091. anim.scaling = babylonjs_1.Vector3.Zero();
  100092. }
  100093. if (animConfig.easingFunction !== undefined) {
  100094. anim.easingFunction = animConfig.easingFunction;
  100095. }
  100096. if (animConfig.easingMode !== undefined) {
  100097. anim.easingMode = animConfig.easingMode;
  100098. }
  100099. helper_1.extendClassWithConfig(anim, animConfig);
  100100. return anim;
  100101. };
  100102. /**
  100103. * Apply a material configuration to a material
  100104. * @param material Material to apply configuration to
  100105. */
  100106. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  100107. if (!this._modelConfiguration.material)
  100108. return;
  100109. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  100110. if (material instanceof babylonjs_1.PBRMaterial) {
  100111. if (this._modelConfiguration.material.directIntensity !== undefined) {
  100112. material.directIntensity = this._modelConfiguration.material.directIntensity;
  100113. }
  100114. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  100115. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  100116. }
  100117. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  100118. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  100119. }
  100120. if (this._modelConfiguration.material.directEnabled !== undefined) {
  100121. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  100122. }
  100123. if (this._viewer.sceneManager.reflectionColor) {
  100124. material.reflectionColor = this._viewer.sceneManager.reflectionColor;
  100125. }
  100126. }
  100127. else if (material instanceof babylonjs_1.MultiMaterial) {
  100128. for (var i = 0; i < material.subMaterials.length; i++) {
  100129. var subMaterial = material.subMaterials[i];
  100130. if (subMaterial) {
  100131. this._applyModelMaterialConfiguration(subMaterial);
  100132. }
  100133. }
  100134. }
  100135. };
  100136. /**
  100137. * Start entry/exit animation given an animation configuration
  100138. * @param animationConfiguration Entry/Exit animation configuration
  100139. * @param isEntry Pass true if the animation is an entry animation
  100140. * @param completeCallback Callback to execute when the animation completes
  100141. */
  100142. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  100143. var animations = [];
  100144. //scale
  100145. if (animationConfiguration.scaling) {
  100146. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  100147. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  100148. if (!scaleStart.equals(scaleEnd)) {
  100149. this.rootMesh.scaling = scaleStart;
  100150. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  100151. animations.push(this._scaleTransition);
  100152. }
  100153. }
  100154. //Start the animation(s)
  100155. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  100156. completeCallback(); });
  100157. };
  100158. /**
  100159. * Begin @animations with the specified @easingFunction
  100160. * @param animations The BABYLON Animations to begin
  100161. * @param duration of transition, in seconds
  100162. * @param easingFunction An easing function to apply
  100163. * @param easingMode A easing mode to apply to the easingFunction
  100164. * @param onAnimationEnd Call back trigger at the end of the animation.
  100165. */
  100166. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  100167. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  100168. if (easingFunction) {
  100169. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  100170. var animation = animations_1[_i];
  100171. easingFunction.setEasingMode(easingMode);
  100172. animation.setEasingFunction(easingFunction);
  100173. }
  100174. }
  100175. //Stop any current animations before starting the new one - merging not yet supported.
  100176. this.stopAllAnimations();
  100177. this.rootMesh.animations = animations;
  100178. if (this._viewer.sceneManager.scene.beginAnimation) {
  100179. var animatable = this._viewer.sceneManager.scene.beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  100180. if (onAnimationEnd) {
  100181. onAnimationEnd();
  100182. }
  100183. });
  100184. this._animatables.push(animatable);
  100185. }
  100186. };
  100187. /**
  100188. * Sets key values on an Animation from first to last frame.
  100189. * @param animation The Babylon animation object to set keys on
  100190. * @param startValue The value of the first key
  100191. * @param endValue The value of the last key
  100192. * @param duration The duration of the animation, used to determine the end frame
  100193. */
  100194. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  100195. animation.setKeys([
  100196. {
  100197. frame: 0,
  100198. value: startValue
  100199. },
  100200. {
  100201. frame: this._frameRate * duration,
  100202. value: endValue
  100203. }
  100204. ]);
  100205. };
  100206. /**
  100207. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  100208. * @param easingFunctionID The enum of the easing funtion to create
  100209. * @return The newly created Babylon easing function object
  100210. */
  100211. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  100212. var easingFunction;
  100213. switch (easingFunctionID) {
  100214. case 1 /* CircleEase */:
  100215. easingFunction = new babylonjs_1.CircleEase();
  100216. break;
  100217. case 2 /* BackEase */:
  100218. easingFunction = new babylonjs_1.BackEase(0.3);
  100219. break;
  100220. case 3 /* BounceEase */:
  100221. easingFunction = new babylonjs_1.BounceEase();
  100222. break;
  100223. case 4 /* CubicEase */:
  100224. easingFunction = new babylonjs_1.CubicEase();
  100225. break;
  100226. case 5 /* ElasticEase */:
  100227. easingFunction = new babylonjs_1.ElasticEase();
  100228. break;
  100229. case 6 /* ExponentialEase */:
  100230. easingFunction = new babylonjs_1.ExponentialEase();
  100231. break;
  100232. case 7 /* PowerEase */:
  100233. easingFunction = new babylonjs_1.PowerEase();
  100234. break;
  100235. case 8 /* QuadraticEase */:
  100236. easingFunction = new babylonjs_1.QuadraticEase();
  100237. break;
  100238. case 9 /* QuarticEase */:
  100239. easingFunction = new babylonjs_1.QuarticEase();
  100240. break;
  100241. case 10 /* QuinticEase */:
  100242. easingFunction = new babylonjs_1.QuinticEase();
  100243. break;
  100244. case 11 /* SineEase */:
  100245. easingFunction = new babylonjs_1.SineEase();
  100246. break;
  100247. default:
  100248. babylonjs_1.Tools.Log("No ease function found");
  100249. break;
  100250. }
  100251. return easingFunction;
  100252. };
  100253. /**
  100254. * Stops and removes all animations that have been applied to the model
  100255. */
  100256. ViewerModel.prototype.stopAllAnimations = function () {
  100257. if (this.rootMesh) {
  100258. this.rootMesh.animations = [];
  100259. }
  100260. if (this.currentAnimation) {
  100261. this.currentAnimation.stop();
  100262. }
  100263. while (this._animatables.length) {
  100264. this._animatables[0].onAnimationEnd = null;
  100265. this._animatables[0].stop();
  100266. this._animatables.shift();
  100267. }
  100268. };
  100269. /**
  100270. * Will remove this model from the viewer (but NOT dispose it).
  100271. */
  100272. ViewerModel.prototype.remove = function () {
  100273. this.stopAllAnimations();
  100274. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  100275. // hide it
  100276. this.rootMesh.isVisible = false;
  100277. this._viewer.onModelRemovedObservable.notifyObservers(this);
  100278. };
  100279. /**
  100280. * Dispose this model, including all of its associated assets.
  100281. */
  100282. ViewerModel.prototype.dispose = function () {
  100283. this.remove();
  100284. this.onAfterConfigure.clear();
  100285. this.onLoadedObservable.clear();
  100286. this.onLoadErrorObservable.clear();
  100287. this.onLoadProgressObservable.clear();
  100288. if (this.loader && this.loader.name === "gltf") {
  100289. this.loader.dispose();
  100290. }
  100291. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  100292. this.particleSystems.length = 0;
  100293. this.skeletons.forEach(function (s) { return s.dispose(); });
  100294. this.skeletons.length = 0;
  100295. this._animations.forEach(function (ag) { return ag.dispose(); });
  100296. this._animations.length = 0;
  100297. this.rootMesh.dispose(false, true);
  100298. };
  100299. return ViewerModel;
  100300. }());
  100301. exports.ViewerModel = ViewerModel;
  100302. /***/ }),
  100303. /* 5 */
  100304. /***/ (function(module, exports, __webpack_require__) {
  100305. "use strict";
  100306. Object.defineProperty(exports, "__esModule", { value: true });
  100307. var babylonjs_1 = __webpack_require__(0);
  100308. /**
  100309. * Receives Telemetry events and raises events to the API
  100310. */
  100311. var TelemetryManager = /** @class */ (function () {
  100312. function TelemetryManager() {
  100313. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  100314. this._event = this._eventEnabled;
  100315. }
  100316. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  100317. /**
  100318. * Receives a telemetry event
  100319. * @param event The name of the Telemetry event
  100320. * @param details An additional value, or an object containing a list of property/value pairs
  100321. */
  100322. get: function () {
  100323. return this._event;
  100324. },
  100325. enumerable: true,
  100326. configurable: true
  100327. });
  100328. /**
  100329. * Log a Telemetry event for errors raised on the WebGL context.
  100330. * @param engine The Babylon engine with the WebGL context.
  100331. */
  100332. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  100333. var engine = viewer.engine;
  100334. if (!engine) {
  100335. return;
  100336. }
  100337. var logErrors = true;
  100338. while (logErrors) {
  100339. var gl = engine._gl;
  100340. if (gl && gl.getError) {
  100341. var error = gl.getError();
  100342. if (error === gl.NO_ERROR) {
  100343. logErrors = false;
  100344. }
  100345. else {
  100346. this.broadcast("WebGL Error", viewer, { error: error });
  100347. }
  100348. }
  100349. else {
  100350. logErrors = false;
  100351. }
  100352. }
  100353. };
  100354. Object.defineProperty(TelemetryManager.prototype, "enable", {
  100355. /**
  100356. * Enable or disable telemetry events
  100357. * @param enabled Boolan, true if events are enabled
  100358. */
  100359. set: function (enabled) {
  100360. if (enabled) {
  100361. this._event = this._eventEnabled;
  100362. }
  100363. else {
  100364. this._event = this._eventDisabled;
  100365. }
  100366. },
  100367. enumerable: true,
  100368. configurable: true
  100369. });
  100370. /**
  100371. * Called on event when disabled, typically do nothing here
  100372. */
  100373. TelemetryManager.prototype._eventDisabled = function () {
  100374. // nothing to do
  100375. };
  100376. /**
  100377. * Called on event when enabled
  100378. * @param event - The name of the Telemetry event
  100379. * @param details An additional value, or an object containing a list of property/value pairs
  100380. */
  100381. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  100382. var telemetryData = {
  100383. viewer: viewer,
  100384. event: event,
  100385. session: this.session,
  100386. date: new Date(),
  100387. now: window.performance ? window.performance.now() : Date.now(),
  100388. detail: null
  100389. };
  100390. if (typeof details === "object") {
  100391. for (var attr in details) {
  100392. if (details.hasOwnProperty(attr)) {
  100393. telemetryData[attr] = details[attr];
  100394. }
  100395. }
  100396. }
  100397. else if (details) {
  100398. telemetryData.detail = details;
  100399. }
  100400. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  100401. };
  100402. Object.defineProperty(TelemetryManager.prototype, "session", {
  100403. /**
  100404. * Returns the current session ID or creates one if it doesn't exixt
  100405. * @return The current session ID
  100406. */
  100407. get: function () {
  100408. if (!this._currentSessionId) {
  100409. //String + Timestamp + Random Integer
  100410. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  100411. }
  100412. return this._currentSessionId;
  100413. },
  100414. enumerable: true,
  100415. configurable: true
  100416. });
  100417. /**
  100418. * Disposes the telemetry manager
  100419. */
  100420. TelemetryManager.prototype.dispose = function () {
  100421. this.onEventBroadcastedObservable.clear();
  100422. delete this.onEventBroadcastedObservable;
  100423. };
  100424. return TelemetryManager;
  100425. }());
  100426. exports.TelemetryManager = TelemetryManager;
  100427. exports.telemetryManager = new TelemetryManager();
  100428. /***/ }),
  100429. /* 6 */
  100430. /***/ (function(module, exports, __webpack_require__) {
  100431. "use strict";
  100432. function __export(m) {
  100433. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  100434. }
  100435. Object.defineProperty(exports, "__esModule", { value: true });
  100436. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  100437. var mappers_1 = __webpack_require__(3);
  100438. exports.mapperManager = mappers_1.mapperManager;
  100439. var globals_1 = __webpack_require__(7);
  100440. exports.viewerGlobals = globals_1.viewerGlobals;
  100441. var viewerManager_1 = __webpack_require__(8);
  100442. exports.viewerManager = viewerManager_1.viewerManager;
  100443. var defaultViewer_1 = __webpack_require__(9);
  100444. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  100445. var viewer_1 = __webpack_require__(10);
  100446. exports.AbstractViewer = viewer_1.AbstractViewer;
  100447. var telemetryManager_1 = __webpack_require__(5);
  100448. exports.telemetryManager = telemetryManager_1.telemetryManager;
  100449. var modelLoader_1 = __webpack_require__(22);
  100450. exports.ModelLoader = modelLoader_1.ModelLoader;
  100451. var viewerModel_1 = __webpack_require__(4);
  100452. exports.ViewerModel = viewerModel_1.ViewerModel;
  100453. exports.ModelState = viewerModel_1.ModelState;
  100454. /**
  100455. * BabylonJS Viewer
  100456. *
  100457. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  100458. */
  100459. var BABYLON = __webpack_require__(0);
  100460. exports.BABYLON = BABYLON;
  100461. // load needed modules.
  100462. __webpack_require__(23);
  100463. __webpack_require__(56);
  100464. var initializer_1 = __webpack_require__(57);
  100465. exports.InitTags = initializer_1.InitTags;
  100466. // promise polyfill, if needed!
  100467. BABYLON.PromisePolyfill.Apply();
  100468. initializer_1.initListeners();
  100469. //deprectaed, here for backwards compatibility
  100470. var disableInit = globals_1.viewerGlobals.disableInit;
  100471. exports.disableInit = disableInit;
  100472. /**
  100473. * Dispose all viewers currently registered
  100474. */
  100475. function disposeAll() {
  100476. viewerManager_1.viewerManager.dispose();
  100477. mappers_1.mapperManager.dispose();
  100478. telemetryManager_1.telemetryManager.dispose();
  100479. }
  100480. exports.disposeAll = disposeAll;
  100481. var Version = BABYLON.Engine.Version;
  100482. exports.Version = Version;
  100483. console.log("Babylon.js viewer (v" + Version + ")");
  100484. // export publicliy all configuration interfaces
  100485. __export(__webpack_require__(21));
  100486. /***/ }),
  100487. /* 7 */
  100488. /***/ (function(module, exports, __webpack_require__) {
  100489. "use strict";
  100490. Object.defineProperty(exports, "__esModule", { value: true });
  100491. var ViewerGlobals = /** @class */ (function () {
  100492. function ViewerGlobals() {
  100493. this.disableInit = false;
  100494. this.disableWebGL2Support = false;
  100495. }
  100496. return ViewerGlobals;
  100497. }());
  100498. exports.ViewerGlobals = ViewerGlobals;
  100499. exports.viewerGlobals = new ViewerGlobals();
  100500. /***/ }),
  100501. /* 8 */
  100502. /***/ (function(module, exports, __webpack_require__) {
  100503. "use strict";
  100504. Object.defineProperty(exports, "__esModule", { value: true });
  100505. var babylonjs_1 = __webpack_require__(0);
  100506. /**
  100507. * The viewer manager is the container for all viewers currently registered on this page.
  100508. * It is possible to have more than one viewer on a single page.
  100509. */
  100510. var ViewerManager = /** @class */ (function () {
  100511. function ViewerManager() {
  100512. this._viewers = {};
  100513. this.onViewerAddedObservable = new babylonjs_1.Observable();
  100514. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  100515. }
  100516. /**
  100517. * Adding a new viewer to the viewer manager and start tracking it.
  100518. * @param viewer the viewer to add
  100519. */
  100520. ViewerManager.prototype.addViewer = function (viewer) {
  100521. this._viewers[viewer.getBaseId()] = viewer;
  100522. this._onViewerAdded(viewer);
  100523. };
  100524. /**
  100525. * remove a viewer from the viewer manager
  100526. * @param viewer the viewer to remove
  100527. */
  100528. ViewerManager.prototype.removeViewer = function (viewer) {
  100529. var id = viewer.getBaseId();
  100530. delete this._viewers[id];
  100531. this.onViewerRemovedObservable.notifyObservers(id);
  100532. };
  100533. /**
  100534. * 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)
  100535. * @param id the id of the HTMl element (or the viewer's, if none provided)
  100536. */
  100537. ViewerManager.prototype.getViewerById = function (id) {
  100538. return this._viewers[id];
  100539. };
  100540. /**
  100541. * Get a viewer using a container element
  100542. * @param element the HTML element to search viewers associated with
  100543. */
  100544. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  100545. for (var id in this._viewers) {
  100546. if (this._viewers[id].containerElement === element) {
  100547. return this.getViewerById(id);
  100548. }
  100549. }
  100550. };
  100551. /**
  100552. * Get a promise that will fullfil when this viewer was initialized.
  100553. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  100554. * you will get the viewer after everything was already configured.
  100555. * @param id the viewer id to find
  100556. */
  100557. ViewerManager.prototype.getViewerPromiseById = function (id) {
  100558. var _this = this;
  100559. return new Promise(function (resolve, reject) {
  100560. var localViewer = _this.getViewerById(id);
  100561. if (localViewer) {
  100562. return resolve(localViewer);
  100563. }
  100564. var viewerFunction = function (viewer) {
  100565. if (viewer.getBaseId() === id) {
  100566. resolve(viewer);
  100567. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  100568. }
  100569. };
  100570. _this.onViewerAddedObservable.add(viewerFunction);
  100571. });
  100572. };
  100573. ViewerManager.prototype._onViewerAdded = function (viewer) {
  100574. this.onViewerAdded && this.onViewerAdded(viewer);
  100575. this.onViewerAddedObservable.notifyObservers(viewer);
  100576. };
  100577. /**
  100578. * dispose the manager and all of its associated viewers
  100579. */
  100580. ViewerManager.prototype.dispose = function () {
  100581. delete this._onViewerAdded;
  100582. for (var id in this._viewers) {
  100583. this._viewers[id].dispose();
  100584. }
  100585. this.onViewerAddedObservable.clear();
  100586. this.onViewerRemovedObservable.clear();
  100587. };
  100588. return ViewerManager;
  100589. }());
  100590. exports.ViewerManager = ViewerManager;
  100591. exports.viewerManager = new ViewerManager();
  100592. /***/ }),
  100593. /* 9 */
  100594. /***/ (function(module, exports, __webpack_require__) {
  100595. "use strict";
  100596. var __extends = (this && this.__extends) || (function () {
  100597. var extendStatics = Object.setPrototypeOf ||
  100598. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  100599. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  100600. return function (d, b) {
  100601. extendStatics(d, b);
  100602. function __() { this.constructor = d; }
  100603. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  100604. };
  100605. })();
  100606. Object.defineProperty(exports, "__esModule", { value: true });
  100607. var viewer_1 = __webpack_require__(10);
  100608. var babylonjs_1 = __webpack_require__(0);
  100609. /**
  100610. * The Default viewer is the default implementation of the AbstractViewer.
  100611. * It uses the templating system to render a new canvas and controls.
  100612. */
  100613. var DefaultViewer = /** @class */ (function (_super) {
  100614. __extends(DefaultViewer, _super);
  100615. /**
  100616. * Create a new default viewer
  100617. * @param containerElement the element in which the templates will be rendered
  100618. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  100619. */
  100620. function DefaultViewer(containerElement, initialConfiguration) {
  100621. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  100622. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  100623. _this.containerElement = containerElement;
  100624. _this._handlePointerDown = function (event) {
  100625. var pointerDown = event.event;
  100626. if (pointerDown.button !== 0)
  100627. return;
  100628. var element = event.event.target;
  100629. if (!element) {
  100630. return;
  100631. }
  100632. var parentClasses = element.parentElement.classList;
  100633. switch (element.id) {
  100634. case "speed-button":
  100635. case "types-button":
  100636. if (parentClasses.contains("open")) {
  100637. parentClasses.remove("open");
  100638. }
  100639. else {
  100640. parentClasses.add("open");
  100641. }
  100642. break;
  100643. case "play-pause-button":
  100644. _this._togglePlayPause();
  100645. break;
  100646. case "label-option-button":
  100647. var label = element.dataset["value"];
  100648. if (label) {
  100649. _this._updateAnimationType(label);
  100650. }
  100651. break;
  100652. case "speed-option-button":
  100653. if (!_this._currentAnimation) {
  100654. return;
  100655. }
  100656. var speed = element.dataset["value"];
  100657. if (speed)
  100658. _this._updateAnimationSpeed(speed);
  100659. break;
  100660. case "progress-wrapper":
  100661. _this._resumePlay = !_this._isAnimationPaused;
  100662. if (_this._resumePlay) {
  100663. _this._togglePlayPause(true);
  100664. }
  100665. break;
  100666. case "fullscreen-button":
  100667. _this.toggleFullscreen();
  100668. default:
  100669. return;
  100670. }
  100671. };
  100672. /**
  100673. * Plays or Pauses animation
  100674. */
  100675. _this._togglePlayPause = function (noUiUpdate) {
  100676. if (!_this._currentAnimation) {
  100677. return;
  100678. }
  100679. if (_this._isAnimationPaused) {
  100680. _this._currentAnimation.restart();
  100681. }
  100682. else {
  100683. _this._currentAnimation.pause();
  100684. }
  100685. _this._isAnimationPaused = !_this._isAnimationPaused;
  100686. if (noUiUpdate)
  100687. return;
  100688. var navbar = _this.templateManager.getTemplate('navBar');
  100689. if (!navbar)
  100690. return;
  100691. navbar.updateParams({
  100692. paused: _this._isAnimationPaused,
  100693. });
  100694. };
  100695. /**
  100696. * Control progress bar position based on animation current frame
  100697. */
  100698. _this._updateProgressBar = function () {
  100699. var navbar = _this.templateManager.getTemplate('navBar');
  100700. if (!navbar)
  100701. return;
  100702. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  100703. if (progressSlider && _this._currentAnimation) {
  100704. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  100705. var currentValue = progressSlider.valueAsNumber;
  100706. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  100707. progressSlider.value = '' + progress;
  100708. }
  100709. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  100710. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  100711. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  100712. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  100713. }
  100714. }
  100715. else {
  100716. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  100717. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  100718. _this._oldIdleRotationValue = 0;
  100719. }
  100720. }
  100721. }
  100722. };
  100723. /**
  100724. * Update Current Animation Speed
  100725. */
  100726. _this._updateAnimationSpeed = function (speed, paramsObject) {
  100727. var navbar = _this.templateManager.getTemplate('navBar');
  100728. if (!navbar)
  100729. return;
  100730. if (speed && _this._currentAnimation) {
  100731. _this._currentAnimation.speedRatio = parseFloat(speed);
  100732. if (!_this._isAnimationPaused) {
  100733. _this._currentAnimation.restart();
  100734. }
  100735. if (paramsObject) {
  100736. paramsObject.selectedSpeed = speed + "x";
  100737. }
  100738. else {
  100739. navbar.updateParams({
  100740. selectedSpeed: speed + "x",
  100741. });
  100742. }
  100743. }
  100744. };
  100745. /**
  100746. * Update Current Animation Type
  100747. */
  100748. _this._updateAnimationType = function (label, paramsObject) {
  100749. var navbar = _this.templateManager.getTemplate('navBar');
  100750. if (!navbar)
  100751. return;
  100752. if (label) {
  100753. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  100754. }
  100755. if (paramsObject) {
  100756. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  100757. paramsObject.selectedAnimationName = label;
  100758. }
  100759. else {
  100760. navbar.updateParams({
  100761. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  100762. selectedAnimationName: label
  100763. });
  100764. }
  100765. _this._updateAnimationSpeed("1.0", paramsObject);
  100766. };
  100767. /**
  100768. * Toggle fullscreen of the entire viewer
  100769. */
  100770. _this.toggleFullscreen = function () {
  100771. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  100772. var viewerElement = viewerTemplate && viewerTemplate.parent;
  100773. if (viewerElement) {
  100774. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  100775. if (!fullscreenElement) {
  100776. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  100777. requestFullScreen.call(viewerElement);
  100778. }
  100779. else {
  100780. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  100781. exitFullscreen.call(document);
  100782. }
  100783. }
  100784. };
  100785. _this._onModelLoaded = function (model) {
  100786. _this._configureTemplate(model);
  100787. // with a short timeout, making sure everything is there already.
  100788. var hideLoadingDelay = 20;
  100789. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  100790. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  100791. }
  100792. setTimeout(function () {
  100793. _this.sceneManager.scene.executeWhenReady(function () {
  100794. _this.hideLoadingScreen();
  100795. });
  100796. }, hideLoadingDelay);
  100797. return;
  100798. };
  100799. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  100800. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  100801. _this._configureLights(data.newConfiguration, data.model);
  100802. });
  100803. return _this;
  100804. }
  100805. /**
  100806. * This will be executed when the templates initialize.
  100807. */
  100808. DefaultViewer.prototype._onTemplatesLoaded = function () {
  100809. var _this = this;
  100810. this.showLoadingScreen();
  100811. // navbar
  100812. this._initNavbar();
  100813. // close overlay button
  100814. var closeButton = document.getElementById('close-button');
  100815. if (closeButton) {
  100816. closeButton.addEventListener('pointerdown', function () {
  100817. _this.hideOverlayScreen();
  100818. });
  100819. }
  100820. if (this.configuration.templates && this.configuration.templates.viewer) {
  100821. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  100822. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  100823. }, function () {
  100824. }, function () {
  100825. }, function () {
  100826. }, function () {
  100827. }, function (file) {
  100828. _this.loadModel(file);
  100829. }, function () {
  100830. });
  100831. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  100832. }
  100833. }
  100834. return _super.prototype._onTemplatesLoaded.call(this);
  100835. };
  100836. DefaultViewer.prototype._dropped = function (evt) {
  100837. };
  100838. DefaultViewer.prototype._initNavbar = function () {
  100839. var _this = this;
  100840. var navbar = this.templateManager.getTemplate('navBar');
  100841. if (navbar) {
  100842. this.onFrameRenderedObservable.add(this._updateProgressBar);
  100843. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  100844. // an example how to trigger the help button. publiclly available
  100845. this.templateManager.eventManager.registerCallback("navBar", function () {
  100846. // do your thing
  100847. }, "pointerdown", "#help-button");
  100848. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  100849. var evt = event.event;
  100850. var element = (evt.target);
  100851. if (!_this._currentAnimation)
  100852. return;
  100853. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  100854. if (isNaN(gotoFrame))
  100855. return;
  100856. _this._currentAnimation.goToFrame(gotoFrame);
  100857. }, "input");
  100858. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  100859. if (_this._resumePlay) {
  100860. _this._togglePlayPause(true);
  100861. }
  100862. _this._resumePlay = false;
  100863. }, "pointerup", "#progress-wrapper");
  100864. }
  100865. };
  100866. /**
  100867. * Preparing the container element to present the viewer
  100868. */
  100869. DefaultViewer.prototype._prepareContainerElement = function () {
  100870. this.containerElement.style.position = 'relative';
  100871. this.containerElement.style.height = '100%';
  100872. this.containerElement.style.display = 'flex';
  100873. };
  100874. /**
  100875. * This function will configure the templates and update them after a model was loaded
  100876. * It is mainly responsible to changing the title and subtitle etc'.
  100877. * @param model the model to be used to configure the templates by
  100878. */
  100879. DefaultViewer.prototype._configureTemplate = function (model) {
  100880. var navbar = this.templateManager.getTemplate('navBar');
  100881. if (!navbar)
  100882. return;
  100883. var newParams = {};
  100884. var animationNames = model.getAnimationNames();
  100885. if (animationNames.length >= 1) {
  100886. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  100887. this._animationList = animationNames;
  100888. newParams.animations = this._animationList;
  100889. newParams.paused = this._isAnimationPaused;
  100890. var animationIndex = 0;
  100891. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  100892. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  100893. if (animationIndex === -1) {
  100894. animationIndex = 0;
  100895. }
  100896. }
  100897. this._updateAnimationType(animationNames[animationIndex], newParams);
  100898. }
  100899. if (model.configuration.thumbnail) {
  100900. newParams.logoImage = model.configuration.thumbnail;
  100901. }
  100902. navbar.updateParams(newParams);
  100903. };
  100904. /**
  100905. * This will load a new model to the default viewer
  100906. * overriding the AbstractViewer's loadModel.
  100907. * The scene will automatically be cleared of the old models, if exist.
  100908. * @param model the configuration object (or URL) to load.
  100909. */
  100910. DefaultViewer.prototype.loadModel = function (model) {
  100911. var _this = this;
  100912. if (!model) {
  100913. model = this.configuration.model;
  100914. }
  100915. this.showLoadingScreen();
  100916. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  100917. console.log(error);
  100918. _this.hideLoadingScreen();
  100919. _this.showOverlayScreen('error');
  100920. return Promise.reject(error);
  100921. });
  100922. };
  100923. /**
  100924. * Show the overlay and the defined sub-screen.
  100925. * Mainly used for help and errors
  100926. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  100927. */
  100928. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  100929. var _this = this;
  100930. var template = this.templateManager.getTemplate('overlay');
  100931. if (!template)
  100932. return Promise.resolve('Overlay template not found');
  100933. return template.show((function (template) {
  100934. var canvasRect = _this.containerElement.getBoundingClientRect();
  100935. template.parent.style.display = 'flex';
  100936. template.parent.style.width = canvasRect.width + "px";
  100937. template.parent.style.height = canvasRect.height + "px";
  100938. template.parent.style.opacity = "1";
  100939. var subTemplate = _this.templateManager.getTemplate(subScreen);
  100940. if (!subTemplate) {
  100941. return Promise.reject(subScreen + ' template not found');
  100942. }
  100943. return subTemplate.show((function (template) {
  100944. template.parent.style.display = 'flex';
  100945. return Promise.resolve(template);
  100946. }));
  100947. }));
  100948. };
  100949. /**
  100950. * Hide the overlay screen.
  100951. */
  100952. DefaultViewer.prototype.hideOverlayScreen = function () {
  100953. var template = this.templateManager.getTemplate('overlay');
  100954. if (!template)
  100955. return Promise.resolve('Overlay template not found');
  100956. return template.hide((function (template) {
  100957. template.parent.style.opacity = "0";
  100958. var onTransitionEnd = function () {
  100959. template.parent.removeEventListener("transitionend", onTransitionEnd);
  100960. template.parent.style.display = 'none';
  100961. };
  100962. template.parent.addEventListener("transitionend", onTransitionEnd);
  100963. var overlays = template.parent.querySelectorAll('.overlay');
  100964. if (overlays) {
  100965. for (var i = 0; i < overlays.length; ++i) {
  100966. var htmlElement = overlays.item(i);
  100967. htmlElement.style.display = 'none';
  100968. }
  100969. }
  100970. return Promise.resolve(template);
  100971. }));
  100972. };
  100973. /**
  100974. * show the viewer (in case it was hidden)
  100975. *
  100976. * @param visibilityFunction an optional function to execute in order to show the container
  100977. */
  100978. DefaultViewer.prototype.show = function (visibilityFunction) {
  100979. var template = this.templateManager.getTemplate('main');
  100980. //not possible, but yet:
  100981. if (!template)
  100982. return Promise.reject('Main template not found');
  100983. return template.show(visibilityFunction);
  100984. };
  100985. /**
  100986. * hide the viewer (in case it is visible)
  100987. *
  100988. * @param visibilityFunction an optional function to execute in order to hide the container
  100989. */
  100990. DefaultViewer.prototype.hide = function (visibilityFunction) {
  100991. var template = this.templateManager.getTemplate('main');
  100992. //not possible, but yet:
  100993. if (!template)
  100994. return Promise.reject('Main template not found');
  100995. return template.hide(visibilityFunction);
  100996. };
  100997. /**
  100998. * Show the loading screen.
  100999. * The loading screen can be configured using the configuration object
  101000. */
  101001. DefaultViewer.prototype.showLoadingScreen = function () {
  101002. var _this = this;
  101003. var template = this.templateManager.getTemplate('loadingScreen');
  101004. if (!template)
  101005. return Promise.resolve('Loading Screen template not found');
  101006. return template.show((function (template) {
  101007. var canvasRect = _this.containerElement.getBoundingClientRect();
  101008. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  101009. template.parent.style.display = 'flex';
  101010. template.parent.style.width = canvasRect.width + "px";
  101011. template.parent.style.height = canvasRect.height + "px";
  101012. template.parent.style.opacity = "1";
  101013. // from the configuration!!!
  101014. var color = "black";
  101015. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  101016. color = (_this.configuration.templates.loadingScreen.params &&
  101017. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  101018. }
  101019. template.parent.style.backgroundColor = color;
  101020. return Promise.resolve(template);
  101021. }));
  101022. };
  101023. /**
  101024. * Hide the loading screen
  101025. */
  101026. DefaultViewer.prototype.hideLoadingScreen = function () {
  101027. var template = this.templateManager.getTemplate('loadingScreen');
  101028. if (!template)
  101029. return Promise.resolve('Loading Screen template not found');
  101030. return template.hide((function (template) {
  101031. template.parent.style.opacity = "0";
  101032. var onTransitionEnd = function () {
  101033. template.parent.removeEventListener("transitionend", onTransitionEnd);
  101034. template.parent.style.display = 'none';
  101035. };
  101036. template.parent.addEventListener("transitionend", onTransitionEnd);
  101037. return Promise.resolve(template);
  101038. }));
  101039. };
  101040. /**
  101041. * An extension of the light configuration of the abstract viewer.
  101042. * @param lightsConfiguration the light configuration to use
  101043. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  101044. */
  101045. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  101046. var _this = this;
  101047. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  101048. // labs feature - flashlight
  101049. if (this._configuration.lab && this._configuration.lab.flashlight) {
  101050. var pointerPosition = babylonjs_1.Vector3.Zero();
  101051. var lightTarget_1;
  101052. var angle = 0.5;
  101053. var exponent = Math.PI / 2;
  101054. if (typeof this._configuration.lab.flashlight === "object") {
  101055. exponent = this._configuration.lab.flashlight.exponent || exponent;
  101056. angle = this._configuration.lab.flashlight.angle || angle;
  101057. }
  101058. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  101059. if (typeof this._configuration.lab.flashlight === "object") {
  101060. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  101061. if (this._configuration.lab.flashlight.diffuse) {
  101062. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  101063. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  101064. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  101065. }
  101066. if (this._configuration.lab.flashlight.specular) {
  101067. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  101068. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  101069. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  101070. }
  101071. }
  101072. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  101073. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  101074. if (eventData.type === 4 && eventData.pickInfo) {
  101075. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  101076. }
  101077. else {
  101078. lightTarget_1 = undefined;
  101079. }
  101080. });
  101081. var updateFlashlightFunction = function () {
  101082. if (_this.sceneManager.camera && flashlight) {
  101083. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  101084. if (lightTarget_1) {
  101085. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  101086. }
  101087. }
  101088. };
  101089. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  101090. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  101091. }
  101092. };
  101093. return DefaultViewer;
  101094. }(viewer_1.AbstractViewer));
  101095. exports.DefaultViewer = DefaultViewer;
  101096. /***/ }),
  101097. /* 10 */
  101098. /***/ (function(module, exports, __webpack_require__) {
  101099. "use strict";
  101100. Object.defineProperty(exports, "__esModule", { value: true });
  101101. var viewerManager_1 = __webpack_require__(8);
  101102. var sceneManager_1 = __webpack_require__(29);
  101103. var templateManager_1 = __webpack_require__(35);
  101104. var loader_1 = __webpack_require__(38);
  101105. var babylonjs_1 = __webpack_require__(0);
  101106. var deepmerge = __webpack_require__(1);
  101107. var modelLoader_1 = __webpack_require__(22);
  101108. var globals_1 = __webpack_require__(7);
  101109. var telemetryManager_1 = __webpack_require__(5);
  101110. /**
  101111. * The AbstractViewr is the center of Babylon's viewer.
  101112. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  101113. */
  101114. var AbstractViewer = /** @class */ (function () {
  101115. function AbstractViewer(containerElement, initialConfiguration) {
  101116. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  101117. var _this = this;
  101118. this.containerElement = containerElement;
  101119. /**
  101120. * A flag that controls whether or not the render loop should be executed
  101121. */
  101122. this.runRenderLoop = true;
  101123. /**
  101124. * is this viewer disposed?
  101125. */
  101126. this._isDisposed = false;
  101127. /**
  101128. * The resize function that will be registered with the window object
  101129. */
  101130. this._resize = function () {
  101131. // Only resize if Canvas is in the DOM
  101132. if (!_this.isCanvasInDOM()) {
  101133. return;
  101134. }
  101135. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  101136. return;
  101137. }
  101138. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  101139. return;
  101140. }
  101141. _this.engine.resize();
  101142. };
  101143. /**
  101144. * render loop that will be executed by the engine
  101145. */
  101146. this._render = function (force) {
  101147. if (force === void 0) { force = false; }
  101148. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  101149. if (_this.runRenderLoop || force) {
  101150. _this.engine.performanceMonitor.enable();
  101151. _this.sceneManager.scene.render();
  101152. _this.onFrameRenderedObservable.notifyObservers(_this);
  101153. }
  101154. else {
  101155. _this.engine.performanceMonitor.disable();
  101156. // update camera instead of rendering
  101157. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  101158. }
  101159. }
  101160. };
  101161. // if exists, use the container id. otherwise, generate a random string.
  101162. if (containerElement.id) {
  101163. this.baseId = containerElement.id;
  101164. }
  101165. else {
  101166. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  101167. }
  101168. this.onSceneInitObservable = new babylonjs_1.Observable();
  101169. this.onEngineInitObservable = new babylonjs_1.Observable();
  101170. this.onModelLoadedObservable = new babylonjs_1.Observable();
  101171. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  101172. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  101173. this.onModelAddedObservable = new babylonjs_1.Observable();
  101174. this.onModelRemovedObservable = new babylonjs_1.Observable();
  101175. this.onInitDoneObservable = new babylonjs_1.Observable();
  101176. this.onLoaderInitObservable = new babylonjs_1.Observable();
  101177. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  101178. this._registeredOnBeforeRenderFunctions = [];
  101179. this.modelLoader = new modelLoader_1.ModelLoader(this);
  101180. // add this viewer to the viewer manager
  101181. viewerManager_1.viewerManager.addViewer(this);
  101182. // create a new template manager for this viewer
  101183. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  101184. this.sceneManager = new sceneManager_1.SceneManager(this);
  101185. this._prepareContainerElement();
  101186. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  101187. // extend the configuration
  101188. this._configurationLoader = new loader_1.ConfigurationLoader();
  101189. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  101190. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  101191. if (_this._configuration.observers) {
  101192. _this._configureObservers(_this._configuration.observers);
  101193. }
  101194. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  101195. if (_this._configuration.loaderPlugins) {
  101196. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  101197. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  101198. _this.modelLoader.addPlugin(name);
  101199. }
  101200. }));
  101201. }
  101202. // initialize the templates
  101203. var templateConfiguration = _this._configuration.templates || {};
  101204. _this.templateManager.initTemplate(templateConfiguration);
  101205. // when done, execute onTemplatesLoaded()
  101206. _this.templateManager.onAllLoaded.add(function () {
  101207. var canvas = _this.templateManager.getCanvas();
  101208. if (canvas) {
  101209. _this._canvas = canvas;
  101210. }
  101211. _this._onTemplateLoaded();
  101212. });
  101213. });
  101214. this.onModelLoadedObservable.add(function (model) {
  101215. //this.updateConfiguration(this._configuration, model);
  101216. });
  101217. this.onSceneInitObservable.add(function () {
  101218. _this.updateConfiguration();
  101219. });
  101220. this.onInitDoneObservable.add(function () {
  101221. _this._isInit = true;
  101222. _this.engine.runRenderLoop(_this._render);
  101223. });
  101224. }
  101225. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  101226. /**
  101227. * The (single) canvas of this viewer
  101228. */
  101229. get: function () {
  101230. return this._canvas;
  101231. },
  101232. enumerable: true,
  101233. configurable: true
  101234. });
  101235. /**
  101236. * get the baseId of this viewer
  101237. */
  101238. AbstractViewer.prototype.getBaseId = function () {
  101239. return this.baseId;
  101240. };
  101241. /**
  101242. * Do we have a canvas to render on, and is it a part of the scene
  101243. */
  101244. AbstractViewer.prototype.isCanvasInDOM = function () {
  101245. return !!this._canvas && !!this._canvas.parentElement;
  101246. };
  101247. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  101248. /**
  101249. * Is the engine currently set to rende even when the page is in background
  101250. */
  101251. get: function () {
  101252. return this.engine && this.engine.renderEvenInBackground;
  101253. },
  101254. /**
  101255. * Set the viewer's background rendering flag.
  101256. */
  101257. set: function (value) {
  101258. if (this.engine) {
  101259. this.engine.renderEvenInBackground = value;
  101260. }
  101261. },
  101262. enumerable: true,
  101263. configurable: true
  101264. });
  101265. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  101266. /**
  101267. * Get the configuration object. This is a reference only.
  101268. * The configuration can ONLY be updated using the updateConfiguration function.
  101269. * changing this object will have no direct effect on the scene.
  101270. */
  101271. get: function () {
  101272. return this._configuration;
  101273. },
  101274. enumerable: true,
  101275. configurable: true
  101276. });
  101277. /**
  101278. * force resizing the engine.
  101279. */
  101280. AbstractViewer.prototype.forceResize = function () {
  101281. this._resize();
  101282. };
  101283. /**
  101284. * Force a single render loop execution.
  101285. */
  101286. AbstractViewer.prototype.forceRender = function () {
  101287. this._render(true);
  101288. };
  101289. /**
  101290. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  101291. * @param callback optional callback that will be triggered when screenshot is done.
  101292. * @param width Optional screenshot width (default to 512).
  101293. * @param height Optional screenshot height (default to 512).
  101294. * @returns a promise with the screenshot data
  101295. */
  101296. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  101297. var _this = this;
  101298. if (width === void 0) { width = 0; }
  101299. if (height === void 0) { height = 0; }
  101300. width = width || this.canvas.clientWidth;
  101301. height = height || this.canvas.clientHeight;
  101302. // Create the screenshot
  101303. return new Promise(function (resolve, reject) {
  101304. try {
  101305. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  101306. if (callback) {
  101307. callback(data);
  101308. }
  101309. resolve(data);
  101310. });
  101311. }
  101312. catch (e) {
  101313. reject(e);
  101314. }
  101315. });
  101316. };
  101317. /**
  101318. * Update the current viewer configuration with new values.
  101319. * Only provided information will be updated, old configuration values will be kept.
  101320. * If this.configuration was manually changed, you can trigger this function with no parameters,
  101321. * and the entire configuration will be updated.
  101322. * @param newConfiguration the partial configuration to update
  101323. *
  101324. */
  101325. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  101326. var _this = this;
  101327. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  101328. // update this.configuration with the new data
  101329. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  101330. this.sceneManager.updateConfiguration(newConfiguration, this._configuration);
  101331. // observers in configuration
  101332. if (newConfiguration.observers) {
  101333. this._configureObservers(newConfiguration.observers);
  101334. }
  101335. if (newConfiguration.loaderPlugins) {
  101336. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  101337. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  101338. _this.modelLoader.addPlugin(name);
  101339. }
  101340. }));
  101341. }
  101342. };
  101343. /**
  101344. * this is used to register native functions using the configuration object.
  101345. * This will configure the observers.
  101346. * @param observersConfiguration observers configuration
  101347. */
  101348. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  101349. if (observersConfiguration.onEngineInit) {
  101350. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  101351. }
  101352. else {
  101353. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  101354. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  101355. }
  101356. }
  101357. if (observersConfiguration.onSceneInit) {
  101358. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  101359. }
  101360. else {
  101361. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  101362. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  101363. }
  101364. }
  101365. if (observersConfiguration.onModelLoaded) {
  101366. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  101367. }
  101368. else {
  101369. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  101370. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  101371. }
  101372. }
  101373. };
  101374. /**
  101375. * Dispoe the entire viewer including the scene and the engine
  101376. */
  101377. AbstractViewer.prototype.dispose = function () {
  101378. if (this._isDisposed) {
  101379. return;
  101380. }
  101381. window.removeEventListener('resize', this._resize);
  101382. //observers
  101383. this.onEngineInitObservable.clear();
  101384. this.onInitDoneObservable.clear();
  101385. this.onLoaderInitObservable.clear();
  101386. this.onModelLoadedObservable.clear();
  101387. this.onModelLoadErrorObservable.clear();
  101388. this.onModelLoadProgressObservable.clear();
  101389. this.onSceneInitObservable.clear();
  101390. this.onFrameRenderedObservable.clear();
  101391. this.onModelAddedObservable.clear();
  101392. this.onModelRemovedObservable.clear();
  101393. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  101394. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  101395. }
  101396. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  101397. this.sceneManager.dispose();
  101398. this.modelLoader.dispose();
  101399. if (this.engine) {
  101400. this.engine.dispose();
  101401. }
  101402. this.templateManager.dispose();
  101403. viewerManager_1.viewerManager.removeViewer(this);
  101404. this._isDisposed = true;
  101405. };
  101406. /**
  101407. * This function will execute when the HTML templates finished initializing.
  101408. * It should initialize the engine and continue execution.
  101409. *
  101410. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  101411. */
  101412. AbstractViewer.prototype._onTemplatesLoaded = function () {
  101413. return Promise.resolve(this);
  101414. };
  101415. /**
  101416. * This will force the creation of an engine and a scene.
  101417. * It will also load a model if preconfigured.
  101418. * But first - it will load the extendible onTemplateLoaded()!
  101419. */
  101420. AbstractViewer.prototype._onTemplateLoaded = function () {
  101421. var _this = this;
  101422. // check if viewer was disposed right after created
  101423. if (this._isDisposed) {
  101424. return Promise.reject("viewer was disposed");
  101425. }
  101426. return this._onTemplatesLoaded().then(function () {
  101427. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  101428. return _this._initEngine().then(function (engine) {
  101429. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  101430. }).then(function () {
  101431. _this._initTelemetryEvents();
  101432. if (autoLoad) {
  101433. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  101434. }
  101435. else {
  101436. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  101437. }
  101438. }).then(function () {
  101439. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  101440. }).catch(function (e) {
  101441. babylonjs_1.Tools.Warn(e.toString());
  101442. return _this;
  101443. });
  101444. });
  101445. };
  101446. /**
  101447. * Initialize the engine. Retruns a promise in case async calls are needed.
  101448. *
  101449. * @protected
  101450. * @returns {Promise<Engine>}
  101451. * @memberof Viewer
  101452. */
  101453. AbstractViewer.prototype._initEngine = function () {
  101454. // init custom shaders
  101455. this._injectCustomShaders();
  101456. var canvasElement = this.templateManager.getCanvas();
  101457. if (!canvasElement) {
  101458. return Promise.reject('Canvas element not found!');
  101459. }
  101460. var config = this._configuration.engine || {};
  101461. // TDO enable further configuration
  101462. // check for webgl2 support, force-disable if needed.
  101463. if (globals_1.viewerGlobals.disableWebGL2Support) {
  101464. config.engineOptions = config.engineOptions || {};
  101465. config.engineOptions.disableWebGL2Support = true;
  101466. }
  101467. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  101468. // Disable manifest checking
  101469. babylonjs_1.Database.IDBStorageEnabled = false;
  101470. if (!config.disableResize) {
  101471. window.addEventListener('resize', this._resize);
  101472. }
  101473. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  101474. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  101475. this.engine.setHardwareScalingLevel(scale);
  101476. }
  101477. return Promise.resolve(this.engine);
  101478. };
  101479. /**
  101480. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  101481. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  101482. *
  101483. * @param modelConfig model configuration to use when loading the model.
  101484. * @param clearScene should the scene be cleared before loading this model
  101485. * @returns a ViewerModel object that is not yet fully loaded.
  101486. */
  101487. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  101488. var _this = this;
  101489. if (clearScene === void 0) { clearScene = true; }
  101490. var configuration;
  101491. if (typeof modelConfig === 'string') {
  101492. configuration = {
  101493. url: modelConfig
  101494. };
  101495. }
  101496. else if (modelConfig instanceof File) {
  101497. configuration = {
  101498. file: modelConfig,
  101499. root: "file:"
  101500. };
  101501. }
  101502. else {
  101503. configuration = modelConfig;
  101504. }
  101505. if (!configuration.url && !configuration.file) {
  101506. throw new Error("no model provided");
  101507. }
  101508. if (clearScene) {
  101509. this.sceneManager.clearScene(true, false);
  101510. }
  101511. //merge the configuration for future models:
  101512. if (this._configuration.model && typeof this._configuration.model === 'object') {
  101513. var globalConfig = deepmerge({}, this._configuration.model);
  101514. configuration = deepmerge(globalConfig, configuration);
  101515. if (modelConfig instanceof File) {
  101516. configuration.file = modelConfig;
  101517. }
  101518. }
  101519. else {
  101520. this._configuration.model = configuration;
  101521. }
  101522. this._isLoading = true;
  101523. var model = this.modelLoader.load(configuration);
  101524. this.lastUsedLoader = model.loader;
  101525. model.onLoadErrorObservable.add(function (errorObject) {
  101526. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  101527. });
  101528. model.onLoadProgressObservable.add(function (progressEvent) {
  101529. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  101530. });
  101531. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  101532. model.onLoadedObservable.add(function () {
  101533. _this._isLoading = false;
  101534. });
  101535. return model;
  101536. };
  101537. /**
  101538. * load a model using the provided configuration.
  101539. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  101540. * If you want to attach to the observables of the model, use initModle instead.
  101541. *
  101542. * @param modelConfig the model configuration or URL to load.
  101543. * @param clearScene Should the scene be cleared before loading the model
  101544. * @returns a Promise the fulfills when the model finished loading successfully.
  101545. */
  101546. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  101547. var _this = this;
  101548. if (clearScene === void 0) { clearScene = true; }
  101549. if (this._isLoading) {
  101550. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  101551. return Promise.reject("another model is curently being loaded.");
  101552. }
  101553. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  101554. if (!scene)
  101555. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  101556. return scene;
  101557. }).then(function () {
  101558. var model = _this.initModel(modelConfig, clearScene);
  101559. return new Promise(function (resolve, reject) {
  101560. // at this point, configuration.model is an object, not a string
  101561. model.onLoadedObservable.add(function () {
  101562. resolve(model);
  101563. });
  101564. model.onLoadErrorObservable.add(function (error) {
  101565. reject(error);
  101566. });
  101567. });
  101568. });
  101569. };
  101570. AbstractViewer.prototype._initTelemetryEvents = function () {
  101571. var _this = this;
  101572. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  101573. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  101574. userAgent: navigator.userAgent,
  101575. platform: navigator.platform
  101576. });
  101577. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  101578. var trackFPS = function () {
  101579. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  101580. };
  101581. trackFPS();
  101582. // Track the FPS again after 60 seconds
  101583. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  101584. };
  101585. /**
  101586. * Injects all the spectre shader in the babylon shader store
  101587. */
  101588. AbstractViewer.prototype._injectCustomShaders = function () {
  101589. var customShaders = this._configuration.customShaders;
  101590. // Inject all the spectre shader in the babylon shader store.
  101591. if (!customShaders) {
  101592. return;
  101593. }
  101594. if (customShaders.shaders) {
  101595. Object.keys(customShaders.shaders).forEach(function (key) {
  101596. // typescript considers a callback "unsafe", so... '!'
  101597. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  101598. });
  101599. }
  101600. if (customShaders.includes) {
  101601. Object.keys(customShaders.includes).forEach(function (key) {
  101602. // typescript considers a callback "unsafe", so... '!'
  101603. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  101604. });
  101605. }
  101606. };
  101607. return AbstractViewer;
  101608. }());
  101609. exports.AbstractViewer = AbstractViewer;
  101610. /***/ }),
  101611. /* 11 */
  101612. /***/ (function(module, exports, __webpack_require__) {
  101613. "use strict";
  101614. Object.defineProperty(exports, "__esModule", { value: true });
  101615. function getConfigurationKey(key, configObject) {
  101616. var splits = key.split('.');
  101617. if (splits.length === 0 || !configObject)
  101618. return;
  101619. else if (splits.length === 1) {
  101620. if (configObject[key] !== undefined) {
  101621. return configObject[key];
  101622. }
  101623. }
  101624. else {
  101625. var firstKey = splits.shift();
  101626. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  101627. }
  101628. }
  101629. exports.getConfigurationKey = getConfigurationKey;
  101630. /***/ }),
  101631. /* 12 */
  101632. /***/ (function(module, exports, __webpack_require__) {
  101633. "use strict";
  101634. Object.defineProperty(exports, "__esModule", { value: true });
  101635. /**
  101636. * WebGL Pixel Formats
  101637. */
  101638. var PixelFormat;
  101639. (function (PixelFormat) {
  101640. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  101641. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  101642. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  101643. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  101644. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  101645. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  101646. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  101647. /**
  101648. * WebGL Pixel Types
  101649. */
  101650. var PixelType;
  101651. (function (PixelType) {
  101652. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101653. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  101654. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  101655. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  101656. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  101657. /**
  101658. * WebGL Texture Magnification Filter
  101659. */
  101660. var TextureMagFilter;
  101661. (function (TextureMagFilter) {
  101662. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  101663. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  101664. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  101665. /**
  101666. * WebGL Texture Minification Filter
  101667. */
  101668. var TextureMinFilter;
  101669. (function (TextureMinFilter) {
  101670. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  101671. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  101672. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  101673. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  101674. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  101675. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  101676. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  101677. /**
  101678. * WebGL Texture Wrap Modes
  101679. */
  101680. var TextureWrapMode;
  101681. (function (TextureWrapMode) {
  101682. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  101683. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  101684. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  101685. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  101686. /**
  101687. * A minimal WebGL cubemap descriptor
  101688. */
  101689. var TextureCube = /** @class */ (function () {
  101690. /**
  101691. * constructor
  101692. * @param internalFormat WebGL pixel format for the texture on the GPU
  101693. * @param type WebGL pixel type of the supplied data and texture on the GPU
  101694. * @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
  101695. */
  101696. function TextureCube(internalFormat, type, source) {
  101697. if (source === void 0) { source = []; }
  101698. this.internalFormat = internalFormat;
  101699. this.type = type;
  101700. this.source = source;
  101701. }
  101702. Object.defineProperty(TextureCube.prototype, "Width", {
  101703. /**
  101704. * Returns the width of a face of the texture or 0 if not available
  101705. */
  101706. get: function () {
  101707. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  101708. },
  101709. enumerable: true,
  101710. configurable: true
  101711. });
  101712. Object.defineProperty(TextureCube.prototype, "Height", {
  101713. /**
  101714. * Returns the height of a face of the texture or 0 if not available
  101715. */
  101716. get: function () {
  101717. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  101718. },
  101719. enumerable: true,
  101720. configurable: true
  101721. });
  101722. return TextureCube;
  101723. }());
  101724. exports.TextureCube = TextureCube;
  101725. /**
  101726. * A static class providing methods to aid working with Bablyon textures.
  101727. */
  101728. var TextureUtils = /** @class */ (function () {
  101729. function TextureUtils() {
  101730. }
  101731. /**
  101732. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  101733. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  101734. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  101735. * @param scene A Babylon Scene instance
  101736. * @param textureCube A Spectre TextureCube object
  101737. * @param parameters WebGL texture sampling parameters
  101738. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  101739. * @param environment Specifies that the texture will be used as an environment
  101740. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  101741. * @return Babylon cube texture
  101742. */
  101743. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  101744. if (environment === void 0) { environment = false; }
  101745. if (singleLod === void 0) { singleLod = false; }
  101746. if (!textureCube)
  101747. throw new Error("no texture cube provided");
  101748. var parameters;
  101749. if (environment) {
  101750. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  101751. }
  101752. else {
  101753. parameters = {
  101754. magFilter: 9728 /* NEAREST */,
  101755. minFilter: 9728 /* NEAREST */,
  101756. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101757. wrapT: 33071 /* CLAMP_TO_EDGE */
  101758. };
  101759. }
  101760. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  101761. var babylonTexture = textureCube[key];
  101762. if (!babylonTexture) {
  101763. //initialize babylon texture
  101764. babylonTexture = new BABYLON.CubeTexture('', scene);
  101765. if (environment) {
  101766. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  101767. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  101768. }
  101769. babylonTexture.gammaSpace = false;
  101770. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  101771. var glTexture_1 = internalTexture_1._webGLTexture;
  101772. //babylon properties
  101773. internalTexture_1.isCube = true;
  101774. internalTexture_1.generateMipMaps = false;
  101775. babylonTexture._texture = internalTexture_1;
  101776. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  101777. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  101778. var texturesUploaded_1 = 0;
  101779. var textureComplete = function () {
  101780. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  101781. };
  101782. var uploadFace = function (i, level, face) {
  101783. if (!glTexture_1)
  101784. return;
  101785. if (i === 0 && level === 0) {
  101786. internalTexture_1.width = face.width;
  101787. internalTexture_1.height = face.height;
  101788. }
  101789. var gl = (scene.getEngine())._gl;
  101790. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  101791. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  101792. if (face instanceof HTMLElement || face instanceof ImageData) {
  101793. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  101794. }
  101795. else {
  101796. var textureData = face;
  101797. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  101798. }
  101799. texturesUploaded_1++;
  101800. if (textureComplete()) {
  101801. //generate mipmaps
  101802. if (automaticMipmaps) {
  101803. var w = face.width;
  101804. var h = face.height;
  101805. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  101806. if (isPot) {
  101807. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  101808. }
  101809. }
  101810. // Upload Separate lods in case there is no support for texture lod.
  101811. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  101812. var mipSlices = 3;
  101813. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  101814. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  101815. var lod = textureCube[lodKey];
  101816. //initialize lod texture if it doesn't already exist
  101817. if (lod == null && textureCube.Width) {
  101818. //compute LOD from even spacing in smoothness (matching shader calculation)
  101819. var smoothness = i_1 / (mipSlices - 1);
  101820. var roughness = 1 - smoothness;
  101821. var kMinimumVariance = 0.0005;
  101822. var alphaG = roughness * roughness + kMinimumVariance;
  101823. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  101824. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  101825. var maxLODIndex = textureCube.source.length - 1;
  101826. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  101827. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  101828. if (i_1 === 0) {
  101829. internalTexture_1._lodTextureLow = lod;
  101830. }
  101831. else if (i_1 === 1) {
  101832. internalTexture_1._lodTextureMid = lod;
  101833. }
  101834. else {
  101835. internalTexture_1._lodTextureHigh = lod;
  101836. }
  101837. textureCube[lodKey] = lod;
  101838. }
  101839. }
  101840. }
  101841. internalTexture_1.isReady = true;
  101842. }
  101843. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  101844. scene.getEngine().resetTextureCache();
  101845. };
  101846. var _loop_1 = function (i) {
  101847. var faces = textureCube.source[i];
  101848. var _loop_2 = function (j) {
  101849. var face = faces[j];
  101850. if (face instanceof HTMLImageElement && !face.complete) {
  101851. face.addEventListener('load', function () {
  101852. uploadFace(j, i, face);
  101853. }, false);
  101854. }
  101855. else {
  101856. uploadFace(j, i, face);
  101857. }
  101858. };
  101859. for (var j = 0; j < faces.length; j++) {
  101860. _loop_2(j);
  101861. }
  101862. };
  101863. for (var i = 0; i <= maxMipLevel_1; i++) {
  101864. _loop_1(i);
  101865. }
  101866. scene.getEngine().resetTextureCache();
  101867. babylonTexture.isReady = function () {
  101868. return textureComplete();
  101869. };
  101870. textureCube[key] = babylonTexture;
  101871. }
  101872. return babylonTexture;
  101873. };
  101874. /**
  101875. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  101876. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  101877. * @param parameters Spectre SamplingParameters to apply
  101878. */
  101879. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  101880. var scene = babylonTexture.getScene();
  101881. if (!scene)
  101882. return;
  101883. var gl = (scene.getEngine())._gl;
  101884. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  101885. var internalTexture = babylonTexture._texture;
  101886. if (!internalTexture)
  101887. return;
  101888. var glTexture = internalTexture._webGLTexture;
  101889. gl.bindTexture(target, glTexture);
  101890. if (parameters.magFilter != null)
  101891. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  101892. if (parameters.minFilter != null)
  101893. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  101894. if (parameters.wrapS != null)
  101895. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  101896. if (parameters.wrapT != null)
  101897. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  101898. //set babylon wrap modes from sampling parameter
  101899. switch (parameters.wrapS) {
  101900. case 10497 /* REPEAT */:
  101901. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  101902. break;
  101903. case 33071 /* CLAMP_TO_EDGE */:
  101904. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101905. break;
  101906. case 33648 /* MIRRORED_REPEAT */:
  101907. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  101908. break;
  101909. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101910. }
  101911. switch (parameters.wrapT) {
  101912. case 10497 /* REPEAT */:
  101913. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  101914. break;
  101915. case 33071 /* CLAMP_TO_EDGE */:
  101916. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101917. break;
  101918. case 33648 /* MIRRORED_REPEAT */:
  101919. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  101920. break;
  101921. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101922. }
  101923. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  101924. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  101925. if (anisotropicExt) {
  101926. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  101927. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  101928. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  101929. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  101930. }
  101931. }
  101932. gl.bindTexture(target, null);
  101933. scene.getEngine().resetTextureCache();
  101934. };
  101935. /**
  101936. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  101937. */
  101938. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  101939. /**
  101940. * Controls anisotropic filtering for deserialized textures.
  101941. */
  101942. TextureUtils.MaxAnisotropy = 4;
  101943. TextureUtils._EnvironmentSampling = {
  101944. magFilter: 9729 /* LINEAR */,
  101945. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  101946. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101947. wrapT: 33071 /* CLAMP_TO_EDGE */,
  101948. maxAnisotropy: 1
  101949. };
  101950. TextureUtils._EnvironmentSingleMipSampling = {
  101951. magFilter: 9729 /* LINEAR */,
  101952. minFilter: 9729 /* LINEAR */,
  101953. wrapS: 33071 /* CLAMP_TO_EDGE */,
  101954. wrapT: 33071 /* CLAMP_TO_EDGE */,
  101955. maxAnisotropy: 1
  101956. };
  101957. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  101958. /**
  101959. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  101960. */
  101961. TextureUtils.EnvironmentLODScale = 0.8;
  101962. /**
  101963. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  101964. */
  101965. TextureUtils.EnvironmentLODOffset = 1.0;
  101966. return TextureUtils;
  101967. }());
  101968. exports.TextureUtils = TextureUtils;
  101969. /***/ }),
  101970. /* 13 */
  101971. /***/ (function(module, exports) {
  101972. 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>";
  101973. /***/ }),
  101974. /* 14 */
  101975. /***/ (function(module, exports) {
  101976. 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>";
  101977. /***/ }),
  101978. /* 15 */
  101979. /***/ (function(module, exports) {
  101980. 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}}>";
  101981. /***/ }),
  101982. /* 16 */
  101983. /***/ (function(module, exports) {
  101984. 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=="
  101985. /***/ }),
  101986. /* 17 */
  101987. /***/ (function(module, exports) {
  101988. 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>";
  101989. /***/ }),
  101990. /* 18 */
  101991. /***/ (function(module, exports) {
  101992. 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>";
  101993. /***/ }),
  101994. /* 19 */
  101995. /***/ (function(module, exports) {
  101996. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  101997. /***/ }),
  101998. /* 20 */
  101999. /***/ (function(module, exports) {
  102000. module.exports = "Error loading the model";
  102001. /***/ }),
  102002. /* 21 */
  102003. /***/ (function(module, exports, __webpack_require__) {
  102004. "use strict";
  102005. function __export(m) {
  102006. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  102007. }
  102008. Object.defineProperty(exports, "__esModule", { value: true });
  102009. __export(__webpack_require__(11));
  102010. /***/ }),
  102011. /* 22 */
  102012. /***/ (function(module, exports, __webpack_require__) {
  102013. "use strict";
  102014. Object.defineProperty(exports, "__esModule", { value: true });
  102015. var babylonjs_1 = __webpack_require__(0);
  102016. var babylonjs_loaders_1 = __webpack_require__(23);
  102017. var viewerModel_1 = __webpack_require__(4);
  102018. var _1 = __webpack_require__(51);
  102019. /**
  102020. * An instance of the class is in charge of loading the model correctly.
  102021. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  102022. *
  102023. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  102024. */
  102025. var ModelLoader = /** @class */ (function () {
  102026. /**
  102027. * Create a new Model loader
  102028. * @param _viewer the viewer using this model loader
  102029. */
  102030. function ModelLoader(_viewer) {
  102031. this._viewer = _viewer;
  102032. this._disposed = false;
  102033. this._loaders = [];
  102034. this._loadId = 0;
  102035. this._plugins = [];
  102036. }
  102037. /**
  102038. * Adds a new plugin to the loader process.
  102039. *
  102040. * @param plugin the plugin name or the plugin itself
  102041. */
  102042. ModelLoader.prototype.addPlugin = function (plugin) {
  102043. var actualPlugin = {};
  102044. if (typeof plugin === 'string') {
  102045. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  102046. if (loadedPlugin) {
  102047. actualPlugin = loadedPlugin;
  102048. }
  102049. }
  102050. else {
  102051. actualPlugin = plugin;
  102052. }
  102053. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  102054. this._plugins.push(actualPlugin);
  102055. }
  102056. };
  102057. /**
  102058. * Load a model using predefined configuration
  102059. * @param modelConfiguration the modelConfiguration to use to load the model
  102060. */
  102061. ModelLoader.prototype.load = function (modelConfiguration) {
  102062. var _this = this;
  102063. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  102064. model.loadId = this._loadId++;
  102065. if (!modelConfiguration.url) {
  102066. model.state = viewerModel_1.ModelState.ERROR;
  102067. babylonjs_1.Tools.Error("No URL provided");
  102068. return model;
  102069. }
  102070. var base;
  102071. var filename;
  102072. if (modelConfiguration.file) {
  102073. base = "file:";
  102074. filename = modelConfiguration.file;
  102075. }
  102076. else {
  102077. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  102078. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  102079. }
  102080. var plugin = modelConfiguration.loader;
  102081. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  102082. meshes.forEach(function (mesh) {
  102083. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  102084. model.addMesh(mesh);
  102085. });
  102086. model.particleSystems = particleSystems;
  102087. model.skeletons = skeletons;
  102088. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  102089. var animationGroup = animationGroups_1[_i];
  102090. model.addAnimationGroup(animationGroup);
  102091. }
  102092. _this._checkAndRun("onLoaded", model);
  102093. _this._viewer.sceneManager.scene.executeWhenReady(function () {
  102094. model.onLoadedObservable.notifyObservers(model);
  102095. });
  102096. }, function (progressEvent) {
  102097. _this._checkAndRun("onProgress", progressEvent);
  102098. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  102099. }, function (scene, m, exception) {
  102100. model.state = viewerModel_1.ModelState.ERROR;
  102101. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  102102. _this._checkAndRun("onError", m, exception);
  102103. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  102104. }, plugin);
  102105. if (model.loader.name === "gltf") {
  102106. var gltfLoader_1 = model.loader;
  102107. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  102108. gltfLoader_1.compileMaterials = true;
  102109. if (!modelConfiguration.file) {
  102110. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  102111. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  102112. };
  102113. }
  102114. // if ground is set to "mirror":
  102115. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  102116. gltfLoader_1.useClipPlane = true;
  102117. }
  102118. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  102119. gltfLoader_1[functionName].add(function (payload) {
  102120. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  102121. });
  102122. });
  102123. gltfLoader_1.onParsedObservable.add(function (data) {
  102124. if (data && data.json && data.json['asset']) {
  102125. model.loadInfo = data.json['asset'];
  102126. }
  102127. });
  102128. gltfLoader_1.onCompleteObservable.add(function () {
  102129. model.loaderDone = true;
  102130. });
  102131. }
  102132. else {
  102133. model.loaderDone = true;
  102134. }
  102135. this._checkAndRun("onInit", model.loader, model);
  102136. this._loaders.push(model.loader);
  102137. return model;
  102138. };
  102139. ModelLoader.prototype.cancelLoad = function (model) {
  102140. var loader = model.loader || this._loaders[model.loadId];
  102141. // ATM only available in the GLTF Loader
  102142. if (loader && loader.name === "gltf") {
  102143. var gltfLoader = loader;
  102144. gltfLoader.dispose();
  102145. model.state = viewerModel_1.ModelState.CANCELED;
  102146. }
  102147. else {
  102148. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  102149. }
  102150. };
  102151. /**
  102152. * dispose the model loader.
  102153. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  102154. */
  102155. ModelLoader.prototype.dispose = function () {
  102156. this._loaders.forEach(function (loader) {
  102157. if (loader.name === "gltf") {
  102158. loader.dispose();
  102159. }
  102160. });
  102161. this._loaders.length = 0;
  102162. this._disposed = true;
  102163. };
  102164. ModelLoader.prototype._checkAndRun = function (functionName) {
  102165. var _this = this;
  102166. var payload = [];
  102167. for (var _i = 1; _i < arguments.length; _i++) {
  102168. payload[_i - 1] = arguments[_i];
  102169. }
  102170. if (this._disposed)
  102171. return;
  102172. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  102173. try {
  102174. plugin[functionName].apply(_this, payload);
  102175. }
  102176. catch (e) { }
  102177. });
  102178. };
  102179. return ModelLoader;
  102180. }());
  102181. exports.ModelLoader = ModelLoader;
  102182. /***/ }),
  102183. /* 23 */
  102184. /***/ (function(module, exports, __webpack_require__) {
  102185. (function universalModuleDefinition(root, factory) {
  102186. var amdDependencies = [];
  102187. var BABYLON = root.BABYLON || this.BABYLON;
  102188. if(true) {
  102189. BABYLON = BABYLON || __webpack_require__(0);
  102190. module.exports = factory(BABYLON);
  102191. } else if(typeof define === 'function' && define.amd) {
  102192. amdDependencies.push("babylonjs");
  102193. define("babylonjs-loaders", amdDependencies, factory);
  102194. } else if(typeof exports === 'object') {
  102195. BABYLON = BABYLON || require("babylonjs");
  102196. exports["babylonjs-loaders"] = factory(BABYLON);
  102197. } else {
  102198. root["BABYLON"] = factory(BABYLON);
  102199. }
  102200. })(this, function(BABYLON) {
  102201. BABYLON = BABYLON || this.BABYLON;
  102202. 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};
  102203. 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)}}();
  102204. var BABYLON;
  102205. (function (BABYLON) {
  102206. var STLFileLoader = /** @class */ (function () {
  102207. function STLFileLoader() {
  102208. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  102209. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  102210. 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;
  102211. 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;
  102212. this.name = "stl";
  102213. // force data to come in as an ArrayBuffer
  102214. // we'll convert to string if it looks like it's an ASCII .stl
  102215. this.extensions = {
  102216. ".stl": { isBinary: true },
  102217. };
  102218. }
  102219. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  102220. var matches;
  102221. if (this.isBinary(data)) {
  102222. // binary .stl
  102223. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  102224. this.parseBinary(babylonMesh, data);
  102225. if (meshes) {
  102226. meshes.push(babylonMesh);
  102227. }
  102228. return true;
  102229. }
  102230. // ASCII .stl
  102231. // convert to string
  102232. var array_buffer = new Uint8Array(data);
  102233. var str = '';
  102234. for (var i = 0; i < data.byteLength; i++) {
  102235. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  102236. }
  102237. data = str;
  102238. while (matches = this.solidPattern.exec(data)) {
  102239. var meshName = matches[1];
  102240. var meshNameFromEnd = matches[3];
  102241. if (meshName != meshNameFromEnd) {
  102242. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  102243. return false;
  102244. }
  102245. // check meshesNames
  102246. if (meshesNames && meshName) {
  102247. if (meshesNames instanceof Array) {
  102248. if (!meshesNames.indexOf(meshName)) {
  102249. continue;
  102250. }
  102251. }
  102252. else {
  102253. if (meshName !== meshesNames) {
  102254. continue;
  102255. }
  102256. }
  102257. }
  102258. // stl mesh name can be empty as well
  102259. meshName = meshName || "stlmesh";
  102260. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  102261. this.parseASCII(babylonMesh, matches[2]);
  102262. if (meshes) {
  102263. meshes.push(babylonMesh);
  102264. }
  102265. }
  102266. return true;
  102267. };
  102268. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  102269. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  102270. if (result) {
  102271. scene.createDefaultCameraOrLight();
  102272. }
  102273. return result;
  102274. };
  102275. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  102276. var container = new BABYLON.AssetContainer(scene);
  102277. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  102278. container.removeAllFromScene();
  102279. return container;
  102280. };
  102281. STLFileLoader.prototype.isBinary = function (data) {
  102282. // check if file size is correct for binary stl
  102283. var faceSize, nFaces, reader;
  102284. reader = new DataView(data);
  102285. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  102286. nFaces = reader.getUint32(80, true);
  102287. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  102288. return true;
  102289. }
  102290. // check characters higher than ASCII to confirm binary
  102291. var fileLength = reader.byteLength;
  102292. for (var index = 0; index < fileLength; index++) {
  102293. if (reader.getUint8(index) > 127) {
  102294. return true;
  102295. }
  102296. }
  102297. return false;
  102298. };
  102299. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  102300. var reader = new DataView(data);
  102301. var faces = reader.getUint32(80, true);
  102302. var dataOffset = 84;
  102303. var faceLength = 12 * 4 + 2;
  102304. var offset = 0;
  102305. var positions = new Float32Array(faces * 3 * 3);
  102306. var normals = new Float32Array(faces * 3 * 3);
  102307. var indices = new Uint32Array(faces * 3);
  102308. var indicesCount = 0;
  102309. for (var face = 0; face < faces; face++) {
  102310. var start = dataOffset + face * faceLength;
  102311. var normalX = reader.getFloat32(start, true);
  102312. var normalY = reader.getFloat32(start + 4, true);
  102313. var normalZ = reader.getFloat32(start + 8, true);
  102314. for (var i = 1; i <= 3; i++) {
  102315. var vertexstart = start + i * 12;
  102316. // ordering is intentional to match ascii import
  102317. positions[offset] = reader.getFloat32(vertexstart, true);
  102318. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  102319. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  102320. normals[offset] = normalX;
  102321. normals[offset + 2] = normalY;
  102322. normals[offset + 1] = normalZ;
  102323. offset += 3;
  102324. }
  102325. indices[indicesCount] = indicesCount++;
  102326. indices[indicesCount] = indicesCount++;
  102327. indices[indicesCount] = indicesCount++;
  102328. }
  102329. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  102330. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  102331. mesh.setIndices(indices);
  102332. mesh.computeWorldMatrix(true);
  102333. };
  102334. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  102335. var positions = [];
  102336. var normals = [];
  102337. var indices = [];
  102338. var indicesCount = 0;
  102339. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  102340. var matches;
  102341. while (matches = this.facetsPattern.exec(solidData)) {
  102342. var facet = matches[1];
  102343. //one normal per face
  102344. var normalMatches = this.normalPattern.exec(facet);
  102345. this.normalPattern.lastIndex = 0;
  102346. if (!normalMatches) {
  102347. continue;
  102348. }
  102349. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  102350. var vertexMatch;
  102351. while (vertexMatch = this.vertexPattern.exec(facet)) {
  102352. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  102353. normals.push(normal[0], normal[1], normal[2]);
  102354. }
  102355. indices.push(indicesCount++, indicesCount++, indicesCount++);
  102356. this.vertexPattern.lastIndex = 0;
  102357. }
  102358. this.facetsPattern.lastIndex = 0;
  102359. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  102360. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  102361. mesh.setIndices(indices);
  102362. mesh.computeWorldMatrix(true);
  102363. };
  102364. return STLFileLoader;
  102365. }());
  102366. BABYLON.STLFileLoader = STLFileLoader;
  102367. if (BABYLON.SceneLoader) {
  102368. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  102369. }
  102370. })(BABYLON || (BABYLON = {}));
  102371. //# sourceMappingURL=babylon.stlFileLoader.js.map
  102372. var BABYLON;
  102373. (function (BABYLON) {
  102374. /**
  102375. * Class reading and parsing the MTL file bundled with the obj file.
  102376. */
  102377. var MTLFileLoader = /** @class */ (function () {
  102378. function MTLFileLoader() {
  102379. // All material loaded from the mtl will be set here
  102380. this.materials = [];
  102381. }
  102382. /**
  102383. * This function will read the mtl file and create each material described inside
  102384. * This function could be improve by adding :
  102385. * -some component missing (Ni, Tf...)
  102386. * -including the specific options available
  102387. *
  102388. * @param scene
  102389. * @param data
  102390. * @param rootUrl
  102391. */
  102392. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  102393. if (data instanceof ArrayBuffer) {
  102394. return;
  102395. }
  102396. //Split the lines from the file
  102397. var lines = data.split('\n');
  102398. //Space char
  102399. var delimiter_pattern = /\s+/;
  102400. //Array with RGB colors
  102401. var color;
  102402. //New material
  102403. var material = null;
  102404. //Look at each line
  102405. for (var i = 0; i < lines.length; i++) {
  102406. var line = lines[i].trim();
  102407. // Blank line or comment
  102408. if (line.length === 0 || line.charAt(0) === '#') {
  102409. continue;
  102410. }
  102411. //Get the first parameter (keyword)
  102412. var pos = line.indexOf(' ');
  102413. var key = (pos >= 0) ? line.substring(0, pos) : line;
  102414. key = key.toLowerCase();
  102415. //Get the data following the key
  102416. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  102417. //This mtl keyword will create the new material
  102418. if (key === "newmtl") {
  102419. //Check if it is the first material.
  102420. // Materials specifications are described after this keyword.
  102421. if (material) {
  102422. //Add the previous material in the material array.
  102423. this.materials.push(material);
  102424. }
  102425. //Create a new material.
  102426. // value is the name of the material read in the mtl file
  102427. material = new BABYLON.StandardMaterial(value, scene);
  102428. }
  102429. else if (key === "kd" && material) {
  102430. // Diffuse color (color under white light) using RGB values
  102431. //value = "r g b"
  102432. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102433. //color = [r,g,b]
  102434. //Set tghe color into the material
  102435. material.diffuseColor = BABYLON.Color3.FromArray(color);
  102436. }
  102437. else if (key === "ka" && material) {
  102438. // Ambient color (color under shadow) using RGB values
  102439. //value = "r g b"
  102440. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102441. //color = [r,g,b]
  102442. //Set tghe color into the material
  102443. material.ambientColor = BABYLON.Color3.FromArray(color);
  102444. }
  102445. else if (key === "ks" && material) {
  102446. // Specular color (color when light is reflected from shiny surface) using RGB values
  102447. //value = "r g b"
  102448. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102449. //color = [r,g,b]
  102450. //Set the color into the material
  102451. material.specularColor = BABYLON.Color3.FromArray(color);
  102452. }
  102453. else if (key === "ke" && material) {
  102454. // Emissive color using RGB values
  102455. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102456. material.emissiveColor = BABYLON.Color3.FromArray(color);
  102457. }
  102458. else if (key === "ns" && material) {
  102459. //value = "Integer"
  102460. material.specularPower = parseFloat(value);
  102461. }
  102462. else if (key === "d" && material) {
  102463. //d is dissolve for current material. It mean alpha for BABYLON
  102464. material.alpha = parseFloat(value);
  102465. //Texture
  102466. //This part can be improved by adding the possible options of texture
  102467. }
  102468. else if (key === "map_ka" && material) {
  102469. // ambient texture map with a loaded image
  102470. //We must first get the folder of the image
  102471. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102472. }
  102473. else if (key === "map_kd" && material) {
  102474. // Diffuse texture map with a loaded image
  102475. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102476. }
  102477. else if (key === "map_ks" && material) {
  102478. // Specular texture map with a loaded image
  102479. //We must first get the folder of the image
  102480. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102481. }
  102482. else if (key === "map_ns") {
  102483. //Specular
  102484. //Specular highlight component
  102485. //We must first get the folder of the image
  102486. //
  102487. //Not supported by BABYLON
  102488. //
  102489. // continue;
  102490. }
  102491. else if (key === "map_bump" && material) {
  102492. //The bump texture
  102493. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102494. }
  102495. else if (key === "map_d" && material) {
  102496. // The dissolve of the material
  102497. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102498. //Options for illumination
  102499. }
  102500. else if (key === "illum") {
  102501. //Illumination
  102502. if (value === "0") {
  102503. //That mean Kd == Kd
  102504. }
  102505. else if (value === "1") {
  102506. //Color on and Ambient on
  102507. }
  102508. else if (value === "2") {
  102509. //Highlight on
  102510. }
  102511. else if (value === "3") {
  102512. //Reflection on and Ray trace on
  102513. }
  102514. else if (value === "4") {
  102515. //Transparency: Glass on, Reflection: Ray trace on
  102516. }
  102517. else if (value === "5") {
  102518. //Reflection: Fresnel on and Ray trace on
  102519. }
  102520. else if (value === "6") {
  102521. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  102522. }
  102523. else if (value === "7") {
  102524. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  102525. }
  102526. else if (value === "8") {
  102527. //Reflection on and Ray trace off
  102528. }
  102529. else if (value === "9") {
  102530. //Transparency: Glass on, Reflection: Ray trace off
  102531. }
  102532. else if (value === "10") {
  102533. //Casts shadows onto invisible surfaces
  102534. }
  102535. }
  102536. else {
  102537. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  102538. }
  102539. }
  102540. //At the end of the file, add the last material
  102541. if (material) {
  102542. this.materials.push(material);
  102543. }
  102544. };
  102545. /**
  102546. * Gets the texture for the material.
  102547. *
  102548. * If the material is imported from input file,
  102549. * We sanitize the url to ensure it takes the textre from aside the material.
  102550. *
  102551. * @param rootUrl The root url to load from
  102552. * @param value The value stored in the mtl
  102553. * @return The Texture
  102554. */
  102555. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  102556. if (!value) {
  102557. return null;
  102558. }
  102559. var url = rootUrl;
  102560. // Load from input file.
  102561. if (rootUrl === "file:") {
  102562. var lastDelimiter = value.lastIndexOf("\\");
  102563. if (lastDelimiter === -1) {
  102564. lastDelimiter = value.lastIndexOf("/");
  102565. }
  102566. if (lastDelimiter > -1) {
  102567. url += value.substr(lastDelimiter + 1);
  102568. }
  102569. else {
  102570. url += value;
  102571. }
  102572. }
  102573. // Not from input file.
  102574. else {
  102575. url += value;
  102576. }
  102577. return new BABYLON.Texture(url, scene);
  102578. };
  102579. return MTLFileLoader;
  102580. }());
  102581. BABYLON.MTLFileLoader = MTLFileLoader;
  102582. var OBJFileLoader = /** @class */ (function () {
  102583. function OBJFileLoader() {
  102584. this.name = "obj";
  102585. this.extensions = ".obj";
  102586. this.obj = /^o/;
  102587. this.group = /^g/;
  102588. this.mtllib = /^mtllib /;
  102589. this.usemtl = /^usemtl /;
  102590. this.smooth = /^s /;
  102591. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102592. // vn float float float
  102593. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102594. // vt float float
  102595. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102596. // f vertex vertex vertex ...
  102597. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  102598. // f vertex/uvs vertex/uvs vertex/uvs ...
  102599. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  102600. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  102601. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  102602. // f vertex//normal vertex//normal vertex//normal ...
  102603. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  102604. }
  102605. /**
  102606. * Calls synchronously the MTL file attached to this obj.
  102607. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  102608. * Without this function materials are not displayed in the first frame (but displayed after).
  102609. * In consequence it is impossible to get material information in your HTML file
  102610. *
  102611. * @param url The URL of the MTL file
  102612. * @param rootUrl
  102613. * @param onSuccess Callback function to be called when the MTL file is loaded
  102614. * @private
  102615. */
  102616. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  102617. //The complete path to the mtl file
  102618. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  102619. // Loads through the babylon tools to allow fileInput search.
  102620. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  102621. };
  102622. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  102623. //get the meshes from OBJ file
  102624. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  102625. //Push meshes from OBJ file into the variable mesh of this function
  102626. if (meshes) {
  102627. loadedMeshes.forEach(function (mesh) {
  102628. meshes.push(mesh);
  102629. });
  102630. }
  102631. return true;
  102632. };
  102633. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  102634. //Get the 3D model
  102635. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  102636. };
  102637. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  102638. var container = new BABYLON.AssetContainer(scene);
  102639. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  102640. container.removeAllFromScene();
  102641. return container;
  102642. };
  102643. /**
  102644. * Read the OBJ file and create an Array of meshes.
  102645. * Each mesh contains all information given by the OBJ and the MTL file.
  102646. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  102647. *
  102648. * @param meshesNames
  102649. * @param scene BABYLON.Scene The scene where are displayed the data
  102650. * @param data String The content of the obj file
  102651. * @param rootUrl String The path to the folder
  102652. * @returns Array<AbstractMesh>
  102653. * @private
  102654. */
  102655. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  102656. var positions = []; //values for the positions of vertices
  102657. var normals = []; //Values for the normals
  102658. var uvs = []; //Values for the textures
  102659. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  102660. var handledMesh; //The current mesh of meshes array
  102661. var indicesForBabylon = []; //The list of indices for VertexData
  102662. var wrappedPositionForBabylon = []; //The list of position in vectors
  102663. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  102664. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  102665. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  102666. var curPositionInIndices = 0;
  102667. var hasMeshes = false; //Meshes are defined in the file
  102668. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  102669. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  102670. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  102671. var triangles = []; //Indices from new triangles coming from polygons
  102672. var materialNameFromObj = ""; //The name of the current material
  102673. var fileToLoad = ""; //The name of the mtlFile to load
  102674. var materialsFromMTLFile = new MTLFileLoader();
  102675. var objMeshName = ""; //The name of the current obj mesh
  102676. var increment = 1; //Id for meshes created by the multimaterial
  102677. var isFirstMaterial = true;
  102678. /**
  102679. * Search for obj in the given array.
  102680. * This function is called to check if a couple of data already exists in an array.
  102681. *
  102682. * If found, returns the index of the founded tuple index. Returns -1 if not found
  102683. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  102684. * @param obj Array<number>
  102685. * @returns {boolean}
  102686. */
  102687. var isInArray = function (arr, obj) {
  102688. if (!arr[obj[0]])
  102689. arr[obj[0]] = { normals: [], idx: [] };
  102690. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  102691. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  102692. };
  102693. var isInArrayUV = function (arr, obj) {
  102694. if (!arr[obj[0]])
  102695. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  102696. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  102697. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  102698. return arr[obj[0]].idx[idx];
  102699. }
  102700. return -1;
  102701. };
  102702. /**
  102703. * This function set the data for each triangle.
  102704. * Data are position, normals and uvs
  102705. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  102706. * If the tuple already exist, add only their indice
  102707. *
  102708. * @param indicePositionFromObj Integer The index in positions array
  102709. * @param indiceUvsFromObj Integer The index in uvs array
  102710. * @param indiceNormalFromObj Integer The index in normals array
  102711. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  102712. * @param textureVectorFromOBJ Vector3 The value of uvs
  102713. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  102714. */
  102715. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  102716. //Check if this tuple already exists in the list of tuples
  102717. var _index;
  102718. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  102719. _index = isInArrayUV(tuplePosNorm, [
  102720. indicePositionFromObj,
  102721. indiceNormalFromObj,
  102722. indiceUvsFromObj
  102723. ]);
  102724. }
  102725. else {
  102726. _index = isInArray(tuplePosNorm, [
  102727. indicePositionFromObj,
  102728. indiceNormalFromObj
  102729. ]);
  102730. }
  102731. //If it not exists
  102732. if (_index == -1) {
  102733. //Add an new indice.
  102734. //The array of indices is only an array with his length equal to the number of triangles - 1.
  102735. //We add vertices data in this order
  102736. indicesForBabylon.push(wrappedPositionForBabylon.length);
  102737. //Push the position of vertice for Babylon
  102738. //Each element is a BABYLON.Vector3(x,y,z)
  102739. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  102740. //Push the uvs for Babylon
  102741. //Each element is a BABYLON.Vector3(u,v)
  102742. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  102743. //Push the normals for Babylon
  102744. //Each element is a BABYLON.Vector3(x,y,z)
  102745. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  102746. //Add the tuple in the comparison list
  102747. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  102748. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  102749. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  102750. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  102751. }
  102752. else {
  102753. //The tuple already exists
  102754. //Add the index of the already existing tuple
  102755. //At this index we can get the value of position, normal and uvs of vertex
  102756. indicesForBabylon.push(_index);
  102757. }
  102758. };
  102759. /**
  102760. * Transform BABYLON.Vector() object onto 3 digits in an array
  102761. */
  102762. var unwrapData = function () {
  102763. //Every array has the same length
  102764. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  102765. //Push the x, y, z values of each element in the unwrapped array
  102766. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  102767. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  102768. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  102769. }
  102770. // Reset arrays for the next new meshes
  102771. wrappedPositionForBabylon = [];
  102772. wrappedNormalsForBabylon = [];
  102773. wrappedUvsForBabylon = [];
  102774. tuplePosNorm = [];
  102775. curPositionInIndices = 0;
  102776. };
  102777. /**
  102778. * Create triangles from polygons by recursion
  102779. * The best to understand how it works is to draw it in the same time you get the recursion.
  102780. * It is important to notice that a triangle is a polygon
  102781. * We get 4 patterns of face defined in OBJ File :
  102782. * facePattern1 = ["1","2","3","4","5","6"]
  102783. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  102784. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  102785. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  102786. * Each pattern is divided by the same method
  102787. * @param face Array[String] The indices of elements
  102788. * @param v Integer The variable to increment
  102789. */
  102790. var getTriangles = function (face, v) {
  102791. //Work for each element of the array
  102792. if (v + 1 < face.length) {
  102793. //Add on the triangle variable the indexes to obtain triangles
  102794. triangles.push(face[0], face[v], face[v + 1]);
  102795. //Incrementation for recursion
  102796. v += 1;
  102797. //Recursion
  102798. getTriangles(face, v);
  102799. }
  102800. //Result obtained after 2 iterations:
  102801. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  102802. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  102803. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  102804. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  102805. };
  102806. /**
  102807. * Create triangles and push the data for each polygon for the pattern 1
  102808. * In this pattern we get vertice positions
  102809. * @param face
  102810. * @param v
  102811. */
  102812. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  102813. //Get the indices of triangles for each polygon
  102814. getTriangles(face, v);
  102815. //For each element in the triangles array.
  102816. //This var could contains 1 to an infinity of triangles
  102817. for (var k = 0; k < triangles.length; k++) {
  102818. // Set position indice
  102819. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  102820. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  102821. positions[indicePositionFromObj], //Get the vectors data
  102822. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  102823. );
  102824. }
  102825. //Reset variable for the next line
  102826. triangles = [];
  102827. };
  102828. /**
  102829. * Create triangles and push the data for each polygon for the pattern 2
  102830. * In this pattern we get vertice positions and uvsu
  102831. * @param face
  102832. * @param v
  102833. */
  102834. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  102835. //Get the indices of triangles for each polygon
  102836. getTriangles(face, v);
  102837. for (var k = 0; k < triangles.length; k++) {
  102838. //triangle[k] = "1/1"
  102839. //Split the data for getting position and uv
  102840. var point = triangles[k].split("/"); // ["1", "1"]
  102841. //Set position indice
  102842. var indicePositionFromObj = parseInt(point[0]) - 1;
  102843. //Set uv indice
  102844. var indiceUvsFromObj = parseInt(point[1]) - 1;
  102845. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  102846. positions[indicePositionFromObj], //Get the values for each element
  102847. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  102848. );
  102849. }
  102850. //Reset variable for the next line
  102851. triangles = [];
  102852. };
  102853. /**
  102854. * Create triangles and push the data for each polygon for the pattern 3
  102855. * In this pattern we get vertice positions, uvs and normals
  102856. * @param face
  102857. * @param v
  102858. */
  102859. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  102860. //Get the indices of triangles for each polygon
  102861. getTriangles(face, v);
  102862. for (var k = 0; k < triangles.length; k++) {
  102863. //triangle[k] = "1/1/1"
  102864. //Split the data for getting position, uv, and normals
  102865. var point = triangles[k].split("/"); // ["1", "1", "1"]
  102866. // Set position indice
  102867. var indicePositionFromObj = parseInt(point[0]) - 1;
  102868. // Set uv indice
  102869. var indiceUvsFromObj = parseInt(point[1]) - 1;
  102870. // Set normal indice
  102871. var indiceNormalFromObj = parseInt(point[2]) - 1;
  102872. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  102873. );
  102874. }
  102875. //Reset variable for the next line
  102876. triangles = [];
  102877. };
  102878. /**
  102879. * Create triangles and push the data for each polygon for the pattern 4
  102880. * In this pattern we get vertice positions and normals
  102881. * @param face
  102882. * @param v
  102883. */
  102884. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  102885. getTriangles(face, v);
  102886. for (var k = 0; k < triangles.length; k++) {
  102887. //triangle[k] = "1//1"
  102888. //Split the data for getting position and normals
  102889. var point = triangles[k].split("//"); // ["1", "1"]
  102890. // We check indices, and normals
  102891. var indicePositionFromObj = parseInt(point[0]) - 1;
  102892. var indiceNormalFromObj = parseInt(point[1]) - 1;
  102893. setData(indicePositionFromObj, 1, //Default value for uv
  102894. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  102895. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  102896. }
  102897. //Reset variable for the next line
  102898. triangles = [];
  102899. };
  102900. var addPreviousObjMesh = function () {
  102901. //Check if it is not the first mesh. Otherwise we don't have data.
  102902. if (meshesFromObj.length > 0) {
  102903. //Get the previous mesh for applying the data about the faces
  102904. //=> in obj file, faces definition append after the name of the mesh
  102905. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  102906. //Set the data into Array for the mesh
  102907. unwrapData();
  102908. // Reverse tab. Otherwise face are displayed in the wrong sens
  102909. indicesForBabylon.reverse();
  102910. //Set the information for the mesh
  102911. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  102912. handledMesh.indices = indicesForBabylon.slice();
  102913. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  102914. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  102915. handledMesh.uvs = unwrappedUVForBabylon.slice();
  102916. //Reset the array for the next mesh
  102917. indicesForBabylon = [];
  102918. unwrappedPositionsForBabylon = [];
  102919. unwrappedNormalsForBabylon = [];
  102920. unwrappedUVForBabylon = [];
  102921. }
  102922. };
  102923. //Main function
  102924. //Split the file into lines
  102925. var lines = data.split('\n');
  102926. //Look at each line
  102927. for (var i = 0; i < lines.length; i++) {
  102928. var line = lines[i].trim();
  102929. var result;
  102930. //Comment or newLine
  102931. if (line.length === 0 || line.charAt(0) === '#') {
  102932. continue;
  102933. //Get information about one position possible for the vertices
  102934. }
  102935. else if ((result = this.vertexPattern.exec(line)) !== null) {
  102936. //Create a Vector3 with the position x, y, z
  102937. //Value of result:
  102938. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102939. //Add the Vector in the list of positions
  102940. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102941. }
  102942. else if ((result = this.normalPattern.exec(line)) !== null) {
  102943. //Create a Vector3 with the normals x, y, z
  102944. //Value of result
  102945. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102946. //Add the Vector in the list of normals
  102947. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102948. }
  102949. else if ((result = this.uvPattern.exec(line)) !== null) {
  102950. //Create a Vector2 with the normals u, v
  102951. //Value of result
  102952. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  102953. //Add the Vector in the list of uvs
  102954. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  102955. //Identify patterns of faces
  102956. //Face could be defined in different type of pattern
  102957. }
  102958. else if ((result = this.facePattern3.exec(line)) !== null) {
  102959. //Value of result:
  102960. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  102961. //Set the data for this face
  102962. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  102963. 1);
  102964. }
  102965. else if ((result = this.facePattern4.exec(line)) !== null) {
  102966. //Value of result:
  102967. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  102968. //Set the data for this face
  102969. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  102970. 1);
  102971. }
  102972. else if ((result = this.facePattern2.exec(line)) !== null) {
  102973. //Value of result:
  102974. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  102975. //Set the data for this face
  102976. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  102977. 1);
  102978. }
  102979. else if ((result = this.facePattern1.exec(line)) !== null) {
  102980. //Value of result
  102981. //["f 1 2 3", "1 2 3"...]
  102982. //Set the data for this face
  102983. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  102984. 1);
  102985. //Define a mesh or an object
  102986. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  102987. }
  102988. else if (this.group.test(line) || this.obj.test(line)) {
  102989. //Create a new mesh corresponding to the name of the group.
  102990. //Definition of the mesh
  102991. var objMesh =
  102992. //Set the name of the current obj mesh
  102993. {
  102994. name: line.substring(2).trim(),
  102995. indices: undefined,
  102996. positions: undefined,
  102997. normals: undefined,
  102998. uvs: undefined,
  102999. materialName: ""
  103000. };
  103001. addPreviousObjMesh();
  103002. //Push the last mesh created with only the name
  103003. meshesFromObj.push(objMesh);
  103004. //Set this variable to indicate that now meshesFromObj has objects defined inside
  103005. hasMeshes = true;
  103006. isFirstMaterial = true;
  103007. increment = 1;
  103008. //Keyword for applying a material
  103009. }
  103010. else if (this.usemtl.test(line)) {
  103011. //Get the name of the material
  103012. materialNameFromObj = line.substring(7).trim();
  103013. //If this new material is in the same mesh
  103014. if (!isFirstMaterial) {
  103015. //Set the data for the previous mesh
  103016. addPreviousObjMesh();
  103017. //Create a new mesh
  103018. var objMesh =
  103019. //Set the name of the current obj mesh
  103020. {
  103021. name: objMeshName + "_mm" + increment.toString(),
  103022. indices: undefined,
  103023. positions: undefined,
  103024. normals: undefined,
  103025. uvs: undefined,
  103026. materialName: materialNameFromObj
  103027. };
  103028. increment++;
  103029. //If meshes are already defined
  103030. meshesFromObj.push(objMesh);
  103031. }
  103032. //Set the material name if the previous line define a mesh
  103033. if (hasMeshes && isFirstMaterial) {
  103034. //Set the material name to the previous mesh (1 material per mesh)
  103035. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  103036. isFirstMaterial = false;
  103037. }
  103038. //Keyword for loading the mtl file
  103039. }
  103040. else if (this.mtllib.test(line)) {
  103041. //Get the name of mtl file
  103042. fileToLoad = line.substring(7).trim();
  103043. //Apply smoothing
  103044. }
  103045. else if (this.smooth.test(line)) {
  103046. // smooth shading => apply smoothing
  103047. //Toda y I don't know it work with babylon and with obj.
  103048. //With the obj file an integer is set
  103049. }
  103050. else {
  103051. //If there is another possibility
  103052. console.log("Unhandled expression at line : " + line);
  103053. }
  103054. }
  103055. //At the end of the file, add the last mesh into the meshesFromObj array
  103056. if (hasMeshes) {
  103057. //Set the data for the last mesh
  103058. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  103059. //Reverse indices for displaying faces in the good sens
  103060. indicesForBabylon.reverse();
  103061. //Get the good array
  103062. unwrapData();
  103063. //Set array
  103064. handledMesh.indices = indicesForBabylon;
  103065. handledMesh.positions = unwrappedPositionsForBabylon;
  103066. handledMesh.normals = unwrappedNormalsForBabylon;
  103067. handledMesh.uvs = unwrappedUVForBabylon;
  103068. }
  103069. //If any o or g keyword found, create a mesj with a random id
  103070. if (!hasMeshes) {
  103071. // reverse tab of indices
  103072. indicesForBabylon.reverse();
  103073. //Get positions normals uvs
  103074. unwrapData();
  103075. //Set data for one mesh
  103076. meshesFromObj.push({
  103077. name: BABYLON.Geometry.RandomId(),
  103078. indices: indicesForBabylon,
  103079. positions: unwrappedPositionsForBabylon,
  103080. normals: unwrappedNormalsForBabylon,
  103081. uvs: unwrappedUVForBabylon,
  103082. materialName: materialNameFromObj
  103083. });
  103084. }
  103085. //Create a BABYLON.Mesh list
  103086. var babylonMeshesArray = []; //The mesh for babylon
  103087. var materialToUse = new Array();
  103088. //Set data for each mesh
  103089. for (var j = 0; j < meshesFromObj.length; j++) {
  103090. //check meshesNames (stlFileLoader)
  103091. if (meshesNames && meshesFromObj[j].name) {
  103092. if (meshesNames instanceof Array) {
  103093. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  103094. continue;
  103095. }
  103096. }
  103097. else {
  103098. if (meshesFromObj[j].name !== meshesNames) {
  103099. continue;
  103100. }
  103101. }
  103102. }
  103103. //Get the current mesh
  103104. //Set the data with VertexBuffer for each mesh
  103105. handledMesh = meshesFromObj[j];
  103106. //Create a BABYLON.Mesh with the name of the obj mesh
  103107. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  103108. //Push the name of the material to an array
  103109. //This is indispensable for the importMesh function
  103110. materialToUse.push(meshesFromObj[j].materialName);
  103111. var vertexData = new BABYLON.VertexData(); //The container for the values
  103112. //Set the data for the babylonMesh
  103113. vertexData.positions = handledMesh.positions;
  103114. vertexData.normals = handledMesh.normals;
  103115. vertexData.uvs = handledMesh.uvs;
  103116. vertexData.indices = handledMesh.indices;
  103117. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  103118. vertexData.applyToMesh(babylonMesh);
  103119. if (OBJFileLoader.INVERT_Y) {
  103120. babylonMesh.scaling.y *= -1;
  103121. }
  103122. //Push the mesh into an array
  103123. babylonMeshesArray.push(babylonMesh);
  103124. }
  103125. //load the materials
  103126. //Check if we have a file to load
  103127. if (fileToLoad !== "") {
  103128. //Load the file synchronously
  103129. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  103130. //Create materials thanks MTLLoader function
  103131. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  103132. //Look at each material loaded in the mtl file
  103133. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  103134. //Three variables to get all meshes with the same material
  103135. var startIndex = 0;
  103136. var _indices = [];
  103137. var _index;
  103138. //The material from MTL file is used in the meshes loaded
  103139. //Push the indice in an array
  103140. //Check if the material is not used for another mesh
  103141. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  103142. _indices.push(_index);
  103143. startIndex = _index + 1;
  103144. }
  103145. //If the material is not used dispose it
  103146. if (_index == -1 && _indices.length == 0) {
  103147. //If the material is not needed, remove it
  103148. materialsFromMTLFile.materials[n].dispose();
  103149. }
  103150. else {
  103151. for (var o = 0; o < _indices.length; o++) {
  103152. //Apply the material to the BABYLON.Mesh for each mesh with the material
  103153. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  103154. }
  103155. }
  103156. }
  103157. });
  103158. }
  103159. //Return an array with all BABYLON.Mesh
  103160. return babylonMeshesArray;
  103161. };
  103162. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  103163. OBJFileLoader.INVERT_Y = false;
  103164. return OBJFileLoader;
  103165. }());
  103166. BABYLON.OBJFileLoader = OBJFileLoader;
  103167. if (BABYLON.SceneLoader) {
  103168. //Add this loader into the register plugin
  103169. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  103170. }
  103171. })(BABYLON || (BABYLON = {}));
  103172. //# sourceMappingURL=babylon.objFileLoader.js.map
  103173. var BABYLON;
  103174. (function (BABYLON) {
  103175. /**
  103176. * Mode that determines the coordinate system to use.
  103177. */
  103178. var GLTFLoaderCoordinateSystemMode;
  103179. (function (GLTFLoaderCoordinateSystemMode) {
  103180. /**
  103181. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  103182. */
  103183. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  103184. /**
  103185. * Sets the useRightHandedSystem flag on the scene.
  103186. */
  103187. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  103188. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  103189. /**
  103190. * Mode that determines what animations will start.
  103191. */
  103192. var GLTFLoaderAnimationStartMode;
  103193. (function (GLTFLoaderAnimationStartMode) {
  103194. /**
  103195. * No animation will start.
  103196. */
  103197. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  103198. /**
  103199. * The first animation will start.
  103200. */
  103201. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  103202. /**
  103203. * All animations will start.
  103204. */
  103205. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  103206. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  103207. /**
  103208. * Loader state.
  103209. */
  103210. var GLTFLoaderState;
  103211. (function (GLTFLoaderState) {
  103212. /**
  103213. * The asset is loading.
  103214. */
  103215. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  103216. /**
  103217. * The asset is ready for rendering.
  103218. */
  103219. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  103220. /**
  103221. * The asset is completely loaded.
  103222. */
  103223. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  103224. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  103225. /**
  103226. * File loader for loading glTF files into a scene.
  103227. */
  103228. var GLTFFileLoader = /** @class */ (function () {
  103229. function GLTFFileLoader() {
  103230. // #region Common options
  103231. /**
  103232. * Raised when the asset has been parsed
  103233. */
  103234. this.onParsedObservable = new BABYLON.Observable();
  103235. // #endregion
  103236. // #region V2 options
  103237. /**
  103238. * The coordinate system mode. Defaults to AUTO.
  103239. */
  103240. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  103241. /**
  103242. * The animation start mode. Defaults to FIRST.
  103243. */
  103244. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  103245. /**
  103246. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  103247. */
  103248. this.compileMaterials = false;
  103249. /**
  103250. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  103251. */
  103252. this.useClipPlane = false;
  103253. /**
  103254. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  103255. */
  103256. this.compileShadowGenerators = false;
  103257. /**
  103258. * Defines if the Alpha blended materials are only applied as coverage.
  103259. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  103260. * If true, no extra effects are applied to transparent pixels.
  103261. */
  103262. this.transparencyAsCoverage = false;
  103263. /** @hidden */
  103264. this._normalizeAnimationGroupsToBeginAtZero = true;
  103265. /**
  103266. * Function called before loading a url referenced by the asset.
  103267. */
  103268. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103269. /**
  103270. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  103271. */
  103272. this.onMeshLoadedObservable = new BABYLON.Observable();
  103273. /**
  103274. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  103275. */
  103276. this.onTextureLoadedObservable = new BABYLON.Observable();
  103277. /**
  103278. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  103279. */
  103280. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103281. /**
  103282. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  103283. */
  103284. this.onCameraLoadedObservable = new BABYLON.Observable();
  103285. /**
  103286. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  103287. * For assets with LODs, raised when all of the LODs are complete.
  103288. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  103289. */
  103290. this.onCompleteObservable = new BABYLON.Observable();
  103291. /**
  103292. * Observable raised after the loader is disposed.
  103293. */
  103294. this.onDisposeObservable = new BABYLON.Observable();
  103295. /**
  103296. * Observable raised after a loader extension is created.
  103297. * Set additional options for a loader extension in this event.
  103298. */
  103299. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103300. // #endregion
  103301. this._loader = null;
  103302. /**
  103303. * Name of the loader ("gltf")
  103304. */
  103305. this.name = "gltf";
  103306. /**
  103307. * Supported file extensions of the loader (.gltf, .glb)
  103308. */
  103309. this.extensions = {
  103310. ".gltf": { isBinary: false },
  103311. ".glb": { isBinary: true }
  103312. };
  103313. }
  103314. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  103315. /**
  103316. * Raised when the asset has been parsed
  103317. */
  103318. set: function (callback) {
  103319. if (this._onParsedObserver) {
  103320. this.onParsedObservable.remove(this._onParsedObserver);
  103321. }
  103322. this._onParsedObserver = this.onParsedObservable.add(callback);
  103323. },
  103324. enumerable: true,
  103325. configurable: true
  103326. });
  103327. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  103328. /**
  103329. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  103330. */
  103331. set: function (callback) {
  103332. if (this._onMeshLoadedObserver) {
  103333. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  103334. }
  103335. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  103336. },
  103337. enumerable: true,
  103338. configurable: true
  103339. });
  103340. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  103341. /**
  103342. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  103343. */
  103344. set: function (callback) {
  103345. if (this._onTextureLoadedObserver) {
  103346. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  103347. }
  103348. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  103349. },
  103350. enumerable: true,
  103351. configurable: true
  103352. });
  103353. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  103354. /**
  103355. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  103356. */
  103357. set: function (callback) {
  103358. if (this._onMaterialLoadedObserver) {
  103359. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  103360. }
  103361. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  103362. },
  103363. enumerable: true,
  103364. configurable: true
  103365. });
  103366. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  103367. /**
  103368. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  103369. */
  103370. set: function (callback) {
  103371. if (this._onCameraLoadedObserver) {
  103372. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  103373. }
  103374. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  103375. },
  103376. enumerable: true,
  103377. configurable: true
  103378. });
  103379. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  103380. /**
  103381. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  103382. */
  103383. set: function (callback) {
  103384. if (this._onCompleteObserver) {
  103385. this.onCompleteObservable.remove(this._onCompleteObserver);
  103386. }
  103387. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  103388. },
  103389. enumerable: true,
  103390. configurable: true
  103391. });
  103392. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  103393. /**
  103394. * Callback raised after the loader is disposed.
  103395. */
  103396. set: function (callback) {
  103397. if (this._onDisposeObserver) {
  103398. this.onDisposeObservable.remove(this._onDisposeObserver);
  103399. }
  103400. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  103401. },
  103402. enumerable: true,
  103403. configurable: true
  103404. });
  103405. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  103406. /**
  103407. * Callback raised after a loader extension is created.
  103408. */
  103409. set: function (callback) {
  103410. if (this._onExtensionLoadedObserver) {
  103411. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  103412. }
  103413. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  103414. },
  103415. enumerable: true,
  103416. configurable: true
  103417. });
  103418. /**
  103419. * Returns a promise that resolves when the asset is completely loaded.
  103420. * @returns a promise that resolves when the asset is completely loaded.
  103421. */
  103422. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  103423. var _this = this;
  103424. return new Promise(function (resolve) {
  103425. _this.onCompleteObservable.addOnce(function () {
  103426. resolve();
  103427. });
  103428. });
  103429. };
  103430. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  103431. /**
  103432. * The loader state or null if the loader is not active.
  103433. */
  103434. get: function () {
  103435. return this._loader ? this._loader.state : null;
  103436. },
  103437. enumerable: true,
  103438. configurable: true
  103439. });
  103440. /**
  103441. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  103442. */
  103443. GLTFFileLoader.prototype.dispose = function () {
  103444. if (this._loader) {
  103445. this._loader.dispose();
  103446. this._loader = null;
  103447. }
  103448. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103449. this.onMeshLoadedObservable.clear();
  103450. this.onTextureLoadedObservable.clear();
  103451. this.onMaterialLoadedObservable.clear();
  103452. this.onCameraLoadedObservable.clear();
  103453. this.onCompleteObservable.clear();
  103454. this.onExtensionLoadedObservable.clear();
  103455. this.onDisposeObservable.notifyObservers(this);
  103456. this.onDisposeObservable.clear();
  103457. };
  103458. /**
  103459. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  103460. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103461. * @param scene the scene the meshes should be added to
  103462. * @param data the glTF data to load
  103463. * @param rootUrl root url to load from
  103464. * @param onProgress event that fires when loading progress has occured
  103465. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103466. */
  103467. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103468. var _this = this;
  103469. return Promise.resolve().then(function () {
  103470. var loaderData = _this._parse(data);
  103471. _this._loader = _this._getLoader(loaderData);
  103472. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  103473. });
  103474. };
  103475. /**
  103476. * Imports all objects from the loaded glTF data and adds them to the scene
  103477. * @param scene the scene the objects should be added to
  103478. * @param data the glTF data to load
  103479. * @param rootUrl root url to load from
  103480. * @param onProgress event that fires when loading progress has occured
  103481. * @returns a promise which completes when objects have been loaded to the scene
  103482. */
  103483. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103484. var _this = this;
  103485. return Promise.resolve().then(function () {
  103486. var loaderData = _this._parse(data);
  103487. _this._loader = _this._getLoader(loaderData);
  103488. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  103489. });
  103490. };
  103491. /**
  103492. * Load into an asset container.
  103493. * @param scene The scene to load into
  103494. * @param data The data to import
  103495. * @param rootUrl The root url for scene and resources
  103496. * @param onProgress The callback when the load progresses
  103497. * @returns The loaded asset container
  103498. */
  103499. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  103500. var _this = this;
  103501. return Promise.resolve().then(function () {
  103502. var loaderData = _this._parse(data);
  103503. _this._loader = _this._getLoader(loaderData);
  103504. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  103505. var container = new BABYLON.AssetContainer(scene);
  103506. Array.prototype.push.apply(container.meshes, result.meshes);
  103507. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  103508. Array.prototype.push.apply(container.skeletons, result.skeletons);
  103509. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  103510. container.removeAllFromScene();
  103511. return container;
  103512. });
  103513. });
  103514. };
  103515. /**
  103516. * If the data string can be loaded directly.
  103517. * @param data string contianing the file data
  103518. * @returns if the data can be loaded directly
  103519. */
  103520. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  103521. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  103522. };
  103523. /**
  103524. * Instantiates a glTF file loader plugin.
  103525. * @returns the created plugin
  103526. */
  103527. GLTFFileLoader.prototype.createPlugin = function () {
  103528. return new GLTFFileLoader();
  103529. };
  103530. GLTFFileLoader.prototype._parse = function (data) {
  103531. var parsedData;
  103532. if (data instanceof ArrayBuffer) {
  103533. parsedData = GLTFFileLoader._parseBinary(data);
  103534. }
  103535. else {
  103536. parsedData = {
  103537. json: JSON.parse(data),
  103538. bin: null
  103539. };
  103540. }
  103541. this.onParsedObservable.notifyObservers(parsedData);
  103542. this.onParsedObservable.clear();
  103543. return parsedData;
  103544. };
  103545. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  103546. var _this = this;
  103547. var loaderVersion = { major: 2, minor: 0 };
  103548. var asset = loaderData.json.asset || {};
  103549. var version = GLTFFileLoader._parseVersion(asset.version);
  103550. if (!version) {
  103551. throw new Error("Invalid version: " + asset.version);
  103552. }
  103553. if (asset.minVersion !== undefined) {
  103554. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  103555. if (!minVersion) {
  103556. throw new Error("Invalid minimum version: " + asset.minVersion);
  103557. }
  103558. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  103559. throw new Error("Incompatible minimum version: " + asset.minVersion);
  103560. }
  103561. }
  103562. var createLoaders = {
  103563. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  103564. 2: GLTFFileLoader._CreateGLTFLoaderV2
  103565. };
  103566. var createLoader = createLoaders[version.major];
  103567. if (!createLoader) {
  103568. throw new Error("Unsupported version: " + asset.version);
  103569. }
  103570. var loader = createLoader();
  103571. loader.coordinateSystemMode = this.coordinateSystemMode;
  103572. loader.animationStartMode = this.animationStartMode;
  103573. loader.compileMaterials = this.compileMaterials;
  103574. loader.useClipPlane = this.useClipPlane;
  103575. loader.compileShadowGenerators = this.compileShadowGenerators;
  103576. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  103577. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  103578. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  103579. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  103580. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  103581. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  103582. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  103583. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  103584. loader.onCompleteObservable.add(function () {
  103585. _this.onMeshLoadedObservable.clear();
  103586. _this.onTextureLoadedObservable.clear();
  103587. _this.onMaterialLoadedObservable.clear();
  103588. _this.onCameraLoadedObservable.clear();
  103589. _this.onExtensionLoadedObservable.clear();
  103590. _this.onCompleteObservable.notifyObservers(_this);
  103591. _this.onCompleteObservable.clear();
  103592. });
  103593. return loader;
  103594. };
  103595. GLTFFileLoader._parseBinary = function (data) {
  103596. var Binary = {
  103597. Magic: 0x46546C67
  103598. };
  103599. var binaryReader = new BinaryReader(data);
  103600. var magic = binaryReader.readUint32();
  103601. if (magic !== Binary.Magic) {
  103602. throw new Error("Unexpected magic: " + magic);
  103603. }
  103604. var version = binaryReader.readUint32();
  103605. switch (version) {
  103606. case 1: return GLTFFileLoader._parseV1(binaryReader);
  103607. case 2: return GLTFFileLoader._parseV2(binaryReader);
  103608. }
  103609. throw new Error("Unsupported version: " + version);
  103610. };
  103611. GLTFFileLoader._parseV1 = function (binaryReader) {
  103612. var ContentFormat = {
  103613. JSON: 0
  103614. };
  103615. var length = binaryReader.readUint32();
  103616. if (length != binaryReader.getLength()) {
  103617. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  103618. }
  103619. var contentLength = binaryReader.readUint32();
  103620. var contentFormat = binaryReader.readUint32();
  103621. var content;
  103622. switch (contentFormat) {
  103623. case ContentFormat.JSON: {
  103624. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  103625. break;
  103626. }
  103627. default: {
  103628. throw new Error("Unexpected content format: " + contentFormat);
  103629. }
  103630. }
  103631. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  103632. var body = binaryReader.readUint8Array(bytesRemaining);
  103633. return {
  103634. json: content,
  103635. bin: body
  103636. };
  103637. };
  103638. GLTFFileLoader._parseV2 = function (binaryReader) {
  103639. var ChunkFormat = {
  103640. JSON: 0x4E4F534A,
  103641. BIN: 0x004E4942
  103642. };
  103643. var length = binaryReader.readUint32();
  103644. if (length !== binaryReader.getLength()) {
  103645. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  103646. }
  103647. // JSON chunk
  103648. var chunkLength = binaryReader.readUint32();
  103649. var chunkFormat = binaryReader.readUint32();
  103650. if (chunkFormat !== ChunkFormat.JSON) {
  103651. throw new Error("First chunk format is not JSON");
  103652. }
  103653. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  103654. // Look for BIN chunk
  103655. var bin = null;
  103656. while (binaryReader.getPosition() < binaryReader.getLength()) {
  103657. var chunkLength_1 = binaryReader.readUint32();
  103658. var chunkFormat_1 = binaryReader.readUint32();
  103659. switch (chunkFormat_1) {
  103660. case ChunkFormat.JSON: {
  103661. throw new Error("Unexpected JSON chunk");
  103662. }
  103663. case ChunkFormat.BIN: {
  103664. bin = binaryReader.readUint8Array(chunkLength_1);
  103665. break;
  103666. }
  103667. default: {
  103668. // ignore unrecognized chunkFormat
  103669. binaryReader.skipBytes(chunkLength_1);
  103670. break;
  103671. }
  103672. }
  103673. }
  103674. return {
  103675. json: json,
  103676. bin: bin
  103677. };
  103678. };
  103679. GLTFFileLoader._parseVersion = function (version) {
  103680. if (version === "1.0" || version === "1.0.1") {
  103681. return {
  103682. major: 1,
  103683. minor: 0
  103684. };
  103685. }
  103686. var match = (version + "").match(/^(\d+)\.(\d+)/);
  103687. if (!match) {
  103688. return null;
  103689. }
  103690. return {
  103691. major: parseInt(match[1]),
  103692. minor: parseInt(match[2])
  103693. };
  103694. };
  103695. GLTFFileLoader._compareVersion = function (a, b) {
  103696. if (a.major > b.major)
  103697. return 1;
  103698. if (a.major < b.major)
  103699. return -1;
  103700. if (a.minor > b.minor)
  103701. return 1;
  103702. if (a.minor < b.minor)
  103703. return -1;
  103704. return 0;
  103705. };
  103706. GLTFFileLoader._decodeBufferToText = function (buffer) {
  103707. var result = "";
  103708. var length = buffer.byteLength;
  103709. for (var i = 0; i < length; i++) {
  103710. result += String.fromCharCode(buffer[i]);
  103711. }
  103712. return result;
  103713. };
  103714. // #endregion
  103715. // #region V1 options
  103716. /**
  103717. * 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.
  103718. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  103719. * Defaults to true.
  103720. */
  103721. GLTFFileLoader.IncrementalLoading = true;
  103722. /**
  103723. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  103724. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  103725. */
  103726. GLTFFileLoader.HomogeneousCoordinates = false;
  103727. return GLTFFileLoader;
  103728. }());
  103729. BABYLON.GLTFFileLoader = GLTFFileLoader;
  103730. var BinaryReader = /** @class */ (function () {
  103731. function BinaryReader(arrayBuffer) {
  103732. this._arrayBuffer = arrayBuffer;
  103733. this._dataView = new DataView(arrayBuffer);
  103734. this._byteOffset = 0;
  103735. }
  103736. BinaryReader.prototype.getPosition = function () {
  103737. return this._byteOffset;
  103738. };
  103739. BinaryReader.prototype.getLength = function () {
  103740. return this._arrayBuffer.byteLength;
  103741. };
  103742. BinaryReader.prototype.readUint32 = function () {
  103743. var value = this._dataView.getUint32(this._byteOffset, true);
  103744. this._byteOffset += 4;
  103745. return value;
  103746. };
  103747. BinaryReader.prototype.readUint8Array = function (length) {
  103748. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  103749. this._byteOffset += length;
  103750. return value;
  103751. };
  103752. BinaryReader.prototype.skipBytes = function (length) {
  103753. this._byteOffset += length;
  103754. };
  103755. return BinaryReader;
  103756. }());
  103757. if (BABYLON.SceneLoader) {
  103758. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  103759. }
  103760. })(BABYLON || (BABYLON = {}));
  103761. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  103762. var BABYLON;
  103763. (function (BABYLON) {
  103764. var GLTF1;
  103765. (function (GLTF1) {
  103766. /**
  103767. * Enums
  103768. */
  103769. var EComponentType;
  103770. (function (EComponentType) {
  103771. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  103772. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  103773. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  103774. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  103775. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  103776. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  103777. var EShaderType;
  103778. (function (EShaderType) {
  103779. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  103780. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  103781. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  103782. var EParameterType;
  103783. (function (EParameterType) {
  103784. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  103785. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  103786. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  103787. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  103788. EParameterType[EParameterType["INT"] = 5124] = "INT";
  103789. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  103790. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  103791. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  103792. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  103793. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  103794. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  103795. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  103796. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  103797. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  103798. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  103799. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  103800. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  103801. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  103802. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  103803. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  103804. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  103805. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  103806. var ETextureWrapMode;
  103807. (function (ETextureWrapMode) {
  103808. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  103809. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  103810. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  103811. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  103812. var ETextureFilterType;
  103813. (function (ETextureFilterType) {
  103814. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  103815. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  103816. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  103817. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  103818. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  103819. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  103820. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  103821. var ETextureFormat;
  103822. (function (ETextureFormat) {
  103823. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  103824. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  103825. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  103826. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  103827. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  103828. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  103829. var ECullingType;
  103830. (function (ECullingType) {
  103831. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  103832. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  103833. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  103834. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  103835. var EBlendingFunction;
  103836. (function (EBlendingFunction) {
  103837. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  103838. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  103839. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  103840. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  103841. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  103842. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  103843. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  103844. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  103845. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  103846. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  103847. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  103848. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  103849. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  103850. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  103851. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  103852. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  103853. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103854. })(BABYLON || (BABYLON = {}));
  103855. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103856. var BABYLON;
  103857. (function (BABYLON) {
  103858. var GLTF1;
  103859. (function (GLTF1) {
  103860. /**
  103861. * Tokenizer. Used for shaders compatibility
  103862. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  103863. */
  103864. var ETokenType;
  103865. (function (ETokenType) {
  103866. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  103867. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  103868. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  103869. })(ETokenType || (ETokenType = {}));
  103870. var Tokenizer = /** @class */ (function () {
  103871. function Tokenizer(toParse) {
  103872. this._pos = 0;
  103873. this.currentToken = ETokenType.UNKNOWN;
  103874. this.currentIdentifier = "";
  103875. this.currentString = "";
  103876. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  103877. this._toParse = toParse;
  103878. this._maxPos = toParse.length;
  103879. }
  103880. Tokenizer.prototype.getNextToken = function () {
  103881. if (this.isEnd())
  103882. return ETokenType.END_OF_INPUT;
  103883. this.currentString = this.read();
  103884. this.currentToken = ETokenType.UNKNOWN;
  103885. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  103886. this.currentToken = ETokenType.IDENTIFIER;
  103887. this.currentIdentifier = this.currentString;
  103888. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  103889. this.currentIdentifier += this.currentString;
  103890. this.forward();
  103891. }
  103892. }
  103893. return this.currentToken;
  103894. };
  103895. Tokenizer.prototype.peek = function () {
  103896. return this._toParse[this._pos];
  103897. };
  103898. Tokenizer.prototype.read = function () {
  103899. return this._toParse[this._pos++];
  103900. };
  103901. Tokenizer.prototype.forward = function () {
  103902. this._pos++;
  103903. };
  103904. Tokenizer.prototype.isEnd = function () {
  103905. return this._pos >= this._maxPos;
  103906. };
  103907. return Tokenizer;
  103908. }());
  103909. /**
  103910. * Values
  103911. */
  103912. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  103913. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  103914. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  103915. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  103916. /**
  103917. * Parse
  103918. */
  103919. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  103920. for (var buf in parsedBuffers) {
  103921. var parsedBuffer = parsedBuffers[buf];
  103922. gltfRuntime.buffers[buf] = parsedBuffer;
  103923. gltfRuntime.buffersCount++;
  103924. }
  103925. };
  103926. var parseShaders = function (parsedShaders, gltfRuntime) {
  103927. for (var sha in parsedShaders) {
  103928. var parsedShader = parsedShaders[sha];
  103929. gltfRuntime.shaders[sha] = parsedShader;
  103930. gltfRuntime.shaderscount++;
  103931. }
  103932. };
  103933. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  103934. for (var object in parsedObjects) {
  103935. var parsedObject = parsedObjects[object];
  103936. gltfRuntime[runtimeProperty][object] = parsedObject;
  103937. }
  103938. };
  103939. /**
  103940. * Utils
  103941. */
  103942. var normalizeUVs = function (buffer) {
  103943. if (!buffer) {
  103944. return;
  103945. }
  103946. for (var i = 0; i < buffer.length / 2; i++) {
  103947. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  103948. }
  103949. };
  103950. var getAttribute = function (attributeParameter) {
  103951. if (attributeParameter.semantic === "NORMAL") {
  103952. return "normal";
  103953. }
  103954. else if (attributeParameter.semantic === "POSITION") {
  103955. return "position";
  103956. }
  103957. else if (attributeParameter.semantic === "JOINT") {
  103958. return "matricesIndices";
  103959. }
  103960. else if (attributeParameter.semantic === "WEIGHT") {
  103961. return "matricesWeights";
  103962. }
  103963. else if (attributeParameter.semantic === "COLOR") {
  103964. return "color";
  103965. }
  103966. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  103967. var channel = Number(attributeParameter.semantic.split("_")[1]);
  103968. return "uv" + (channel === 0 ? "" : channel + 1);
  103969. }
  103970. return null;
  103971. };
  103972. /**
  103973. * Loads and creates animations
  103974. */
  103975. var loadAnimations = function (gltfRuntime) {
  103976. for (var anim in gltfRuntime.animations) {
  103977. var animation = gltfRuntime.animations[anim];
  103978. if (!animation.channels || !animation.samplers) {
  103979. continue;
  103980. }
  103981. var lastAnimation = null;
  103982. for (var i = 0; i < animation.channels.length; i++) {
  103983. // Get parameters and load buffers
  103984. var channel = animation.channels[i];
  103985. var sampler = animation.samplers[channel.sampler];
  103986. if (!sampler) {
  103987. continue;
  103988. }
  103989. var inputData = null;
  103990. var outputData = null;
  103991. if (animation.parameters) {
  103992. inputData = animation.parameters[sampler.input];
  103993. outputData = animation.parameters[sampler.output];
  103994. }
  103995. else {
  103996. inputData = sampler.input;
  103997. outputData = sampler.output;
  103998. }
  103999. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  104000. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  104001. var targetID = channel.target.id;
  104002. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  104003. if (targetNode === null) {
  104004. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  104005. }
  104006. if (targetNode === null) {
  104007. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  104008. continue;
  104009. }
  104010. var isBone = targetNode instanceof BABYLON.Bone;
  104011. // Get target path (position, rotation or scaling)
  104012. var targetPath = channel.target.path;
  104013. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  104014. if (targetPathIndex !== -1) {
  104015. targetPath = babylonAnimationPaths[targetPathIndex];
  104016. }
  104017. // Determine animation type
  104018. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  104019. if (!isBone) {
  104020. if (targetPath === "rotationQuaternion") {
  104021. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  104022. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  104023. }
  104024. else {
  104025. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104026. }
  104027. }
  104028. // Create animation and key frames
  104029. var babylonAnimation = null;
  104030. var keys = [];
  104031. var arrayOffset = 0;
  104032. var modifyKey = false;
  104033. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  104034. babylonAnimation = lastAnimation;
  104035. modifyKey = true;
  104036. }
  104037. if (!modifyKey) {
  104038. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  104039. }
  104040. // For each frame
  104041. for (var j = 0; j < bufferInput.length; j++) {
  104042. var value = null;
  104043. if (targetPath === "rotationQuaternion") { // VEC4
  104044. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  104045. arrayOffset += 4;
  104046. }
  104047. else { // Position and scaling are VEC3
  104048. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  104049. arrayOffset += 3;
  104050. }
  104051. if (isBone) {
  104052. var bone = targetNode;
  104053. var translation = BABYLON.Vector3.Zero();
  104054. var rotationQuaternion = new BABYLON.Quaternion();
  104055. var scaling = BABYLON.Vector3.Zero();
  104056. // Warning on decompose
  104057. var mat = bone.getBaseMatrix();
  104058. if (modifyKey && lastAnimation) {
  104059. mat = lastAnimation.getKeys()[j].value;
  104060. }
  104061. mat.decompose(scaling, rotationQuaternion, translation);
  104062. if (targetPath === "position") {
  104063. translation = value;
  104064. }
  104065. else if (targetPath === "rotationQuaternion") {
  104066. rotationQuaternion = value;
  104067. }
  104068. else {
  104069. scaling = value;
  104070. }
  104071. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  104072. }
  104073. if (!modifyKey) {
  104074. keys.push({
  104075. frame: bufferInput[j],
  104076. value: value
  104077. });
  104078. }
  104079. else if (lastAnimation) {
  104080. lastAnimation.getKeys()[j].value = value;
  104081. }
  104082. }
  104083. // Finish
  104084. if (!modifyKey && babylonAnimation) {
  104085. babylonAnimation.setKeys(keys);
  104086. targetNode.animations.push(babylonAnimation);
  104087. }
  104088. lastAnimation = babylonAnimation;
  104089. gltfRuntime.scene.stopAnimation(targetNode);
  104090. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  104091. }
  104092. }
  104093. };
  104094. /**
  104095. * Returns the bones transformation matrix
  104096. */
  104097. var configureBoneTransformation = function (node) {
  104098. var mat = null;
  104099. if (node.translation || node.rotation || node.scale) {
  104100. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  104101. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  104102. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  104103. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  104104. }
  104105. else {
  104106. mat = BABYLON.Matrix.FromArray(node.matrix);
  104107. }
  104108. return mat;
  104109. };
  104110. /**
  104111. * Returns the parent bone
  104112. */
  104113. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  104114. // Try to find
  104115. for (var i = 0; i < newSkeleton.bones.length; i++) {
  104116. if (newSkeleton.bones[i].name === jointName) {
  104117. return newSkeleton.bones[i];
  104118. }
  104119. }
  104120. // Not found, search in gltf nodes
  104121. var nodes = gltfRuntime.nodes;
  104122. for (var nde in nodes) {
  104123. var node = nodes[nde];
  104124. if (!node.jointName) {
  104125. continue;
  104126. }
  104127. var children = node.children;
  104128. for (var i = 0; i < children.length; i++) {
  104129. var child = gltfRuntime.nodes[children[i]];
  104130. if (!child.jointName) {
  104131. continue;
  104132. }
  104133. if (child.jointName === jointName) {
  104134. var mat = configureBoneTransformation(node);
  104135. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  104136. bone.id = nde;
  104137. return bone;
  104138. }
  104139. }
  104140. }
  104141. return null;
  104142. };
  104143. /**
  104144. * Returns the appropriate root node
  104145. */
  104146. var getNodeToRoot = function (nodesToRoot, id) {
  104147. for (var i = 0; i < nodesToRoot.length; i++) {
  104148. var nodeToRoot = nodesToRoot[i];
  104149. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  104150. var child = nodeToRoot.node.children[j];
  104151. if (child === id) {
  104152. return nodeToRoot.bone;
  104153. }
  104154. }
  104155. }
  104156. return null;
  104157. };
  104158. /**
  104159. * Returns the node with the joint name
  104160. */
  104161. var getJointNode = function (gltfRuntime, jointName) {
  104162. var nodes = gltfRuntime.nodes;
  104163. var node = nodes[jointName];
  104164. if (node) {
  104165. return {
  104166. node: node,
  104167. id: jointName
  104168. };
  104169. }
  104170. for (var nde in nodes) {
  104171. node = nodes[nde];
  104172. if (node.jointName === jointName) {
  104173. return {
  104174. node: node,
  104175. id: nde
  104176. };
  104177. }
  104178. }
  104179. return null;
  104180. };
  104181. /**
  104182. * Checks if a nodes is in joints
  104183. */
  104184. var nodeIsInJoints = function (skins, id) {
  104185. for (var i = 0; i < skins.jointNames.length; i++) {
  104186. if (skins.jointNames[i] === id) {
  104187. return true;
  104188. }
  104189. }
  104190. return false;
  104191. };
  104192. /**
  104193. * Fills the nodes to root for bones and builds hierarchy
  104194. */
  104195. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  104196. // Creates nodes for root
  104197. for (var nde in gltfRuntime.nodes) {
  104198. var node = gltfRuntime.nodes[nde];
  104199. var id = nde;
  104200. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  104201. continue;
  104202. }
  104203. // Create node to root bone
  104204. var mat = configureBoneTransformation(node);
  104205. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  104206. bone.id = id;
  104207. nodesToRoot.push({ bone: bone, node: node, id: id });
  104208. }
  104209. // Parenting
  104210. for (var i = 0; i < nodesToRoot.length; i++) {
  104211. var nodeToRoot = nodesToRoot[i];
  104212. var children = nodeToRoot.node.children;
  104213. for (var j = 0; j < children.length; j++) {
  104214. var child = null;
  104215. for (var k = 0; k < nodesToRoot.length; k++) {
  104216. if (nodesToRoot[k].id === children[j]) {
  104217. child = nodesToRoot[k];
  104218. break;
  104219. }
  104220. }
  104221. if (child) {
  104222. child.bone._parent = nodeToRoot.bone;
  104223. nodeToRoot.bone.children.push(child.bone);
  104224. }
  104225. }
  104226. }
  104227. };
  104228. /**
  104229. * Imports a skeleton
  104230. */
  104231. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  104232. if (!newSkeleton) {
  104233. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  104234. }
  104235. if (!skins.babylonSkeleton) {
  104236. return newSkeleton;
  104237. }
  104238. // Find the root bones
  104239. var nodesToRoot = [];
  104240. var nodesToRootToAdd = [];
  104241. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  104242. newSkeleton.bones = [];
  104243. // Joints
  104244. for (var i = 0; i < skins.jointNames.length; i++) {
  104245. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  104246. if (!jointNode) {
  104247. continue;
  104248. }
  104249. var node = jointNode.node;
  104250. if (!node) {
  104251. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  104252. continue;
  104253. }
  104254. var id = jointNode.id;
  104255. // Optimize, if the bone already exists...
  104256. var existingBone = gltfRuntime.scene.getBoneByID(id);
  104257. if (existingBone) {
  104258. newSkeleton.bones.push(existingBone);
  104259. continue;
  104260. }
  104261. // Search for parent bone
  104262. var foundBone = false;
  104263. var parentBone = null;
  104264. for (var j = 0; j < i; j++) {
  104265. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  104266. if (!jointNode_1) {
  104267. continue;
  104268. }
  104269. var joint = jointNode_1.node;
  104270. if (!joint) {
  104271. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  104272. continue;
  104273. }
  104274. var children = joint.children;
  104275. if (!children) {
  104276. continue;
  104277. }
  104278. foundBone = false;
  104279. for (var k = 0; k < children.length; k++) {
  104280. if (children[k] === id) {
  104281. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  104282. foundBone = true;
  104283. break;
  104284. }
  104285. }
  104286. if (foundBone) {
  104287. break;
  104288. }
  104289. }
  104290. // Create bone
  104291. var mat = configureBoneTransformation(node);
  104292. if (!parentBone && nodesToRoot.length > 0) {
  104293. parentBone = getNodeToRoot(nodesToRoot, id);
  104294. if (parentBone) {
  104295. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  104296. nodesToRootToAdd.push(parentBone);
  104297. }
  104298. }
  104299. }
  104300. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  104301. bone.id = id;
  104302. }
  104303. // Polish
  104304. var bones = newSkeleton.bones;
  104305. newSkeleton.bones = [];
  104306. for (var i = 0; i < skins.jointNames.length; i++) {
  104307. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  104308. if (!jointNode) {
  104309. continue;
  104310. }
  104311. for (var j = 0; j < bones.length; j++) {
  104312. if (bones[j].id === jointNode.id) {
  104313. newSkeleton.bones.push(bones[j]);
  104314. break;
  104315. }
  104316. }
  104317. }
  104318. newSkeleton.prepare();
  104319. // Finish
  104320. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  104321. newSkeleton.bones.push(nodesToRootToAdd[i]);
  104322. }
  104323. return newSkeleton;
  104324. };
  104325. /**
  104326. * Imports a mesh and its geometries
  104327. */
  104328. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  104329. if (!newMesh) {
  104330. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  104331. newMesh.id = id;
  104332. }
  104333. if (!node.babylonNode) {
  104334. return newMesh;
  104335. }
  104336. var subMaterials = [];
  104337. var vertexData = null;
  104338. var verticesStarts = new Array();
  104339. var verticesCounts = new Array();
  104340. var indexStarts = new Array();
  104341. var indexCounts = new Array();
  104342. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  104343. var meshID = meshes[meshIndex];
  104344. var mesh = gltfRuntime.meshes[meshID];
  104345. if (!mesh) {
  104346. continue;
  104347. }
  104348. // Positions, normals and UVs
  104349. for (var i = 0; i < mesh.primitives.length; i++) {
  104350. // Temporary vertex data
  104351. var tempVertexData = new BABYLON.VertexData();
  104352. var primitive = mesh.primitives[i];
  104353. if (primitive.mode !== 4) {
  104354. // continue;
  104355. }
  104356. var attributes = primitive.attributes;
  104357. var accessor = null;
  104358. var buffer = null;
  104359. // Set positions, normal and uvs
  104360. for (var semantic in attributes) {
  104361. // Link accessor and buffer view
  104362. accessor = gltfRuntime.accessors[attributes[semantic]];
  104363. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  104364. if (semantic === "NORMAL") {
  104365. tempVertexData.normals = new Float32Array(buffer.length);
  104366. tempVertexData.normals.set(buffer);
  104367. }
  104368. else if (semantic === "POSITION") {
  104369. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  104370. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  104371. for (var j = 0; j < buffer.length; j += 4) {
  104372. tempVertexData.positions[j] = buffer[j];
  104373. tempVertexData.positions[j + 1] = buffer[j + 1];
  104374. tempVertexData.positions[j + 2] = buffer[j + 2];
  104375. }
  104376. }
  104377. else {
  104378. tempVertexData.positions = new Float32Array(buffer.length);
  104379. tempVertexData.positions.set(buffer);
  104380. }
  104381. verticesCounts.push(tempVertexData.positions.length);
  104382. }
  104383. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  104384. var channel = Number(semantic.split("_")[1]);
  104385. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  104386. var uvs = new Float32Array(buffer.length);
  104387. uvs.set(buffer);
  104388. normalizeUVs(uvs);
  104389. tempVertexData.set(uvs, uvKind);
  104390. }
  104391. else if (semantic === "JOINT") {
  104392. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  104393. tempVertexData.matricesIndices.set(buffer);
  104394. }
  104395. else if (semantic === "WEIGHT") {
  104396. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  104397. tempVertexData.matricesWeights.set(buffer);
  104398. }
  104399. else if (semantic === "COLOR") {
  104400. tempVertexData.colors = new Float32Array(buffer.length);
  104401. tempVertexData.colors.set(buffer);
  104402. }
  104403. }
  104404. // Indices
  104405. accessor = gltfRuntime.accessors[primitive.indices];
  104406. if (accessor) {
  104407. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  104408. tempVertexData.indices = new Int32Array(buffer.length);
  104409. tempVertexData.indices.set(buffer);
  104410. indexCounts.push(tempVertexData.indices.length);
  104411. }
  104412. else {
  104413. // Set indices on the fly
  104414. var indices = [];
  104415. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  104416. indices.push(j);
  104417. }
  104418. tempVertexData.indices = new Int32Array(indices);
  104419. indexCounts.push(tempVertexData.indices.length);
  104420. }
  104421. if (!vertexData) {
  104422. vertexData = tempVertexData;
  104423. }
  104424. else {
  104425. vertexData.merge(tempVertexData);
  104426. }
  104427. // Sub material
  104428. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  104429. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  104430. // Update vertices start and index start
  104431. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  104432. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  104433. }
  104434. }
  104435. var material;
  104436. if (subMaterials.length > 1) {
  104437. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  104438. material.subMaterials = subMaterials;
  104439. }
  104440. else {
  104441. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  104442. }
  104443. if (subMaterials.length === 1) {
  104444. material = subMaterials[0];
  104445. }
  104446. if (!newMesh.material) {
  104447. newMesh.material = material;
  104448. }
  104449. // Apply geometry
  104450. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  104451. newMesh.computeWorldMatrix(true);
  104452. // Apply submeshes
  104453. newMesh.subMeshes = [];
  104454. var index = 0;
  104455. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  104456. var meshID = meshes[meshIndex];
  104457. var mesh = gltfRuntime.meshes[meshID];
  104458. if (!mesh) {
  104459. continue;
  104460. }
  104461. for (var i = 0; i < mesh.primitives.length; i++) {
  104462. if (mesh.primitives[i].mode !== 4) {
  104463. //continue;
  104464. }
  104465. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  104466. index++;
  104467. }
  104468. }
  104469. // Finish
  104470. return newMesh;
  104471. };
  104472. /**
  104473. * Configure node transformation from position, rotation and scaling
  104474. */
  104475. var configureNode = function (newNode, position, rotation, scaling) {
  104476. if (newNode.position) {
  104477. newNode.position = position;
  104478. }
  104479. if (newNode.rotationQuaternion || newNode.rotation) {
  104480. newNode.rotationQuaternion = rotation;
  104481. }
  104482. if (newNode.scaling) {
  104483. newNode.scaling = scaling;
  104484. }
  104485. };
  104486. /**
  104487. * Configures node from transformation matrix
  104488. */
  104489. var configureNodeFromMatrix = function (newNode, node, parent) {
  104490. if (node.matrix) {
  104491. var position = new BABYLON.Vector3(0, 0, 0);
  104492. var rotation = new BABYLON.Quaternion();
  104493. var scaling = new BABYLON.Vector3(0, 0, 0);
  104494. var mat = BABYLON.Matrix.FromArray(node.matrix);
  104495. mat.decompose(scaling, rotation, position);
  104496. configureNode(newNode, position, rotation, scaling);
  104497. }
  104498. else if (node.translation && node.rotation && node.scale) {
  104499. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  104500. }
  104501. newNode.computeWorldMatrix(true);
  104502. };
  104503. /**
  104504. * Imports a node
  104505. */
  104506. var importNode = function (gltfRuntime, node, id, parent) {
  104507. var lastNode = null;
  104508. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  104509. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  104510. return null;
  104511. }
  104512. }
  104513. // Meshes
  104514. if (node.skin) {
  104515. if (node.meshes) {
  104516. var skin = gltfRuntime.skins[node.skin];
  104517. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  104518. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  104519. if (newMesh.skeleton === null) {
  104520. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  104521. if (!skin.babylonSkeleton) {
  104522. skin.babylonSkeleton = newMesh.skeleton;
  104523. }
  104524. }
  104525. lastNode = newMesh;
  104526. }
  104527. }
  104528. else if (node.meshes) {
  104529. /**
  104530. * Improve meshes property
  104531. */
  104532. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  104533. lastNode = newMesh;
  104534. }
  104535. // Lights
  104536. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  104537. var light = gltfRuntime.lights[node.light];
  104538. if (light) {
  104539. if (light.type === "ambient") {
  104540. var ambienLight = light[light.type];
  104541. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104542. hemiLight.name = node.name || "";
  104543. if (ambienLight.color) {
  104544. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  104545. }
  104546. lastNode = hemiLight;
  104547. }
  104548. else if (light.type === "directional") {
  104549. var directionalLight = light[light.type];
  104550. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104551. dirLight.name = node.name || "";
  104552. if (directionalLight.color) {
  104553. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  104554. }
  104555. lastNode = dirLight;
  104556. }
  104557. else if (light.type === "point") {
  104558. var pointLight = light[light.type];
  104559. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104560. ptLight.name = node.name || "";
  104561. if (pointLight.color) {
  104562. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  104563. }
  104564. lastNode = ptLight;
  104565. }
  104566. else if (light.type === "spot") {
  104567. var spotLight = light[light.type];
  104568. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  104569. spLight.name = node.name || "";
  104570. if (spotLight.color) {
  104571. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  104572. }
  104573. if (spotLight.fallOfAngle) {
  104574. spLight.angle = spotLight.fallOfAngle;
  104575. }
  104576. if (spotLight.fallOffExponent) {
  104577. spLight.exponent = spotLight.fallOffExponent;
  104578. }
  104579. lastNode = spLight;
  104580. }
  104581. }
  104582. }
  104583. // Cameras
  104584. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  104585. var camera = gltfRuntime.cameras[node.camera];
  104586. if (camera) {
  104587. if (camera.type === "orthographic") {
  104588. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  104589. orthoCamera.name = node.name || "";
  104590. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  104591. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  104592. lastNode = orthoCamera;
  104593. }
  104594. else if (camera.type === "perspective") {
  104595. var perspectiveCamera = camera[camera.type];
  104596. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  104597. persCamera.name = node.name || "";
  104598. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  104599. if (!perspectiveCamera.aspectRatio) {
  104600. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  104601. }
  104602. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  104603. persCamera.maxZ = perspectiveCamera.zfar;
  104604. persCamera.minZ = perspectiveCamera.znear;
  104605. }
  104606. lastNode = persCamera;
  104607. }
  104608. }
  104609. }
  104610. // Empty node
  104611. if (!node.jointName) {
  104612. if (node.babylonNode) {
  104613. return node.babylonNode;
  104614. }
  104615. else if (lastNode === null) {
  104616. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  104617. node.babylonNode = dummy;
  104618. lastNode = dummy;
  104619. }
  104620. }
  104621. if (lastNode !== null) {
  104622. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  104623. configureNodeFromMatrix(lastNode, node, parent);
  104624. }
  104625. else {
  104626. var translation = node.translation || [0, 0, 0];
  104627. var rotation = node.rotation || [0, 0, 0, 1];
  104628. var scale = node.scale || [1, 1, 1];
  104629. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  104630. }
  104631. lastNode.updateCache(true);
  104632. node.babylonNode = lastNode;
  104633. }
  104634. return lastNode;
  104635. };
  104636. /**
  104637. * Traverses nodes and creates them
  104638. */
  104639. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  104640. if (meshIncluded === void 0) { meshIncluded = false; }
  104641. var node = gltfRuntime.nodes[id];
  104642. var newNode = null;
  104643. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  104644. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  104645. meshIncluded = true;
  104646. }
  104647. else {
  104648. meshIncluded = false;
  104649. }
  104650. }
  104651. else {
  104652. meshIncluded = true;
  104653. }
  104654. if (!node.jointName && meshIncluded) {
  104655. newNode = importNode(gltfRuntime, node, id, parent);
  104656. if (newNode !== null) {
  104657. newNode.id = id;
  104658. newNode.parent = parent;
  104659. }
  104660. }
  104661. if (node.children) {
  104662. for (var i = 0; i < node.children.length; i++) {
  104663. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  104664. }
  104665. }
  104666. };
  104667. /**
  104668. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  104669. */
  104670. var postLoad = function (gltfRuntime) {
  104671. // Nodes
  104672. var currentScene = gltfRuntime.currentScene;
  104673. if (currentScene) {
  104674. for (var i = 0; i < currentScene.nodes.length; i++) {
  104675. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104676. }
  104677. }
  104678. else {
  104679. for (var thing in gltfRuntime.scenes) {
  104680. currentScene = gltfRuntime.scenes[thing];
  104681. for (var i = 0; i < currentScene.nodes.length; i++) {
  104682. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104683. }
  104684. }
  104685. }
  104686. // Set animations
  104687. loadAnimations(gltfRuntime);
  104688. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  104689. var skeleton = gltfRuntime.scene.skeletons[i];
  104690. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  104691. }
  104692. };
  104693. /**
  104694. * onBind shaderrs callback to set uniforms and matrices
  104695. */
  104696. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  104697. var materialValues = material.values || technique.parameters;
  104698. for (var unif in unTreatedUniforms) {
  104699. var uniform = unTreatedUniforms[unif];
  104700. var type = uniform.type;
  104701. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  104702. if (uniform.semantic && !uniform.source && !uniform.node) {
  104703. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  104704. }
  104705. else if (uniform.semantic && (uniform.source || uniform.node)) {
  104706. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  104707. if (source === null) {
  104708. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  104709. }
  104710. if (source === null) {
  104711. continue;
  104712. }
  104713. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  104714. }
  104715. }
  104716. else {
  104717. var value = materialValues[technique.uniforms[unif]];
  104718. if (!value) {
  104719. continue;
  104720. }
  104721. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  104722. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  104723. if (texture === null || texture === undefined) {
  104724. continue;
  104725. }
  104726. shaderMaterial.getEffect().setTexture(unif, texture);
  104727. }
  104728. else {
  104729. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  104730. }
  104731. }
  104732. }
  104733. onSuccess(shaderMaterial);
  104734. };
  104735. /**
  104736. * Prepare uniforms to send the only one time
  104737. * Loads the appropriate textures
  104738. */
  104739. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  104740. var materialValues = material.values || technique.parameters;
  104741. var techniqueUniforms = technique.uniforms;
  104742. /**
  104743. * Prepare values here (not matrices)
  104744. */
  104745. for (var unif in unTreatedUniforms) {
  104746. var uniform = unTreatedUniforms[unif];
  104747. var type = uniform.type;
  104748. var value = materialValues[techniqueUniforms[unif]];
  104749. if (value === undefined) {
  104750. // In case the value is the same for all materials
  104751. value = uniform.value;
  104752. }
  104753. if (!value) {
  104754. continue;
  104755. }
  104756. var onLoadTexture = function (uniformName) {
  104757. return function (texture) {
  104758. if (uniform.value && uniformName) {
  104759. // Static uniform
  104760. shaderMaterial.setTexture(uniformName, texture);
  104761. delete unTreatedUniforms[uniformName];
  104762. }
  104763. };
  104764. };
  104765. // Texture (sampler2D)
  104766. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  104767. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  104768. }
  104769. // Others
  104770. else {
  104771. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  104772. // Static uniform
  104773. delete unTreatedUniforms[unif];
  104774. }
  104775. }
  104776. }
  104777. };
  104778. /**
  104779. * Shader compilation failed
  104780. */
  104781. var onShaderCompileError = function (program, shaderMaterial, onError) {
  104782. return function (effect, error) {
  104783. shaderMaterial.dispose(true);
  104784. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  104785. };
  104786. };
  104787. /**
  104788. * Shader compilation success
  104789. */
  104790. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  104791. return function (_) {
  104792. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  104793. shaderMaterial.onBind = function (mesh) {
  104794. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  104795. };
  104796. };
  104797. };
  104798. /**
  104799. * Returns the appropriate uniform if already handled by babylon
  104800. */
  104801. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  104802. for (var unif in technique.uniforms) {
  104803. var uniform = technique.uniforms[unif];
  104804. var uniformParameter = technique.parameters[uniform];
  104805. if (tokenizer.currentIdentifier === unif) {
  104806. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  104807. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  104808. if (transformIndex !== -1) {
  104809. delete unTreatedUniforms[unif];
  104810. return babylonTransforms[transformIndex];
  104811. }
  104812. }
  104813. }
  104814. }
  104815. return tokenizer.currentIdentifier;
  104816. };
  104817. /**
  104818. * All shaders loaded. Create materials one by one
  104819. */
  104820. var importMaterials = function (gltfRuntime) {
  104821. // Create materials
  104822. for (var mat in gltfRuntime.materials) {
  104823. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  104824. }
  104825. };
  104826. /**
  104827. * Implementation of the base glTF spec
  104828. */
  104829. var GLTFLoaderBase = /** @class */ (function () {
  104830. function GLTFLoaderBase() {
  104831. }
  104832. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  104833. var gltfRuntime = {
  104834. extensions: {},
  104835. accessors: {},
  104836. buffers: {},
  104837. bufferViews: {},
  104838. meshes: {},
  104839. lights: {},
  104840. cameras: {},
  104841. nodes: {},
  104842. images: {},
  104843. textures: {},
  104844. shaders: {},
  104845. programs: {},
  104846. samplers: {},
  104847. techniques: {},
  104848. materials: {},
  104849. animations: {},
  104850. skins: {},
  104851. extensionsUsed: [],
  104852. scenes: {},
  104853. buffersCount: 0,
  104854. shaderscount: 0,
  104855. scene: scene,
  104856. rootUrl: rootUrl,
  104857. loadedBufferCount: 0,
  104858. loadedBufferViews: {},
  104859. loadedShaderCount: 0,
  104860. importOnlyMeshes: false,
  104861. dummyNodes: []
  104862. };
  104863. // Parse
  104864. if (parsedData.extensions) {
  104865. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  104866. }
  104867. if (parsedData.extensionsUsed) {
  104868. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  104869. }
  104870. if (parsedData.buffers) {
  104871. parseBuffers(parsedData.buffers, gltfRuntime);
  104872. }
  104873. if (parsedData.bufferViews) {
  104874. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  104875. }
  104876. if (parsedData.accessors) {
  104877. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  104878. }
  104879. if (parsedData.meshes) {
  104880. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  104881. }
  104882. if (parsedData.lights) {
  104883. parseObject(parsedData.lights, "lights", gltfRuntime);
  104884. }
  104885. if (parsedData.cameras) {
  104886. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  104887. }
  104888. if (parsedData.nodes) {
  104889. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  104890. }
  104891. if (parsedData.images) {
  104892. parseObject(parsedData.images, "images", gltfRuntime);
  104893. }
  104894. if (parsedData.textures) {
  104895. parseObject(parsedData.textures, "textures", gltfRuntime);
  104896. }
  104897. if (parsedData.shaders) {
  104898. parseShaders(parsedData.shaders, gltfRuntime);
  104899. }
  104900. if (parsedData.programs) {
  104901. parseObject(parsedData.programs, "programs", gltfRuntime);
  104902. }
  104903. if (parsedData.samplers) {
  104904. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  104905. }
  104906. if (parsedData.techniques) {
  104907. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  104908. }
  104909. if (parsedData.materials) {
  104910. parseObject(parsedData.materials, "materials", gltfRuntime);
  104911. }
  104912. if (parsedData.animations) {
  104913. parseObject(parsedData.animations, "animations", gltfRuntime);
  104914. }
  104915. if (parsedData.skins) {
  104916. parseObject(parsedData.skins, "skins", gltfRuntime);
  104917. }
  104918. if (parsedData.scenes) {
  104919. gltfRuntime.scenes = parsedData.scenes;
  104920. }
  104921. if (parsedData.scene && parsedData.scenes) {
  104922. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  104923. }
  104924. return gltfRuntime;
  104925. };
  104926. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104927. var buffer = gltfRuntime.buffers[id];
  104928. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  104929. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  104930. }
  104931. else {
  104932. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  104933. if (request) {
  104934. onError(request.status + " " + request.statusText);
  104935. }
  104936. });
  104937. }
  104938. };
  104939. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104940. var texture = gltfRuntime.textures[id];
  104941. if (!texture || !texture.source) {
  104942. onError("");
  104943. return;
  104944. }
  104945. if (texture.babylonTexture) {
  104946. onSuccess(null);
  104947. return;
  104948. }
  104949. var source = gltfRuntime.images[texture.source];
  104950. if (BABYLON.Tools.IsBase64(source.uri)) {
  104951. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  104952. }
  104953. else {
  104954. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  104955. if (request) {
  104956. onError(request.status + " " + request.statusText);
  104957. }
  104958. });
  104959. }
  104960. };
  104961. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104962. var texture = gltfRuntime.textures[id];
  104963. if (texture.babylonTexture) {
  104964. onSuccess(texture.babylonTexture);
  104965. return;
  104966. }
  104967. var sampler = gltfRuntime.samplers[texture.sampler];
  104968. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  104969. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  104970. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  104971. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  104972. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104973. var blob = new Blob([buffer]);
  104974. var blobURL = URL.createObjectURL(blob);
  104975. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  104976. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  104977. if (sampler.wrapS !== undefined) {
  104978. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  104979. }
  104980. if (sampler.wrapT !== undefined) {
  104981. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  104982. }
  104983. newTexture.name = id;
  104984. texture.babylonTexture = newTexture;
  104985. onSuccess(newTexture);
  104986. };
  104987. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104988. var shader = gltfRuntime.shaders[id];
  104989. if (BABYLON.Tools.IsBase64(shader.uri)) {
  104990. var shaderString = atob(shader.uri.split(",")[1]);
  104991. if (onSuccess) {
  104992. onSuccess(shaderString);
  104993. }
  104994. }
  104995. else {
  104996. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  104997. if (request && onError) {
  104998. onError(request.status + " " + request.statusText);
  104999. }
  105000. });
  105001. }
  105002. };
  105003. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105004. var material = gltfRuntime.materials[id];
  105005. if (!material.technique) {
  105006. if (onError) {
  105007. onError("No technique found.");
  105008. }
  105009. return;
  105010. }
  105011. var technique = gltfRuntime.techniques[material.technique];
  105012. if (!technique) {
  105013. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  105014. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  105015. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105016. onSuccess(defaultMaterial);
  105017. return;
  105018. }
  105019. var program = gltfRuntime.programs[technique.program];
  105020. var states = technique.states;
  105021. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  105022. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  105023. var newVertexShader = "";
  105024. var newPixelShader = "";
  105025. var vertexTokenizer = new Tokenizer(vertexShader);
  105026. var pixelTokenizer = new Tokenizer(pixelShader);
  105027. var unTreatedUniforms = {};
  105028. var uniforms = [];
  105029. var attributes = [];
  105030. var samplers = [];
  105031. // Fill uniform, sampler2D and attributes
  105032. for (var unif in technique.uniforms) {
  105033. var uniform = technique.uniforms[unif];
  105034. var uniformParameter = technique.parameters[uniform];
  105035. unTreatedUniforms[unif] = uniformParameter;
  105036. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  105037. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  105038. if (transformIndex !== -1) {
  105039. uniforms.push(babylonTransforms[transformIndex]);
  105040. delete unTreatedUniforms[unif];
  105041. }
  105042. else {
  105043. uniforms.push(unif);
  105044. }
  105045. }
  105046. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  105047. samplers.push(unif);
  105048. }
  105049. else {
  105050. uniforms.push(unif);
  105051. }
  105052. }
  105053. for (var attr in technique.attributes) {
  105054. var attribute = technique.attributes[attr];
  105055. var attributeParameter = technique.parameters[attribute];
  105056. if (attributeParameter.semantic) {
  105057. attributes.push(getAttribute(attributeParameter));
  105058. }
  105059. }
  105060. // Configure vertex shader
  105061. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  105062. var tokenType = vertexTokenizer.currentToken;
  105063. if (tokenType !== ETokenType.IDENTIFIER) {
  105064. newVertexShader += vertexTokenizer.currentString;
  105065. continue;
  105066. }
  105067. var foundAttribute = false;
  105068. for (var attr in technique.attributes) {
  105069. var attribute = technique.attributes[attr];
  105070. var attributeParameter = technique.parameters[attribute];
  105071. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  105072. newVertexShader += getAttribute(attributeParameter);
  105073. foundAttribute = true;
  105074. break;
  105075. }
  105076. }
  105077. if (foundAttribute) {
  105078. continue;
  105079. }
  105080. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  105081. }
  105082. // Configure pixel shader
  105083. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  105084. var tokenType = pixelTokenizer.currentToken;
  105085. if (tokenType !== ETokenType.IDENTIFIER) {
  105086. newPixelShader += pixelTokenizer.currentString;
  105087. continue;
  105088. }
  105089. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  105090. }
  105091. // Create shader material
  105092. var shaderPath = {
  105093. vertex: program.vertexShader + id,
  105094. fragment: program.fragmentShader + id
  105095. };
  105096. var options = {
  105097. attributes: attributes,
  105098. uniforms: uniforms,
  105099. samplers: samplers,
  105100. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  105101. };
  105102. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  105103. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  105104. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  105105. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  105106. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  105107. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105108. if (states && states.functions) {
  105109. var functions = states.functions;
  105110. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  105111. shaderMaterial.backFaceCulling = false;
  105112. }
  105113. var blendFunc = functions.blendFuncSeparate;
  105114. if (blendFunc) {
  105115. 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) {
  105116. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  105117. }
  105118. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  105119. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  105120. }
  105121. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  105122. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  105123. }
  105124. 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) {
  105125. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  105126. }
  105127. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  105128. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  105129. }
  105130. 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) {
  105131. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  105132. }
  105133. }
  105134. }
  105135. };
  105136. return GLTFLoaderBase;
  105137. }());
  105138. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  105139. /**
  105140. * glTF V1 Loader
  105141. */
  105142. var GLTFLoader = /** @class */ (function () {
  105143. function GLTFLoader() {
  105144. // #region Stubs for IGLTFLoader interface
  105145. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  105146. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  105147. this.compileMaterials = false;
  105148. this.useClipPlane = false;
  105149. this.compileShadowGenerators = false;
  105150. this.transparencyAsCoverage = false;
  105151. this._normalizeAnimationGroupsToBeginAtZero = true;
  105152. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  105153. this.onMeshLoadedObservable = new BABYLON.Observable();
  105154. this.onTextureLoadedObservable = new BABYLON.Observable();
  105155. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105156. this.onCameraLoadedObservable = new BABYLON.Observable();
  105157. this.onCompleteObservable = new BABYLON.Observable();
  105158. this.onDisposeObservable = new BABYLON.Observable();
  105159. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105160. this.state = null;
  105161. }
  105162. GLTFLoader.RegisterExtension = function (extension) {
  105163. if (GLTFLoader.Extensions[extension.name]) {
  105164. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  105165. return;
  105166. }
  105167. GLTFLoader.Extensions[extension.name] = extension;
  105168. };
  105169. GLTFLoader.prototype.dispose = function () { };
  105170. // #endregion
  105171. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  105172. var _this = this;
  105173. scene.useRightHandedSystem = true;
  105174. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  105175. gltfRuntime.importOnlyMeshes = true;
  105176. if (meshesNames === "") {
  105177. gltfRuntime.importMeshesNames = [];
  105178. }
  105179. else if (typeof meshesNames === "string") {
  105180. gltfRuntime.importMeshesNames = [meshesNames];
  105181. }
  105182. else if (meshesNames && !(meshesNames instanceof Array)) {
  105183. gltfRuntime.importMeshesNames = [meshesNames];
  105184. }
  105185. else {
  105186. gltfRuntime.importMeshesNames = [];
  105187. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  105188. }
  105189. // Create nodes
  105190. _this._createNodes(gltfRuntime);
  105191. var meshes = new Array();
  105192. var skeletons = new Array();
  105193. // Fill arrays of meshes and skeletons
  105194. for (var nde in gltfRuntime.nodes) {
  105195. var node = gltfRuntime.nodes[nde];
  105196. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  105197. meshes.push(node.babylonNode);
  105198. }
  105199. }
  105200. for (var skl in gltfRuntime.skins) {
  105201. var skin = gltfRuntime.skins[skl];
  105202. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  105203. skeletons.push(skin.babylonSkeleton);
  105204. }
  105205. }
  105206. // Load buffers, shaders, materials, etc.
  105207. _this._loadBuffersAsync(gltfRuntime, function () {
  105208. _this._loadShadersAsync(gltfRuntime, function () {
  105209. importMaterials(gltfRuntime);
  105210. postLoad(gltfRuntime);
  105211. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  105212. onSuccess(meshes, skeletons);
  105213. }
  105214. });
  105215. }, onProgress);
  105216. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  105217. onSuccess(meshes, skeletons);
  105218. }
  105219. }, onError);
  105220. return true;
  105221. };
  105222. /**
  105223. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  105224. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  105225. * @param scene the scene the meshes should be added to
  105226. * @param data gltf data containing information of the meshes in a loaded file
  105227. * @param rootUrl root url to load from
  105228. * @param onProgress event that fires when loading progress has occured
  105229. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  105230. */
  105231. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105232. var _this = this;
  105233. return new Promise(function (resolve, reject) {
  105234. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  105235. resolve({
  105236. meshes: meshes,
  105237. particleSystems: [],
  105238. skeletons: skeletons,
  105239. animationGroups: []
  105240. });
  105241. }, onProgress, function (message) {
  105242. reject(new Error(message));
  105243. });
  105244. });
  105245. };
  105246. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  105247. var _this = this;
  105248. scene.useRightHandedSystem = true;
  105249. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  105250. // Load runtime extensios
  105251. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  105252. // Create nodes
  105253. _this._createNodes(gltfRuntime);
  105254. // Load buffers, shaders, materials, etc.
  105255. _this._loadBuffersAsync(gltfRuntime, function () {
  105256. _this._loadShadersAsync(gltfRuntime, function () {
  105257. importMaterials(gltfRuntime);
  105258. postLoad(gltfRuntime);
  105259. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  105260. onSuccess();
  105261. }
  105262. });
  105263. });
  105264. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  105265. onSuccess();
  105266. }
  105267. }, onError);
  105268. }, onError);
  105269. };
  105270. /**
  105271. * Imports all objects from a loaded gltf file and adds them to the scene
  105272. * @param scene the scene the objects should be added to
  105273. * @param data gltf data containing information of the meshes in a loaded file
  105274. * @param rootUrl root url to load from
  105275. * @param onProgress event that fires when loading progress has occured
  105276. * @returns a promise which completes when objects have been loaded to the scene
  105277. */
  105278. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105279. var _this = this;
  105280. return new Promise(function (resolve, reject) {
  105281. _this._loadAsync(scene, data, rootUrl, function () {
  105282. resolve();
  105283. }, onProgress, function (message) {
  105284. reject(new Error(message));
  105285. });
  105286. });
  105287. };
  105288. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  105289. var hasShaders = false;
  105290. var processShader = function (sha, shader) {
  105291. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  105292. if (shaderString instanceof ArrayBuffer) {
  105293. return;
  105294. }
  105295. gltfRuntime.loadedShaderCount++;
  105296. if (shaderString) {
  105297. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  105298. }
  105299. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  105300. onload();
  105301. }
  105302. }, function () {
  105303. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  105304. });
  105305. };
  105306. for (var sha in gltfRuntime.shaders) {
  105307. hasShaders = true;
  105308. var shader = gltfRuntime.shaders[sha];
  105309. if (shader) {
  105310. processShader.bind(this, sha, shader)();
  105311. }
  105312. else {
  105313. BABYLON.Tools.Error("No shader named: " + sha);
  105314. }
  105315. }
  105316. if (!hasShaders) {
  105317. onload();
  105318. }
  105319. };
  105320. ;
  105321. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  105322. var hasBuffers = false;
  105323. var processBuffer = function (buf, buffer) {
  105324. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  105325. gltfRuntime.loadedBufferCount++;
  105326. if (bufferView) {
  105327. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  105328. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  105329. }
  105330. gltfRuntime.loadedBufferViews[buf] = bufferView;
  105331. }
  105332. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  105333. onLoad();
  105334. }
  105335. }, function () {
  105336. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  105337. });
  105338. };
  105339. for (var buf in gltfRuntime.buffers) {
  105340. hasBuffers = true;
  105341. var buffer = gltfRuntime.buffers[buf];
  105342. if (buffer) {
  105343. processBuffer.bind(this, buf, buffer)();
  105344. }
  105345. else {
  105346. BABYLON.Tools.Error("No buffer named: " + buf);
  105347. }
  105348. }
  105349. if (!hasBuffers) {
  105350. onLoad();
  105351. }
  105352. };
  105353. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  105354. var currentScene = gltfRuntime.currentScene;
  105355. if (currentScene) {
  105356. // Only one scene even if multiple scenes are defined
  105357. for (var i = 0; i < currentScene.nodes.length; i++) {
  105358. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105359. }
  105360. }
  105361. else {
  105362. // Load all scenes
  105363. for (var thing in gltfRuntime.scenes) {
  105364. currentScene = gltfRuntime.scenes[thing];
  105365. for (var i = 0; i < currentScene.nodes.length; i++) {
  105366. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105367. }
  105368. }
  105369. }
  105370. };
  105371. GLTFLoader.Extensions = {};
  105372. return GLTFLoader;
  105373. }());
  105374. GLTF1.GLTFLoader = GLTFLoader;
  105375. ;
  105376. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  105377. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105378. })(BABYLON || (BABYLON = {}));
  105379. //# sourceMappingURL=babylon.glTFLoader.js.map
  105380. var BABYLON;
  105381. (function (BABYLON) {
  105382. var GLTF1;
  105383. (function (GLTF1) {
  105384. /**
  105385. * Utils functions for GLTF
  105386. */
  105387. var GLTFUtils = /** @class */ (function () {
  105388. function GLTFUtils() {
  105389. }
  105390. /**
  105391. * Sets the given "parameter" matrix
  105392. * @param scene: the {BABYLON.Scene} object
  105393. * @param source: the source node where to pick the matrix
  105394. * @param parameter: the GLTF technique parameter
  105395. * @param uniformName: the name of the shader's uniform
  105396. * @param shaderMaterial: the shader material
  105397. */
  105398. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  105399. var mat = null;
  105400. if (parameter.semantic === "MODEL") {
  105401. mat = source.getWorldMatrix();
  105402. }
  105403. else if (parameter.semantic === "PROJECTION") {
  105404. mat = scene.getProjectionMatrix();
  105405. }
  105406. else if (parameter.semantic === "VIEW") {
  105407. mat = scene.getViewMatrix();
  105408. }
  105409. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  105410. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  105411. }
  105412. else if (parameter.semantic === "MODELVIEW") {
  105413. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  105414. }
  105415. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  105416. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  105417. }
  105418. else if (parameter.semantic === "MODELINVERSE") {
  105419. mat = source.getWorldMatrix().invert();
  105420. }
  105421. else if (parameter.semantic === "VIEWINVERSE") {
  105422. mat = scene.getViewMatrix().invert();
  105423. }
  105424. else if (parameter.semantic === "PROJECTIONINVERSE") {
  105425. mat = scene.getProjectionMatrix().invert();
  105426. }
  105427. else if (parameter.semantic === "MODELVIEWINVERSE") {
  105428. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  105429. }
  105430. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  105431. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  105432. }
  105433. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  105434. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  105435. }
  105436. else {
  105437. debugger;
  105438. }
  105439. if (mat) {
  105440. switch (parameter.type) {
  105441. case GLTF1.EParameterType.FLOAT_MAT2:
  105442. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  105443. break;
  105444. case GLTF1.EParameterType.FLOAT_MAT3:
  105445. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  105446. break;
  105447. case GLTF1.EParameterType.FLOAT_MAT4:
  105448. shaderMaterial.setMatrix(uniformName, mat);
  105449. break;
  105450. default: break;
  105451. }
  105452. }
  105453. };
  105454. /**
  105455. * Sets the given "parameter" matrix
  105456. * @param shaderMaterial: the shader material
  105457. * @param uniform: the name of the shader's uniform
  105458. * @param value: the value of the uniform
  105459. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  105460. */
  105461. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  105462. switch (type) {
  105463. case GLTF1.EParameterType.FLOAT:
  105464. shaderMaterial.setFloat(uniform, value);
  105465. return true;
  105466. case GLTF1.EParameterType.FLOAT_VEC2:
  105467. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  105468. return true;
  105469. case GLTF1.EParameterType.FLOAT_VEC3:
  105470. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  105471. return true;
  105472. case GLTF1.EParameterType.FLOAT_VEC4:
  105473. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  105474. return true;
  105475. default: return false;
  105476. }
  105477. };
  105478. /**
  105479. * Returns the wrap mode of the texture
  105480. * @param mode: the mode value
  105481. */
  105482. GLTFUtils.GetWrapMode = function (mode) {
  105483. switch (mode) {
  105484. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105485. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105486. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105487. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105488. }
  105489. };
  105490. /**
  105491. * Returns the byte stride giving an accessor
  105492. * @param accessor: the GLTF accessor objet
  105493. */
  105494. GLTFUtils.GetByteStrideFromType = function (accessor) {
  105495. // Needs this function since "byteStride" isn't requiered in glTF format
  105496. var type = accessor.type;
  105497. switch (type) {
  105498. case "VEC2": return 2;
  105499. case "VEC3": return 3;
  105500. case "VEC4": return 4;
  105501. case "MAT2": return 4;
  105502. case "MAT3": return 9;
  105503. case "MAT4": return 16;
  105504. default: return 1;
  105505. }
  105506. };
  105507. /**
  105508. * Returns the texture filter mode giving a mode value
  105509. * @param mode: the filter mode value
  105510. */
  105511. GLTFUtils.GetTextureFilterMode = function (mode) {
  105512. switch (mode) {
  105513. case GLTF1.ETextureFilterType.LINEAR:
  105514. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  105515. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105516. case GLTF1.ETextureFilterType.NEAREST:
  105517. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  105518. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  105519. }
  105520. };
  105521. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  105522. var byteOffset = bufferView.byteOffset + byteOffset;
  105523. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  105524. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  105525. throw new Error("Buffer access is out of range");
  105526. }
  105527. var buffer = loadedBufferView.buffer;
  105528. byteOffset += loadedBufferView.byteOffset;
  105529. switch (componentType) {
  105530. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  105531. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  105532. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  105533. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  105534. default: return new Float32Array(buffer, byteOffset, byteLength);
  105535. }
  105536. };
  105537. /**
  105538. * Returns a buffer from its accessor
  105539. * @param gltfRuntime: the GLTF runtime
  105540. * @param accessor: the GLTF accessor
  105541. */
  105542. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  105543. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  105544. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  105545. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  105546. };
  105547. /**
  105548. * Decodes a buffer view into a string
  105549. * @param view: the buffer view
  105550. */
  105551. GLTFUtils.DecodeBufferToText = function (view) {
  105552. var result = "";
  105553. var length = view.byteLength;
  105554. for (var i = 0; i < length; ++i) {
  105555. result += String.fromCharCode(view[i]);
  105556. }
  105557. return result;
  105558. };
  105559. /**
  105560. * Returns the default material of gltf. Related to
  105561. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  105562. * @param scene: the Babylon.js scene
  105563. */
  105564. GLTFUtils.GetDefaultMaterial = function (scene) {
  105565. if (!GLTFUtils._DefaultMaterial) {
  105566. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  105567. "precision highp float;",
  105568. "",
  105569. "uniform mat4 worldView;",
  105570. "uniform mat4 projection;",
  105571. "",
  105572. "attribute vec3 position;",
  105573. "",
  105574. "void main(void)",
  105575. "{",
  105576. " gl_Position = projection * worldView * vec4(position, 1.0);",
  105577. "}"
  105578. ].join("\n");
  105579. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  105580. "precision highp float;",
  105581. "",
  105582. "uniform vec4 u_emission;",
  105583. "",
  105584. "void main(void)",
  105585. "{",
  105586. " gl_FragColor = u_emission;",
  105587. "}"
  105588. ].join("\n");
  105589. var shaderPath = {
  105590. vertex: "GLTFDefaultMaterial",
  105591. fragment: "GLTFDefaultMaterial"
  105592. };
  105593. var options = {
  105594. attributes: ["position"],
  105595. uniforms: ["worldView", "projection", "u_emission"],
  105596. samplers: new Array(),
  105597. needAlphaBlending: false
  105598. };
  105599. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  105600. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  105601. }
  105602. return GLTFUtils._DefaultMaterial;
  105603. };
  105604. // The GLTF default material
  105605. GLTFUtils._DefaultMaterial = null;
  105606. return GLTFUtils;
  105607. }());
  105608. GLTF1.GLTFUtils = GLTFUtils;
  105609. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105610. })(BABYLON || (BABYLON = {}));
  105611. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  105612. var BABYLON;
  105613. (function (BABYLON) {
  105614. var GLTF1;
  105615. (function (GLTF1) {
  105616. var GLTFLoaderExtension = /** @class */ (function () {
  105617. function GLTFLoaderExtension(name) {
  105618. this._name = name;
  105619. }
  105620. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  105621. get: function () {
  105622. return this._name;
  105623. },
  105624. enumerable: true,
  105625. configurable: true
  105626. });
  105627. /**
  105628. * Defines an override for loading the runtime
  105629. * Return true to stop further extensions from loading the runtime
  105630. */
  105631. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105632. return false;
  105633. };
  105634. /**
  105635. * Defines an onverride for creating gltf runtime
  105636. * Return true to stop further extensions from creating the runtime
  105637. */
  105638. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105639. return false;
  105640. };
  105641. /**
  105642. * Defines an override for loading buffers
  105643. * Return true to stop further extensions from loading this buffer
  105644. */
  105645. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105646. return false;
  105647. };
  105648. /**
  105649. * Defines an override for loading texture buffers
  105650. * Return true to stop further extensions from loading this texture data
  105651. */
  105652. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105653. return false;
  105654. };
  105655. /**
  105656. * Defines an override for creating textures
  105657. * Return true to stop further extensions from loading this texture
  105658. */
  105659. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105660. return false;
  105661. };
  105662. /**
  105663. * Defines an override for loading shader strings
  105664. * Return true to stop further extensions from loading this shader data
  105665. */
  105666. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105667. return false;
  105668. };
  105669. /**
  105670. * Defines an override for loading materials
  105671. * Return true to stop further extensions from loading this material
  105672. */
  105673. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105674. return false;
  105675. };
  105676. // ---------
  105677. // Utilities
  105678. // ---------
  105679. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105680. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105681. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  105682. }, function () {
  105683. setTimeout(function () {
  105684. if (!onSuccess) {
  105685. return;
  105686. }
  105687. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  105688. });
  105689. });
  105690. };
  105691. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105692. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105693. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  105694. }, function () {
  105695. setTimeout(function () {
  105696. onSuccess();
  105697. });
  105698. });
  105699. };
  105700. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105701. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105702. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  105703. }, function () {
  105704. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  105705. });
  105706. };
  105707. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  105708. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  105709. if (buffer) {
  105710. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105711. }
  105712. }, onError);
  105713. };
  105714. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105715. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105716. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  105717. }, function () {
  105718. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  105719. });
  105720. };
  105721. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105722. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105723. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  105724. }, function () {
  105725. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  105726. });
  105727. };
  105728. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105729. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105730. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  105731. }, function () {
  105732. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  105733. });
  105734. };
  105735. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105736. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105737. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105738. }, function () {
  105739. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105740. });
  105741. };
  105742. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  105743. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  105744. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  105745. if (func(loaderExtension)) {
  105746. return;
  105747. }
  105748. }
  105749. defaultFunc();
  105750. };
  105751. return GLTFLoaderExtension;
  105752. }());
  105753. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  105754. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105755. })(BABYLON || (BABYLON = {}));
  105756. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105757. var BABYLON;
  105758. (function (BABYLON) {
  105759. var GLTF1;
  105760. (function (GLTF1) {
  105761. var BinaryExtensionBufferName = "binary_glTF";
  105762. ;
  105763. ;
  105764. var GLTFBinaryExtension = /** @class */ (function (_super) {
  105765. __extends(GLTFBinaryExtension, _super);
  105766. function GLTFBinaryExtension() {
  105767. return _super.call(this, "KHR_binary_glTF") || this;
  105768. }
  105769. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105770. var extensionsUsed = data.json.extensionsUsed;
  105771. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  105772. return false;
  105773. }
  105774. this._bin = data.bin;
  105775. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  105776. return true;
  105777. };
  105778. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105779. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  105780. return false;
  105781. }
  105782. if (id !== BinaryExtensionBufferName) {
  105783. return false;
  105784. }
  105785. onSuccess(this._bin);
  105786. return true;
  105787. };
  105788. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105789. var texture = gltfRuntime.textures[id];
  105790. var source = gltfRuntime.images[texture.source];
  105791. if (!source.extensions || !(this.name in source.extensions)) {
  105792. return false;
  105793. }
  105794. var sourceExt = source.extensions[this.name];
  105795. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  105796. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  105797. onSuccess(buffer);
  105798. return true;
  105799. };
  105800. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105801. var shader = gltfRuntime.shaders[id];
  105802. if (!shader.extensions || !(this.name in shader.extensions)) {
  105803. return false;
  105804. }
  105805. var binaryExtensionShader = shader.extensions[this.name];
  105806. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  105807. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  105808. setTimeout(function () {
  105809. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  105810. onSuccess(shaderString);
  105811. });
  105812. return true;
  105813. };
  105814. return GLTFBinaryExtension;
  105815. }(GLTF1.GLTFLoaderExtension));
  105816. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  105817. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  105818. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105819. })(BABYLON || (BABYLON = {}));
  105820. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  105821. var BABYLON;
  105822. (function (BABYLON) {
  105823. var GLTF1;
  105824. (function (GLTF1) {
  105825. ;
  105826. ;
  105827. ;
  105828. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  105829. __extends(GLTFMaterialsCommonExtension, _super);
  105830. function GLTFMaterialsCommonExtension() {
  105831. return _super.call(this, "KHR_materials_common") || this;
  105832. }
  105833. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105834. if (!gltfRuntime.extensions)
  105835. return false;
  105836. var extension = gltfRuntime.extensions[this.name];
  105837. if (!extension)
  105838. return false;
  105839. // Create lights
  105840. var lights = extension.lights;
  105841. if (lights) {
  105842. for (var thing in lights) {
  105843. var light = lights[thing];
  105844. switch (light.type) {
  105845. case "ambient":
  105846. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  105847. var ambient = light.ambient;
  105848. if (ambient) {
  105849. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  105850. }
  105851. break;
  105852. case "point":
  105853. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  105854. var point = light.point;
  105855. if (point) {
  105856. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  105857. }
  105858. break;
  105859. case "directional":
  105860. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  105861. var directional = light.directional;
  105862. if (directional) {
  105863. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  105864. }
  105865. break;
  105866. case "spot":
  105867. var spot = light.spot;
  105868. if (spot) {
  105869. 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);
  105870. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  105871. }
  105872. break;
  105873. default:
  105874. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  105875. break;
  105876. }
  105877. }
  105878. }
  105879. return false;
  105880. };
  105881. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105882. var material = gltfRuntime.materials[id];
  105883. if (!material || !material.extensions)
  105884. return false;
  105885. var extension = material.extensions[this.name];
  105886. if (!extension)
  105887. return false;
  105888. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  105889. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105890. if (extension.technique === "CONSTANT") {
  105891. standardMaterial.disableLighting = true;
  105892. }
  105893. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  105894. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  105895. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  105896. // Ambient
  105897. if (typeof extension.values.ambient === "string") {
  105898. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  105899. }
  105900. else {
  105901. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  105902. }
  105903. // Diffuse
  105904. if (typeof extension.values.diffuse === "string") {
  105905. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  105906. }
  105907. else {
  105908. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  105909. }
  105910. // Emission
  105911. if (typeof extension.values.emission === "string") {
  105912. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  105913. }
  105914. else {
  105915. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  105916. }
  105917. // Specular
  105918. if (typeof extension.values.specular === "string") {
  105919. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  105920. }
  105921. else {
  105922. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  105923. }
  105924. return true;
  105925. };
  105926. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  105927. // Create buffer from texture url
  105928. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  105929. // Create texture from buffer
  105930. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  105931. }, onError);
  105932. };
  105933. return GLTFMaterialsCommonExtension;
  105934. }(GLTF1.GLTFLoaderExtension));
  105935. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  105936. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  105937. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105938. })(BABYLON || (BABYLON = {}));
  105939. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  105940. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105941. /**
  105942. * Defines the module used to import/export glTF 2.0 assets
  105943. */
  105944. var BABYLON;
  105945. (function (BABYLON) {
  105946. var GLTF2;
  105947. (function (GLTF2) {
  105948. var _ArrayItem = /** @class */ (function () {
  105949. function _ArrayItem() {
  105950. }
  105951. _ArrayItem.Assign = function (values) {
  105952. if (values) {
  105953. for (var index = 0; index < values.length; index++) {
  105954. values[index]._index = index;
  105955. }
  105956. }
  105957. };
  105958. return _ArrayItem;
  105959. }());
  105960. /**
  105961. * Loader for loading a glTF 2.0 asset
  105962. */
  105963. var GLTFLoader = /** @class */ (function () {
  105964. function GLTFLoader() {
  105965. /** @hidden */
  105966. this._completePromises = new Array();
  105967. /** @hidden */
  105968. this._onReadyObservable = new BABYLON.Observable();
  105969. this._disposed = false;
  105970. this._state = null;
  105971. this._extensions = {};
  105972. this._defaultSampler = {};
  105973. this._defaultBabylonMaterials = {};
  105974. this._requests = new Array();
  105975. /**
  105976. * Mode that determines the coordinate system to use.
  105977. */
  105978. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  105979. /**
  105980. * Mode that determines what animations will start.
  105981. */
  105982. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  105983. /**
  105984. * Defines if the loader should compile materials.
  105985. */
  105986. this.compileMaterials = false;
  105987. /**
  105988. * Defines if the loader should also compile materials with clip planes.
  105989. */
  105990. this.useClipPlane = false;
  105991. /**
  105992. * Defines if the loader should compile shadow generators.
  105993. */
  105994. this.compileShadowGenerators = false;
  105995. /**
  105996. * Defines if the Alpha blended materials are only applied as coverage.
  105997. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  105998. * If true, no extra effects are applied to transparent pixels.
  105999. */
  106000. this.transparencyAsCoverage = false;
  106001. /** @hidden */
  106002. this._normalizeAnimationGroupsToBeginAtZero = true;
  106003. /**
  106004. * Function called before loading a url referenced by the asset.
  106005. */
  106006. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106007. /**
  106008. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106009. */
  106010. this.onMeshLoadedObservable = new BABYLON.Observable();
  106011. /**
  106012. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  106013. */
  106014. this.onTextureLoadedObservable = new BABYLON.Observable();
  106015. /**
  106016. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  106017. */
  106018. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106019. /**
  106020. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  106021. */
  106022. this.onCameraLoadedObservable = new BABYLON.Observable();
  106023. /**
  106024. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  106025. * For assets with LODs, raised when all of the LODs are complete.
  106026. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  106027. */
  106028. this.onCompleteObservable = new BABYLON.Observable();
  106029. /**
  106030. * Observable raised after the loader is disposed.
  106031. */
  106032. this.onDisposeObservable = new BABYLON.Observable();
  106033. /**
  106034. * Observable raised after a loader extension is created.
  106035. * Set additional options for a loader extension in this event.
  106036. */
  106037. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106038. }
  106039. /** @hidden */
  106040. GLTFLoader._Register = function (name, factory) {
  106041. if (GLTFLoader._ExtensionFactories[name]) {
  106042. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  106043. return;
  106044. }
  106045. GLTFLoader._ExtensionFactories[name] = factory;
  106046. // Keep the order of registration so that extensions registered first are called first.
  106047. GLTFLoader._ExtensionNames.push(name);
  106048. };
  106049. Object.defineProperty(GLTFLoader.prototype, "state", {
  106050. /**
  106051. * Loader state or null if the loader is not active.
  106052. */
  106053. get: function () {
  106054. return this._state;
  106055. },
  106056. enumerable: true,
  106057. configurable: true
  106058. });
  106059. /**
  106060. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106061. */
  106062. GLTFLoader.prototype.dispose = function () {
  106063. if (this._disposed) {
  106064. return;
  106065. }
  106066. this._disposed = true;
  106067. this.onDisposeObservable.notifyObservers(this);
  106068. this.onDisposeObservable.clear();
  106069. this._clear();
  106070. };
  106071. /**
  106072. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  106073. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106074. * @param scene the scene the meshes should be added to
  106075. * @param data the glTF data to load
  106076. * @param rootUrl root url to load from
  106077. * @param onProgress event that fires when loading progress has occured
  106078. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106079. */
  106080. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106081. var _this = this;
  106082. return Promise.resolve().then(function () {
  106083. _this._babylonScene = scene;
  106084. _this._rootUrl = rootUrl;
  106085. _this._progressCallback = onProgress;
  106086. _this._loadData(data);
  106087. var nodes = null;
  106088. if (meshesNames) {
  106089. var nodeMap_1 = {};
  106090. if (_this._gltf.nodes) {
  106091. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  106092. var node = _a[_i];
  106093. if (node.name) {
  106094. nodeMap_1[node.name] = node;
  106095. }
  106096. }
  106097. }
  106098. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  106099. nodes = names.map(function (name) {
  106100. var node = nodeMap_1[name];
  106101. if (!node) {
  106102. throw new Error("Failed to find node '" + name + "'");
  106103. }
  106104. return node;
  106105. });
  106106. }
  106107. return _this._loadAsync(nodes).then(function () {
  106108. return {
  106109. meshes: _this._getMeshes(),
  106110. particleSystems: [],
  106111. skeletons: _this._getSkeletons(),
  106112. animationGroups: _this._getAnimationGroups()
  106113. };
  106114. });
  106115. });
  106116. };
  106117. /**
  106118. * Imports all objects from the loaded glTF data and adds them to the scene
  106119. * @param scene the scene the objects should be added to
  106120. * @param data the glTF data to load
  106121. * @param rootUrl root url to load from
  106122. * @param onProgress event that fires when loading progress has occured
  106123. * @returns a promise which completes when objects have been loaded to the scene
  106124. */
  106125. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106126. var _this = this;
  106127. return Promise.resolve().then(function () {
  106128. _this._babylonScene = scene;
  106129. _this._rootUrl = rootUrl;
  106130. _this._progressCallback = onProgress;
  106131. _this._loadData(data);
  106132. return _this._loadAsync(null);
  106133. });
  106134. };
  106135. GLTFLoader.prototype._loadAsync = function (nodes) {
  106136. var _this = this;
  106137. return Promise.resolve().then(function () {
  106138. _this._state = BABYLON.GLTFLoaderState.LOADING;
  106139. _this._loadExtensions();
  106140. _this._checkExtensions();
  106141. var promises = new Array();
  106142. if (nodes) {
  106143. promises.push(_this._loadNodesAsync(nodes));
  106144. }
  106145. else {
  106146. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  106147. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  106148. }
  106149. if (_this.compileMaterials) {
  106150. promises.push(_this._compileMaterialsAsync());
  106151. }
  106152. if (_this.compileShadowGenerators) {
  106153. promises.push(_this._compileShadowGeneratorsAsync());
  106154. }
  106155. var resultPromise = Promise.all(promises).then(function () {
  106156. _this._state = BABYLON.GLTFLoaderState.READY;
  106157. _this._onReadyObservable.notifyObservers(_this);
  106158. _this._startAnimations();
  106159. });
  106160. resultPromise.then(function () {
  106161. if (_this._rootBabylonMesh) {
  106162. _this._rootBabylonMesh.setEnabled(true);
  106163. }
  106164. BABYLON.Tools.SetImmediate(function () {
  106165. if (!_this._disposed) {
  106166. Promise.all(_this._completePromises).then(function () {
  106167. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  106168. _this.onCompleteObservable.notifyObservers(_this);
  106169. _this.onCompleteObservable.clear();
  106170. _this._clear();
  106171. }).catch(function (error) {
  106172. BABYLON.Tools.Error("glTF Loader: " + error.message);
  106173. _this._clear();
  106174. });
  106175. }
  106176. });
  106177. });
  106178. return resultPromise;
  106179. }).catch(function (error) {
  106180. if (!_this._disposed) {
  106181. BABYLON.Tools.Error("glTF Loader: " + error.message);
  106182. _this._clear();
  106183. throw error;
  106184. }
  106185. });
  106186. };
  106187. GLTFLoader.prototype._loadData = function (data) {
  106188. this._gltf = data.json;
  106189. this._setupData();
  106190. if (data.bin) {
  106191. var buffers = this._gltf.buffers;
  106192. if (buffers && buffers[0] && !buffers[0].uri) {
  106193. var binaryBuffer = buffers[0];
  106194. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  106195. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  106196. }
  106197. binaryBuffer._data = Promise.resolve(data.bin);
  106198. }
  106199. else {
  106200. BABYLON.Tools.Warn("Unexpected BIN chunk");
  106201. }
  106202. }
  106203. };
  106204. GLTFLoader.prototype._setupData = function () {
  106205. _ArrayItem.Assign(this._gltf.accessors);
  106206. _ArrayItem.Assign(this._gltf.animations);
  106207. _ArrayItem.Assign(this._gltf.buffers);
  106208. _ArrayItem.Assign(this._gltf.bufferViews);
  106209. _ArrayItem.Assign(this._gltf.cameras);
  106210. _ArrayItem.Assign(this._gltf.images);
  106211. _ArrayItem.Assign(this._gltf.materials);
  106212. _ArrayItem.Assign(this._gltf.meshes);
  106213. _ArrayItem.Assign(this._gltf.nodes);
  106214. _ArrayItem.Assign(this._gltf.samplers);
  106215. _ArrayItem.Assign(this._gltf.scenes);
  106216. _ArrayItem.Assign(this._gltf.skins);
  106217. _ArrayItem.Assign(this._gltf.textures);
  106218. if (this._gltf.nodes) {
  106219. var nodeParents = {};
  106220. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  106221. var node = _a[_i];
  106222. if (node.children) {
  106223. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  106224. var index = _c[_b];
  106225. nodeParents[index] = node._index;
  106226. }
  106227. }
  106228. }
  106229. var rootNode = this._createRootNode();
  106230. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  106231. var node = _e[_d];
  106232. var parentIndex = nodeParents[node._index];
  106233. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  106234. }
  106235. }
  106236. };
  106237. GLTFLoader.prototype._loadExtensions = function () {
  106238. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  106239. var name_1 = _a[_i];
  106240. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  106241. this._extensions[name_1] = extension;
  106242. this.onExtensionLoadedObservable.notifyObservers(extension);
  106243. }
  106244. this.onExtensionLoadedObservable.clear();
  106245. };
  106246. GLTFLoader.prototype._checkExtensions = function () {
  106247. if (this._gltf.extensionsRequired) {
  106248. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  106249. var name_2 = _a[_i];
  106250. var extension = this._extensions[name_2];
  106251. if (!extension || !extension.enabled) {
  106252. throw new Error("Require extension " + name_2 + " is not available");
  106253. }
  106254. }
  106255. }
  106256. };
  106257. GLTFLoader.prototype._createRootNode = function () {
  106258. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  106259. this._rootBabylonMesh.setEnabled(false);
  106260. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  106261. switch (this.coordinateSystemMode) {
  106262. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  106263. if (!this._babylonScene.useRightHandedSystem) {
  106264. rootNode.rotation = [0, 1, 0, 0];
  106265. rootNode.scale = [1, 1, -1];
  106266. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  106267. }
  106268. break;
  106269. }
  106270. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  106271. this._babylonScene.useRightHandedSystem = true;
  106272. break;
  106273. }
  106274. default: {
  106275. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  106276. }
  106277. }
  106278. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  106279. return rootNode;
  106280. };
  106281. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  106282. var promises = new Array();
  106283. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  106284. var node = nodes_1[_i];
  106285. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  106286. }
  106287. promises.push(this._loadAnimationsAsync());
  106288. return Promise.all(promises).then(function () { });
  106289. };
  106290. /** @hidden */
  106291. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  106292. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  106293. if (promise) {
  106294. return promise;
  106295. }
  106296. var promises = new Array();
  106297. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  106298. var index = _a[_i];
  106299. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  106300. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  106301. }
  106302. promises.push(this._loadAnimationsAsync());
  106303. return Promise.all(promises).then(function () { });
  106304. };
  106305. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  106306. if (node._primitiveBabylonMeshes) {
  106307. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  106308. var babylonMesh = _a[_i];
  106309. callback(babylonMesh);
  106310. }
  106311. }
  106312. else {
  106313. callback(node._babylonMesh);
  106314. }
  106315. };
  106316. GLTFLoader.prototype._getMeshes = function () {
  106317. var meshes = new Array();
  106318. // Root mesh is always first.
  106319. meshes.push(this._rootBabylonMesh);
  106320. var nodes = this._gltf.nodes;
  106321. if (nodes) {
  106322. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  106323. var node = nodes_2[_i];
  106324. if (node._babylonMesh) {
  106325. meshes.push(node._babylonMesh);
  106326. }
  106327. if (node._primitiveBabylonMeshes) {
  106328. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  106329. var babylonMesh = _b[_a];
  106330. meshes.push(babylonMesh);
  106331. }
  106332. }
  106333. }
  106334. }
  106335. return meshes;
  106336. };
  106337. GLTFLoader.prototype._getSkeletons = function () {
  106338. var skeletons = new Array();
  106339. var skins = this._gltf.skins;
  106340. if (skins) {
  106341. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  106342. var skin = skins_1[_i];
  106343. if (skin._babylonSkeleton) {
  106344. skeletons.push(skin._babylonSkeleton);
  106345. }
  106346. }
  106347. }
  106348. return skeletons;
  106349. };
  106350. GLTFLoader.prototype._getAnimationGroups = function () {
  106351. var animationGroups = new Array();
  106352. var animations = this._gltf.animations;
  106353. if (animations) {
  106354. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  106355. var animation = animations_1[_i];
  106356. if (animation._babylonAnimationGroup) {
  106357. animationGroups.push(animation._babylonAnimationGroup);
  106358. }
  106359. }
  106360. }
  106361. return animationGroups;
  106362. };
  106363. GLTFLoader.prototype._startAnimations = function () {
  106364. switch (this.animationStartMode) {
  106365. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  106366. // do nothing
  106367. break;
  106368. }
  106369. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  106370. var babylonAnimationGroups = this._getAnimationGroups();
  106371. if (babylonAnimationGroups.length !== 0) {
  106372. babylonAnimationGroups[0].start(true);
  106373. }
  106374. break;
  106375. }
  106376. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  106377. var babylonAnimationGroups = this._getAnimationGroups();
  106378. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  106379. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  106380. babylonAnimationGroup.start(true);
  106381. }
  106382. break;
  106383. }
  106384. default: {
  106385. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  106386. return;
  106387. }
  106388. }
  106389. };
  106390. /** @hidden */
  106391. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  106392. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  106393. if (promise) {
  106394. return promise;
  106395. }
  106396. if (node._babylonMesh) {
  106397. throw new Error(context + ": Invalid recursive node hierarchy");
  106398. }
  106399. var promises = new Array();
  106400. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  106401. node._babylonMesh = babylonMesh;
  106402. GLTFLoader._LoadTransform(node, babylonMesh);
  106403. if (node.mesh != undefined) {
  106404. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  106405. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  106406. }
  106407. if (node.camera != undefined) {
  106408. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  106409. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  106410. }
  106411. if (node.children) {
  106412. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  106413. var index = _a[_i];
  106414. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  106415. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  106416. }
  106417. }
  106418. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  106419. return Promise.all(promises).then(function () { });
  106420. };
  106421. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  106422. var _this = this;
  106423. var promises = new Array();
  106424. var primitives = mesh.primitives;
  106425. if (!primitives || primitives.length === 0) {
  106426. throw new Error(context + ": Primitives are missing");
  106427. }
  106428. _ArrayItem.Assign(primitives);
  106429. if (primitives.length === 1) {
  106430. var primitive = primitives[0];
  106431. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  106432. }
  106433. else {
  106434. node._primitiveBabylonMeshes = [];
  106435. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  106436. var primitive = primitives_1[_i];
  106437. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  106438. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  106439. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  106440. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  106441. }
  106442. }
  106443. if (node.skin != undefined) {
  106444. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  106445. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  106446. }
  106447. return Promise.all(promises).then(function () {
  106448. _this._forEachPrimitive(node, function (babylonMesh) {
  106449. babylonMesh._refreshBoundingInfo(true);
  106450. });
  106451. });
  106452. };
  106453. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  106454. var _this = this;
  106455. var promises = new Array();
  106456. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  106457. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  106458. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  106459. babylonGeometry.applyToMesh(babylonMesh);
  106460. });
  106461. }));
  106462. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  106463. if (primitive.material == undefined) {
  106464. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  106465. }
  106466. else {
  106467. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  106468. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  106469. babylonMesh.material = babylonMaterial;
  106470. }));
  106471. }
  106472. return Promise.all(promises).then(function () { });
  106473. };
  106474. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  106475. var _this = this;
  106476. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  106477. if (promise) {
  106478. return promise;
  106479. }
  106480. var attributes = primitive.attributes;
  106481. if (!attributes) {
  106482. throw new Error(context + ": Attributes are missing");
  106483. }
  106484. var promises = new Array();
  106485. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  106486. if (primitive.indices == undefined) {
  106487. babylonMesh.isUnIndexed = true;
  106488. }
  106489. else {
  106490. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  106491. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  106492. babylonGeometry.setIndices(data);
  106493. }));
  106494. }
  106495. var loadAttribute = function (attribute, kind, callback) {
  106496. if (attributes[attribute] == undefined) {
  106497. return;
  106498. }
  106499. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  106500. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  106501. babylonMesh._delayInfo.push(kind);
  106502. }
  106503. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  106504. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  106505. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  106506. }));
  106507. if (callback) {
  106508. callback(accessor);
  106509. }
  106510. };
  106511. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  106512. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  106513. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  106514. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  106515. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  106516. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  106517. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  106518. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  106519. if (accessor.type === "VEC4" /* VEC4 */) {
  106520. babylonMesh.hasVertexAlpha = true;
  106521. }
  106522. });
  106523. return Promise.all(promises).then(function () {
  106524. return babylonGeometry;
  106525. });
  106526. };
  106527. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  106528. if (!primitive.targets) {
  106529. return;
  106530. }
  106531. if (node._numMorphTargets == undefined) {
  106532. node._numMorphTargets = primitive.targets.length;
  106533. }
  106534. else if (primitive.targets.length !== node._numMorphTargets) {
  106535. throw new Error(context + ": Primitives do not have the same number of targets");
  106536. }
  106537. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  106538. for (var index = 0; index < primitive.targets.length; index++) {
  106539. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  106540. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  106541. // TODO: tell the target whether it has positions, normals, tangents
  106542. }
  106543. };
  106544. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  106545. if (!primitive.targets) {
  106546. return Promise.resolve();
  106547. }
  106548. var promises = new Array();
  106549. var morphTargetManager = babylonMesh.morphTargetManager;
  106550. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  106551. var babylonMorphTarget = morphTargetManager.getTarget(index);
  106552. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  106553. }
  106554. return Promise.all(promises).then(function () { });
  106555. };
  106556. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  106557. var _this = this;
  106558. var promises = new Array();
  106559. var loadAttribute = function (attribute, kind, setData) {
  106560. if (attributes[attribute] == undefined) {
  106561. return;
  106562. }
  106563. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  106564. if (!babylonVertexBuffer) {
  106565. return;
  106566. }
  106567. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  106568. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  106569. setData(babylonVertexBuffer, data);
  106570. }));
  106571. };
  106572. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  106573. babylonVertexBuffer.forEach(data.length, function (value, index) {
  106574. data[index] += value;
  106575. });
  106576. babylonMorphTarget.setPositions(data);
  106577. });
  106578. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  106579. babylonVertexBuffer.forEach(data.length, function (value, index) {
  106580. data[index] += value;
  106581. });
  106582. babylonMorphTarget.setNormals(data);
  106583. });
  106584. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  106585. var dataIndex = 0;
  106586. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  106587. // Tangent data for morph targets is stored as xyz delta.
  106588. // The vertexData.tangent is stored as xyzw.
  106589. // So we need to skip every fourth vertexData.tangent.
  106590. if (((index + 1) % 4) !== 0) {
  106591. data[dataIndex++] += value;
  106592. }
  106593. });
  106594. babylonMorphTarget.setTangents(data);
  106595. });
  106596. return Promise.all(promises).then(function () { });
  106597. };
  106598. GLTFLoader._LoadTransform = function (node, babylonNode) {
  106599. var position = BABYLON.Vector3.Zero();
  106600. var rotation = BABYLON.Quaternion.Identity();
  106601. var scaling = BABYLON.Vector3.One();
  106602. if (node.matrix) {
  106603. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  106604. matrix.decompose(scaling, rotation, position);
  106605. }
  106606. else {
  106607. if (node.translation)
  106608. position = BABYLON.Vector3.FromArray(node.translation);
  106609. if (node.rotation)
  106610. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  106611. if (node.scale)
  106612. scaling = BABYLON.Vector3.FromArray(node.scale);
  106613. }
  106614. babylonNode.position = position;
  106615. babylonNode.rotationQuaternion = rotation;
  106616. babylonNode.scaling = scaling;
  106617. };
  106618. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  106619. var _this = this;
  106620. var assignSkeleton = function (skeleton) {
  106621. _this._forEachPrimitive(node, function (babylonMesh) {
  106622. babylonMesh.skeleton = skeleton;
  106623. });
  106624. // Ignore the TRS of skinned nodes.
  106625. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  106626. node._babylonMesh.parent = _this._rootBabylonMesh;
  106627. node._babylonMesh.position = BABYLON.Vector3.Zero();
  106628. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  106629. node._babylonMesh.scaling = BABYLON.Vector3.One();
  106630. };
  106631. if (skin._loaded) {
  106632. return skin._loaded.then(function () {
  106633. assignSkeleton(skin._babylonSkeleton);
  106634. });
  106635. }
  106636. var skeletonId = "skeleton" + skin._index;
  106637. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  106638. skin._babylonSkeleton = babylonSkeleton;
  106639. this._loadBones(context, skin);
  106640. assignSkeleton(babylonSkeleton);
  106641. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  106642. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  106643. }));
  106644. };
  106645. GLTFLoader.prototype._loadBones = function (context, skin) {
  106646. var babylonBones = {};
  106647. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  106648. var index = _a[_i];
  106649. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  106650. this._loadBone(node, skin, babylonBones);
  106651. }
  106652. };
  106653. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  106654. var babylonBone = babylonBones[node._index];
  106655. if (babylonBone) {
  106656. return babylonBone;
  106657. }
  106658. var babylonParentBone = null;
  106659. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  106660. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  106661. }
  106662. var boneIndex = skin.joints.indexOf(node._index);
  106663. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  106664. babylonBones[node._index] = babylonBone;
  106665. node._babylonBones = node._babylonBones || [];
  106666. node._babylonBones.push(babylonBone);
  106667. return babylonBone;
  106668. };
  106669. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  106670. if (skin.inverseBindMatrices == undefined) {
  106671. return Promise.resolve(null);
  106672. }
  106673. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  106674. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  106675. };
  106676. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  106677. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  106678. var babylonBone = _a[_i];
  106679. var baseMatrix = BABYLON.Matrix.Identity();
  106680. var boneIndex = babylonBone._index;
  106681. if (inverseBindMatricesData && boneIndex !== -1) {
  106682. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  106683. baseMatrix.invertToRef(baseMatrix);
  106684. }
  106685. var babylonParentBone = babylonBone.getParent();
  106686. if (babylonParentBone) {
  106687. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  106688. }
  106689. babylonBone.updateMatrix(baseMatrix, false, false);
  106690. babylonBone._updateDifferenceMatrix(undefined, false);
  106691. }
  106692. };
  106693. GLTFLoader.prototype._getNodeMatrix = function (node) {
  106694. return node.matrix ?
  106695. BABYLON.Matrix.FromArray(node.matrix) :
  106696. 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());
  106697. };
  106698. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  106699. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  106700. babylonCamera.parent = babylonMesh;
  106701. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  106702. switch (camera.type) {
  106703. case "perspective" /* PERSPECTIVE */: {
  106704. var perspective = camera.perspective;
  106705. if (!perspective) {
  106706. throw new Error(context + ": Camera perspective properties are missing");
  106707. }
  106708. babylonCamera.fov = perspective.yfov;
  106709. babylonCamera.minZ = perspective.znear;
  106710. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  106711. break;
  106712. }
  106713. case "orthographic" /* ORTHOGRAPHIC */: {
  106714. if (!camera.orthographic) {
  106715. throw new Error(context + ": Camera orthographic properties are missing");
  106716. }
  106717. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  106718. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  106719. babylonCamera.orthoRight = camera.orthographic.xmag;
  106720. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  106721. babylonCamera.orthoTop = camera.orthographic.ymag;
  106722. babylonCamera.minZ = camera.orthographic.znear;
  106723. babylonCamera.maxZ = camera.orthographic.zfar;
  106724. break;
  106725. }
  106726. default: {
  106727. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  106728. }
  106729. }
  106730. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  106731. };
  106732. GLTFLoader.prototype._loadAnimationsAsync = function () {
  106733. var animations = this._gltf.animations;
  106734. if (!animations) {
  106735. return Promise.resolve();
  106736. }
  106737. var promises = new Array();
  106738. for (var index = 0; index < animations.length; index++) {
  106739. var animation = animations[index];
  106740. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  106741. }
  106742. return Promise.all(promises).then(function () { });
  106743. };
  106744. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  106745. var _this = this;
  106746. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  106747. animation._babylonAnimationGroup = babylonAnimationGroup;
  106748. var promises = new Array();
  106749. _ArrayItem.Assign(animation.channels);
  106750. _ArrayItem.Assign(animation.samplers);
  106751. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  106752. var channel = _a[_i];
  106753. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  106754. }
  106755. return Promise.all(promises).then(function () {
  106756. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  106757. });
  106758. };
  106759. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  106760. var _this = this;
  106761. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  106762. // Ignore animations that have no animation targets.
  106763. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  106764. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  106765. return Promise.resolve();
  106766. }
  106767. // Ignore animations targeting TRS of skinned nodes.
  106768. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  106769. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  106770. return Promise.resolve();
  106771. }
  106772. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  106773. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  106774. var targetPath;
  106775. var animationType;
  106776. switch (channel.target.path) {
  106777. case "translation" /* TRANSLATION */: {
  106778. targetPath = "position";
  106779. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106780. break;
  106781. }
  106782. case "rotation" /* ROTATION */: {
  106783. targetPath = "rotationQuaternion";
  106784. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106785. break;
  106786. }
  106787. case "scale" /* SCALE */: {
  106788. targetPath = "scaling";
  106789. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106790. break;
  106791. }
  106792. case "weights" /* WEIGHTS */: {
  106793. targetPath = "influence";
  106794. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  106795. break;
  106796. }
  106797. default: {
  106798. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  106799. }
  106800. }
  106801. var outputBufferOffset = 0;
  106802. var getNextOutputValue;
  106803. switch (targetPath) {
  106804. case "position": {
  106805. getNextOutputValue = function () {
  106806. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  106807. outputBufferOffset += 3;
  106808. return value;
  106809. };
  106810. break;
  106811. }
  106812. case "rotationQuaternion": {
  106813. getNextOutputValue = function () {
  106814. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  106815. outputBufferOffset += 4;
  106816. return value;
  106817. };
  106818. break;
  106819. }
  106820. case "scaling": {
  106821. getNextOutputValue = function () {
  106822. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  106823. outputBufferOffset += 3;
  106824. return value;
  106825. };
  106826. break;
  106827. }
  106828. case "influence": {
  106829. getNextOutputValue = function () {
  106830. var value = new Array(targetNode._numMorphTargets);
  106831. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  106832. value[i] = data.output[outputBufferOffset++];
  106833. }
  106834. return value;
  106835. };
  106836. break;
  106837. }
  106838. }
  106839. var getNextKey;
  106840. switch (data.interpolation) {
  106841. case "STEP" /* STEP */: {
  106842. getNextKey = function (frameIndex) { return ({
  106843. frame: data.input[frameIndex],
  106844. value: getNextOutputValue(),
  106845. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  106846. }); };
  106847. break;
  106848. }
  106849. case "LINEAR" /* LINEAR */: {
  106850. getNextKey = function (frameIndex) { return ({
  106851. frame: data.input[frameIndex],
  106852. value: getNextOutputValue()
  106853. }); };
  106854. break;
  106855. }
  106856. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106857. getNextKey = function (frameIndex) { return ({
  106858. frame: data.input[frameIndex],
  106859. inTangent: getNextOutputValue(),
  106860. value: getNextOutputValue(),
  106861. outTangent: getNextOutputValue()
  106862. }); };
  106863. break;
  106864. }
  106865. }
  106866. var keys = new Array(data.input.length);
  106867. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  106868. keys[frameIndex] = getNextKey(frameIndex);
  106869. }
  106870. if (targetPath === "influence") {
  106871. var _loop_1 = function (targetIndex) {
  106872. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106873. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106874. babylonAnimation.setKeys(keys.map(function (key) { return ({
  106875. frame: key.frame,
  106876. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  106877. value: key.value[targetIndex],
  106878. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  106879. }); }));
  106880. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  106881. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  106882. var babylonAnimationClone = babylonAnimation.clone();
  106883. morphTarget.animations.push(babylonAnimationClone);
  106884. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  106885. });
  106886. };
  106887. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  106888. _loop_1(targetIndex);
  106889. }
  106890. }
  106891. else {
  106892. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106893. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106894. babylonAnimation.setKeys(keys);
  106895. if (targetNode._babylonBones) {
  106896. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  106897. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  106898. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  106899. babylonAnimationTarget.animations.push(babylonAnimation);
  106900. }
  106901. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  106902. }
  106903. else {
  106904. targetNode._babylonMesh.animations.push(babylonAnimation);
  106905. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  106906. }
  106907. }
  106908. });
  106909. };
  106910. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  106911. if (sampler._data) {
  106912. return sampler._data;
  106913. }
  106914. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  106915. switch (interpolation) {
  106916. case "STEP" /* STEP */:
  106917. case "LINEAR" /* LINEAR */:
  106918. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106919. break;
  106920. }
  106921. default: {
  106922. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  106923. }
  106924. }
  106925. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  106926. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  106927. sampler._data = Promise.all([
  106928. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  106929. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  106930. ]).then(function (_a) {
  106931. var inputData = _a[0], outputData = _a[1];
  106932. return {
  106933. input: inputData,
  106934. interpolation: interpolation,
  106935. output: outputData,
  106936. };
  106937. });
  106938. return sampler._data;
  106939. };
  106940. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  106941. if (buffer._data) {
  106942. return buffer._data;
  106943. }
  106944. if (!buffer.uri) {
  106945. throw new Error(context + ": Uri is missing");
  106946. }
  106947. buffer._data = this._loadUriAsync(context, buffer.uri);
  106948. return buffer._data;
  106949. };
  106950. /** @hidden */
  106951. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  106952. if (bufferView._data) {
  106953. return bufferView._data;
  106954. }
  106955. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  106956. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  106957. try {
  106958. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  106959. }
  106960. catch (e) {
  106961. throw new Error(context + ": " + e.message);
  106962. }
  106963. });
  106964. return bufferView._data;
  106965. };
  106966. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  106967. if (accessor.type !== "SCALAR" /* SCALAR */) {
  106968. throw new Error(context + ": Invalid type " + accessor.type);
  106969. }
  106970. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  106971. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  106972. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  106973. throw new Error(context + ": Invalid component type " + accessor.componentType);
  106974. }
  106975. if (accessor._data) {
  106976. return accessor._data;
  106977. }
  106978. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106979. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106980. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  106981. });
  106982. return accessor._data;
  106983. };
  106984. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  106985. // TODO: support normalized and stride
  106986. var _this = this;
  106987. if (accessor.componentType !== 5126 /* FLOAT */) {
  106988. throw new Error("Invalid component type " + accessor.componentType);
  106989. }
  106990. if (accessor._data) {
  106991. return accessor._data;
  106992. }
  106993. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  106994. var length = numComponents * accessor.count;
  106995. if (accessor.bufferView == undefined) {
  106996. accessor._data = Promise.resolve(new Float32Array(length));
  106997. }
  106998. else {
  106999. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  107000. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  107001. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  107002. });
  107003. }
  107004. if (accessor.sparse) {
  107005. var sparse_1 = accessor.sparse;
  107006. accessor._data = accessor._data.then(function (data) {
  107007. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  107008. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  107009. return Promise.all([
  107010. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  107011. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  107012. ]).then(function (_a) {
  107013. var indicesData = _a[0], valuesData = _a[1];
  107014. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  107015. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  107016. var valuesIndex = 0;
  107017. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  107018. var dataIndex = indices[indicesIndex] * numComponents;
  107019. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  107020. data[dataIndex++] = values[valuesIndex++];
  107021. }
  107022. }
  107023. return data;
  107024. });
  107025. });
  107026. }
  107027. return accessor._data;
  107028. };
  107029. /** @hidden */
  107030. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  107031. var _this = this;
  107032. if (bufferView._babylonBuffer) {
  107033. return bufferView._babylonBuffer;
  107034. }
  107035. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  107036. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  107037. });
  107038. return bufferView._babylonBuffer;
  107039. };
  107040. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  107041. var _this = this;
  107042. if (accessor._babylonVertexBuffer) {
  107043. return accessor._babylonVertexBuffer;
  107044. }
  107045. if (accessor.sparse) {
  107046. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  107047. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  107048. });
  107049. }
  107050. else {
  107051. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  107052. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  107053. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  107054. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  107055. });
  107056. }
  107057. return accessor._babylonVertexBuffer;
  107058. };
  107059. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  107060. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  107061. if (!babylonMaterial) {
  107062. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  107063. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  107064. babylonMaterial.metallic = 1;
  107065. babylonMaterial.roughness = 1;
  107066. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107067. }
  107068. return babylonMaterial;
  107069. };
  107070. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  107071. var promises = new Array();
  107072. // Ensure metallic workflow
  107073. babylonMaterial.metallic = 1;
  107074. babylonMaterial.roughness = 1;
  107075. var properties = material.pbrMetallicRoughness;
  107076. if (properties) {
  107077. if (properties.baseColorFactor) {
  107078. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  107079. babylonMaterial.alpha = properties.baseColorFactor[3];
  107080. }
  107081. else {
  107082. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107083. }
  107084. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  107085. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  107086. if (properties.baseColorTexture) {
  107087. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  107088. babylonMaterial.albedoTexture = texture;
  107089. }));
  107090. }
  107091. if (properties.metallicRoughnessTexture) {
  107092. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  107093. babylonMaterial.metallicTexture = texture;
  107094. }));
  107095. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  107096. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  107097. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  107098. }
  107099. }
  107100. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  107101. return Promise.all(promises).then(function () { });
  107102. };
  107103. /** @hidden */
  107104. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  107105. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  107106. if (promise) {
  107107. return promise;
  107108. }
  107109. material._babylonData = material._babylonData || {};
  107110. var babylonData = material._babylonData[babylonDrawMode];
  107111. if (!babylonData) {
  107112. var promises = new Array();
  107113. var name_3 = material.name || "material_" + material._index;
  107114. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  107115. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  107116. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  107117. this.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. /** @hidden */
  107130. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  107131. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  107132. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  107133. babylonMaterial.fillMode = drawMode;
  107134. babylonMaterial.enableSpecularAntiAliasing = true;
  107135. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  107136. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  107137. return babylonMaterial;
  107138. };
  107139. /** @hidden */
  107140. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  107141. var promises = new Array();
  107142. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  107143. if (material.doubleSided) {
  107144. babylonMaterial.backFaceCulling = false;
  107145. babylonMaterial.twoSidedLighting = true;
  107146. }
  107147. if (material.normalTexture) {
  107148. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  107149. babylonMaterial.bumpTexture = texture;
  107150. }));
  107151. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  107152. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  107153. if (material.normalTexture.scale != undefined) {
  107154. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  107155. }
  107156. }
  107157. if (material.occlusionTexture) {
  107158. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  107159. babylonMaterial.ambientTexture = texture;
  107160. }));
  107161. babylonMaterial.useAmbientInGrayScale = true;
  107162. if (material.occlusionTexture.strength != undefined) {
  107163. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  107164. }
  107165. }
  107166. if (material.emissiveTexture) {
  107167. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  107168. babylonMaterial.emissiveTexture = texture;
  107169. }));
  107170. }
  107171. return Promise.all(promises).then(function () { });
  107172. };
  107173. /** @hidden */
  107174. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  107175. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  107176. switch (alphaMode) {
  107177. case "OPAQUE" /* OPAQUE */: {
  107178. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  107179. break;
  107180. }
  107181. case "MASK" /* MASK */: {
  107182. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  107183. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  107184. if (babylonMaterial.albedoTexture) {
  107185. babylonMaterial.albedoTexture.hasAlpha = true;
  107186. }
  107187. break;
  107188. }
  107189. case "BLEND" /* BLEND */: {
  107190. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  107191. if (babylonMaterial.albedoTexture) {
  107192. babylonMaterial.albedoTexture.hasAlpha = true;
  107193. babylonMaterial.useAlphaFromAlbedoTexture = true;
  107194. }
  107195. break;
  107196. }
  107197. default: {
  107198. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  107199. }
  107200. }
  107201. };
  107202. /** @hidden */
  107203. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  107204. var _this = this;
  107205. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  107206. if (promise) {
  107207. return promise;
  107208. }
  107209. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  107210. context = "#/textures/" + textureInfo.index;
  107211. var promises = new Array();
  107212. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  107213. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  107214. var deferred = new BABYLON.Deferred();
  107215. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  107216. if (!_this._disposed) {
  107217. deferred.resolve();
  107218. }
  107219. }, function (message, exception) {
  107220. if (!_this._disposed) {
  107221. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  107222. }
  107223. });
  107224. promises.push(deferred.promise);
  107225. babylonTexture.name = texture.name || "texture" + texture._index;
  107226. babylonTexture.wrapU = samplerData.wrapU;
  107227. babylonTexture.wrapV = samplerData.wrapV;
  107228. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  107229. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  107230. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  107231. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  107232. babylonTexture.updateURL(dataUrl, blob);
  107233. }));
  107234. assign(babylonTexture);
  107235. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  107236. return Promise.all(promises).then(function () { });
  107237. };
  107238. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  107239. if (!sampler._data) {
  107240. sampler._data = {
  107241. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  107242. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  107243. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  107244. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  107245. };
  107246. }
  107247. ;
  107248. return sampler._data;
  107249. };
  107250. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  107251. if (image._blob) {
  107252. return image._blob;
  107253. }
  107254. var promise;
  107255. if (image.uri) {
  107256. promise = this._loadUriAsync(context, image.uri);
  107257. }
  107258. else {
  107259. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  107260. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  107261. }
  107262. image._blob = promise.then(function (data) {
  107263. return new Blob([data], { type: image.mimeType });
  107264. });
  107265. return image._blob;
  107266. };
  107267. /** @hidden */
  107268. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  107269. var _this = this;
  107270. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  107271. if (promise) {
  107272. return promise;
  107273. }
  107274. if (!GLTFLoader._ValidateUri(uri)) {
  107275. throw new Error(context + ": Uri '" + uri + "' is invalid");
  107276. }
  107277. if (BABYLON.Tools.IsBase64(uri)) {
  107278. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  107279. }
  107280. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  107281. return new Promise(function (resolve, reject) {
  107282. if (!_this._disposed) {
  107283. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  107284. if (!_this._disposed) {
  107285. resolve(new Uint8Array(data));
  107286. }
  107287. }, function (event) {
  107288. if (!_this._disposed) {
  107289. try {
  107290. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  107291. request_1._lengthComputable = event.lengthComputable;
  107292. request_1._loaded = event.loaded;
  107293. request_1._total = event.total;
  107294. _this._onProgress();
  107295. }
  107296. }
  107297. catch (e) {
  107298. reject(e);
  107299. }
  107300. }
  107301. }, _this._babylonScene.database, true, function (request, exception) {
  107302. if (!_this._disposed) {
  107303. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  107304. }
  107305. });
  107306. _this._requests.push(request_1);
  107307. }
  107308. });
  107309. });
  107310. };
  107311. GLTFLoader.prototype._onProgress = function () {
  107312. if (!this._progressCallback) {
  107313. return;
  107314. }
  107315. var lengthComputable = true;
  107316. var loaded = 0;
  107317. var total = 0;
  107318. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  107319. var request = _a[_i];
  107320. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  107321. return;
  107322. }
  107323. lengthComputable = lengthComputable && request._lengthComputable;
  107324. loaded += request._loaded;
  107325. total += request._total;
  107326. }
  107327. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  107328. };
  107329. /** @hidden */
  107330. GLTFLoader._GetProperty = function (context, array, index) {
  107331. if (!array || index == undefined || !array[index]) {
  107332. throw new Error(context + ": Failed to find index (" + index + ")");
  107333. }
  107334. return array[index];
  107335. };
  107336. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  107337. // Set defaults if undefined
  107338. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  107339. switch (mode) {
  107340. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  107341. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  107342. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  107343. default:
  107344. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  107345. return BABYLON.Texture.WRAP_ADDRESSMODE;
  107346. }
  107347. };
  107348. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  107349. // Set defaults if undefined
  107350. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  107351. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  107352. if (magFilter === 9729 /* LINEAR */) {
  107353. switch (minFilter) {
  107354. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  107355. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  107356. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  107357. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  107358. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  107359. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  107360. default:
  107361. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  107362. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  107363. }
  107364. }
  107365. else {
  107366. if (magFilter !== 9728 /* NEAREST */) {
  107367. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  107368. }
  107369. switch (minFilter) {
  107370. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  107371. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  107372. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  107373. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  107374. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  107375. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  107376. default:
  107377. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  107378. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  107379. }
  107380. }
  107381. };
  107382. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  107383. var buffer = bufferView.buffer;
  107384. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  107385. try {
  107386. switch (componentType) {
  107387. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  107388. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  107389. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  107390. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  107391. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  107392. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  107393. default: throw new Error("Invalid component type " + componentType);
  107394. }
  107395. }
  107396. catch (e) {
  107397. throw new Error(context + ": " + e);
  107398. }
  107399. };
  107400. GLTFLoader._GetNumComponents = function (context, type) {
  107401. switch (type) {
  107402. case "SCALAR": return 1;
  107403. case "VEC2": return 2;
  107404. case "VEC3": return 3;
  107405. case "VEC4": return 4;
  107406. case "MAT2": return 4;
  107407. case "MAT3": return 9;
  107408. case "MAT4": return 16;
  107409. }
  107410. throw new Error(context + ": Invalid type (" + type + ")");
  107411. };
  107412. GLTFLoader._ValidateUri = function (uri) {
  107413. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  107414. };
  107415. GLTFLoader._GetDrawMode = function (context, mode) {
  107416. if (mode == undefined) {
  107417. mode = 4 /* TRIANGLES */;
  107418. }
  107419. switch (mode) {
  107420. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  107421. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  107422. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  107423. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  107424. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  107425. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  107426. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  107427. }
  107428. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  107429. };
  107430. GLTFLoader.prototype._compileMaterialsAsync = function () {
  107431. var promises = new Array();
  107432. if (this._gltf.materials) {
  107433. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  107434. var material = _a[_i];
  107435. if (material._babylonData) {
  107436. for (var babylonDrawMode in material._babylonData) {
  107437. var babylonData = material._babylonData[babylonDrawMode];
  107438. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  107439. var babylonMesh = _c[_b];
  107440. // Ensure nonUniformScaling is set if necessary.
  107441. babylonMesh.computeWorldMatrix(true);
  107442. var babylonMaterial = babylonData.material;
  107443. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  107444. if (this.useClipPlane) {
  107445. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  107446. }
  107447. }
  107448. }
  107449. }
  107450. }
  107451. }
  107452. return Promise.all(promises).then(function () { });
  107453. };
  107454. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  107455. var promises = new Array();
  107456. var lights = this._babylonScene.lights;
  107457. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  107458. var light = lights_1[_i];
  107459. var generator = light.getShadowGenerator();
  107460. if (generator) {
  107461. promises.push(generator.forceCompilationAsync());
  107462. }
  107463. }
  107464. return Promise.all(promises).then(function () { });
  107465. };
  107466. GLTFLoader.prototype._clear = function () {
  107467. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  107468. var request = _a[_i];
  107469. request.abort();
  107470. }
  107471. this._requests.length = 0;
  107472. delete this._gltf;
  107473. delete this._babylonScene;
  107474. this._completePromises.length = 0;
  107475. this._onReadyObservable.clear();
  107476. for (var name_4 in this._extensions) {
  107477. this._extensions[name_4].dispose();
  107478. }
  107479. this._extensions = {};
  107480. delete this._rootBabylonMesh;
  107481. delete this._progressCallback;
  107482. this.onMeshLoadedObservable.clear();
  107483. this.onTextureLoadedObservable.clear();
  107484. this.onMaterialLoadedObservable.clear();
  107485. this.onCameraLoadedObservable.clear();
  107486. };
  107487. /** @hidden */
  107488. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  107489. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  107490. var name_5 = _a[_i];
  107491. var extension = this._extensions[name_5];
  107492. if (extension.enabled) {
  107493. var promise = actionAsync(extension);
  107494. if (promise) {
  107495. return promise;
  107496. }
  107497. }
  107498. }
  107499. return null;
  107500. };
  107501. GLTFLoader._ExtensionNames = new Array();
  107502. GLTFLoader._ExtensionFactories = {};
  107503. return GLTFLoader;
  107504. }());
  107505. GLTF2.GLTFLoader = GLTFLoader;
  107506. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  107507. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107508. })(BABYLON || (BABYLON = {}));
  107509. //# sourceMappingURL=babylon.glTFLoader.js.map
  107510. var BABYLON;
  107511. (function (BABYLON) {
  107512. var GLTF2;
  107513. (function (GLTF2) {
  107514. /**
  107515. * Abstract class that can be implemented to extend existing glTF loader behavior.
  107516. */
  107517. var GLTFLoaderExtension = /** @class */ (function () {
  107518. /**
  107519. * Creates new GLTFLoaderExtension
  107520. * @param loader defines the GLTFLoader to use
  107521. */
  107522. function GLTFLoaderExtension(loader) {
  107523. /**
  107524. * Gets or sets a boolean indicating if the extension is enabled
  107525. */
  107526. this.enabled = true;
  107527. this._loader = loader;
  107528. }
  107529. /**
  107530. * Release all resources
  107531. */
  107532. GLTFLoaderExtension.prototype.dispose = function () {
  107533. delete this._loader;
  107534. };
  107535. // #region Overridable Methods
  107536. /**
  107537. * Override this method to modify the default behavior for loading scenes.
  107538. * @hidden
  107539. */
  107540. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  107541. /**
  107542. * Override this method to modify the default behavior for loading nodes.
  107543. * @hidden
  107544. */
  107545. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  107546. /**
  107547. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  107548. * @hidden
  107549. */
  107550. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  107551. /**
  107552. * Override this method to modify the default behavior for loading materials.
  107553. * @hidden
  107554. */
  107555. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  107556. /**
  107557. * Override this method to modify the default behavior for loading textures.
  107558. * @hidden
  107559. */
  107560. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  107561. /**
  107562. * Override this method to modify the default behavior for loading uris.
  107563. * @hidden
  107564. */
  107565. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  107566. // #endregion
  107567. /**
  107568. * Helper method called by a loader extension to load an glTF extension.
  107569. * @hidden
  107570. */
  107571. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  107572. if (!property.extensions) {
  107573. return null;
  107574. }
  107575. var extensions = property.extensions;
  107576. var extension = extensions[this.name];
  107577. if (!extension) {
  107578. return null;
  107579. }
  107580. // Clear out the extension before executing the action to avoid infinite recursion.
  107581. delete extensions[this.name];
  107582. try {
  107583. return actionAsync(context + "/extensions/" + this.name, extension);
  107584. }
  107585. finally {
  107586. // Restore the extension after executing the action.
  107587. extensions[this.name] = extension;
  107588. }
  107589. };
  107590. /**
  107591. * Helper method called by the loader to allow extensions to override loading scenes.
  107592. * @hidden
  107593. */
  107594. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  107595. if (!property.extras) {
  107596. return null;
  107597. }
  107598. var extras = property.extras;
  107599. var value = extras[this.name];
  107600. if (value === undefined) {
  107601. return null;
  107602. }
  107603. // Clear out the extras value before executing the action to avoid infinite recursion.
  107604. delete extras[this.name];
  107605. try {
  107606. return actionAsync(context + "/extras/" + this.name, value);
  107607. }
  107608. finally {
  107609. // Restore the extras value after executing the action.
  107610. extras[this.name] = value;
  107611. }
  107612. };
  107613. /**
  107614. * Helper method called by the loader to allow extensions to override loading scenes.
  107615. * @hidden
  107616. */
  107617. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  107618. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  107619. };
  107620. /**
  107621. * Helper method called by the loader to allow extensions to override loading nodes.
  107622. * @hidden
  107623. */
  107624. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  107625. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  107626. };
  107627. /**
  107628. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  107629. * @hidden
  107630. */
  107631. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  107632. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  107633. };
  107634. /**
  107635. * Helper method called by the loader to allow extensions to override loading materials.
  107636. * @hidden
  107637. */
  107638. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  107639. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  107640. };
  107641. /**
  107642. * Helper method called by the loader to allow extensions to override loading textures.
  107643. * @hidden
  107644. */
  107645. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  107646. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  107647. };
  107648. /**
  107649. * Helper method called by the loader to allow extensions to override loading uris.
  107650. * @hidden
  107651. */
  107652. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  107653. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  107654. };
  107655. return GLTFLoaderExtension;
  107656. }());
  107657. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  107658. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107659. })(BABYLON || (BABYLON = {}));
  107660. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107661. var BABYLON;
  107662. (function (BABYLON) {
  107663. var GLTF2;
  107664. (function (GLTF2) {
  107665. var Extensions;
  107666. (function (Extensions) {
  107667. var NAME = "MSFT_lod";
  107668. /**
  107669. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  107670. */
  107671. var MSFT_lod = /** @class */ (function (_super) {
  107672. __extends(MSFT_lod, _super);
  107673. function MSFT_lod(loader) {
  107674. var _this = _super.call(this, loader) || this;
  107675. _this.name = NAME;
  107676. /**
  107677. * Maximum number of LODs to load, starting from the lowest LOD.
  107678. */
  107679. _this.maxLODsToLoad = Number.MAX_VALUE;
  107680. /**
  107681. * Observable raised when all node LODs of one level are loaded.
  107682. * The event data is the index of the loaded LOD starting from zero.
  107683. * Dispose the loader to cancel the loading of the next level of LODs.
  107684. */
  107685. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  107686. /**
  107687. * Observable raised when all material LODs of one level are loaded.
  107688. * The event data is the index of the loaded LOD starting from zero.
  107689. * Dispose the loader to cancel the loading of the next level of LODs.
  107690. */
  107691. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  107692. _this._loadingNodeLOD = null;
  107693. _this._loadNodeSignals = {};
  107694. _this._loadNodePromises = new Array();
  107695. _this._loadingMaterialLOD = null;
  107696. _this._loadMaterialSignals = {};
  107697. _this._loadMaterialPromises = new Array();
  107698. _this._loader._onReadyObservable.addOnce(function () {
  107699. var _loop_1 = function (indexLOD) {
  107700. Promise.all(_this._loadNodePromises[indexLOD]).then(function () {
  107701. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  107702. });
  107703. };
  107704. for (var indexLOD = 0; indexLOD < _this._loadNodePromises.length; indexLOD++) {
  107705. _loop_1(indexLOD);
  107706. }
  107707. var _loop_2 = function (indexLOD) {
  107708. Promise.all(_this._loadMaterialPromises[indexLOD]).then(function () {
  107709. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  107710. });
  107711. };
  107712. for (var indexLOD = 0; indexLOD < _this._loadMaterialPromises.length; indexLOD++) {
  107713. _loop_2(indexLOD);
  107714. }
  107715. });
  107716. return _this;
  107717. }
  107718. MSFT_lod.prototype.dispose = function () {
  107719. _super.prototype.dispose.call(this);
  107720. this._loadingNodeLOD = null;
  107721. this._loadNodeSignals = {};
  107722. this._loadingMaterialLOD = null;
  107723. this._loadMaterialSignals = {};
  107724. this.onMaterialLODsLoadedObservable.clear();
  107725. this.onNodeLODsLoadedObservable.clear();
  107726. };
  107727. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  107728. var _this = this;
  107729. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  107730. var firstPromise;
  107731. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  107732. var _loop_3 = function (indexLOD) {
  107733. var nodeLOD = nodeLODs[indexLOD];
  107734. if (indexLOD !== 0) {
  107735. _this._loadingNodeLOD = nodeLOD;
  107736. if (!_this._loadNodeSignals[nodeLOD._index]) {
  107737. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  107738. }
  107739. }
  107740. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  107741. if (indexLOD !== 0) {
  107742. var previousNodeLOD = nodeLODs[indexLOD - 1];
  107743. if (previousNodeLOD._babylonMesh) {
  107744. previousNodeLOD._babylonMesh.dispose(false, true);
  107745. delete previousNodeLOD._babylonMesh;
  107746. }
  107747. }
  107748. if (indexLOD !== nodeLODs.length - 1) {
  107749. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  107750. if (_this._loadNodeSignals[nodeIndex]) {
  107751. _this._loadNodeSignals[nodeIndex].resolve();
  107752. delete _this._loadNodeSignals[nodeIndex];
  107753. }
  107754. }
  107755. });
  107756. if (indexLOD === 0) {
  107757. firstPromise = promise;
  107758. }
  107759. else {
  107760. _this._loader._completePromises.push(promise);
  107761. _this._loadingNodeLOD = null;
  107762. }
  107763. _this._loadNodePromises[indexLOD] = _this._loadNodePromises[indexLOD] || [];
  107764. _this._loadNodePromises[indexLOD].push(promise);
  107765. };
  107766. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  107767. _loop_3(indexLOD);
  107768. }
  107769. return firstPromise;
  107770. });
  107771. };
  107772. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  107773. var _this = this;
  107774. // Don't load material LODs if already loading a node LOD.
  107775. if (this._loadingNodeLOD) {
  107776. return null;
  107777. }
  107778. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  107779. var firstPromise;
  107780. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  107781. var _loop_4 = function (indexLOD) {
  107782. var materialLOD = materialLODs[indexLOD];
  107783. if (indexLOD !== 0) {
  107784. _this._loadingMaterialLOD = materialLOD;
  107785. if (!_this._loadMaterialSignals[materialLOD._index]) {
  107786. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  107787. }
  107788. }
  107789. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  107790. if (indexLOD !== 0) {
  107791. var babylonDataLOD = materialLOD._babylonData;
  107792. assign(babylonDataLOD[babylonDrawMode].material);
  107793. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  107794. if (previousBabylonDataLOD[babylonDrawMode]) {
  107795. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  107796. delete previousBabylonDataLOD[babylonDrawMode];
  107797. }
  107798. }
  107799. if (indexLOD !== materialLODs.length - 1) {
  107800. var materialIndex = materialLODs[indexLOD + 1]._index;
  107801. if (_this._loadMaterialSignals[materialIndex]) {
  107802. _this._loadMaterialSignals[materialIndex].resolve();
  107803. delete _this._loadMaterialSignals[materialIndex];
  107804. }
  107805. }
  107806. });
  107807. if (indexLOD === 0) {
  107808. firstPromise = promise;
  107809. }
  107810. else {
  107811. _this._loader._completePromises.push(promise);
  107812. _this._loadingMaterialLOD = null;
  107813. }
  107814. _this._loadMaterialPromises[indexLOD] = _this._loadMaterialPromises[indexLOD] || [];
  107815. _this._loadMaterialPromises[indexLOD].push(promise);
  107816. };
  107817. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  107818. _loop_4(indexLOD);
  107819. }
  107820. return firstPromise;
  107821. });
  107822. };
  107823. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  107824. var _this = this;
  107825. // Defer the loading of uris if loading a material or node LOD.
  107826. if (this._loadingMaterialLOD) {
  107827. var index = this._loadingMaterialLOD._index;
  107828. return this._loadMaterialSignals[index].promise.then(function () {
  107829. return _this._loader._loadUriAsync(context, uri);
  107830. });
  107831. }
  107832. else if (this._loadingNodeLOD) {
  107833. var index = this._loadingNodeLOD._index;
  107834. return this._loadNodeSignals[index].promise.then(function () {
  107835. return _this._loader._loadUriAsync(context, uri);
  107836. });
  107837. }
  107838. return null;
  107839. };
  107840. /**
  107841. * Gets an array of LOD properties from lowest to highest.
  107842. */
  107843. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  107844. if (this.maxLODsToLoad <= 0) {
  107845. throw new Error("maxLODsToLoad must be greater than zero");
  107846. }
  107847. var properties = new Array();
  107848. for (var i = ids.length - 1; i >= 0; i--) {
  107849. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  107850. if (properties.length === this.maxLODsToLoad) {
  107851. return properties;
  107852. }
  107853. }
  107854. properties.push(property);
  107855. return properties;
  107856. };
  107857. return MSFT_lod;
  107858. }(GLTF2.GLTFLoaderExtension));
  107859. Extensions.MSFT_lod = MSFT_lod;
  107860. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  107861. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107862. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107863. })(BABYLON || (BABYLON = {}));
  107864. //# sourceMappingURL=MSFT_lod.js.map
  107865. var BABYLON;
  107866. (function (BABYLON) {
  107867. var GLTF2;
  107868. (function (GLTF2) {
  107869. var Extensions;
  107870. (function (Extensions) {
  107871. var NAME = "MSFT_minecraftMesh";
  107872. /** @hidden */
  107873. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  107874. __extends(MSFT_minecraftMesh, _super);
  107875. function MSFT_minecraftMesh() {
  107876. var _this = _super !== null && _super.apply(this, arguments) || this;
  107877. _this.name = NAME;
  107878. return _this;
  107879. }
  107880. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  107881. var _this = this;
  107882. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  107883. if (value) {
  107884. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  107885. if (babylonMaterial.needAlphaBlending()) {
  107886. babylonMaterial.forceDepthWrite = true;
  107887. babylonMaterial.separateCullingPass = true;
  107888. }
  107889. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  107890. babylonMaterial.twoSidedLighting = true;
  107891. assign(babylonMaterial);
  107892. });
  107893. }
  107894. return null;
  107895. });
  107896. };
  107897. return MSFT_minecraftMesh;
  107898. }(GLTF2.GLTFLoaderExtension));
  107899. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  107900. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  107901. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107902. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107903. })(BABYLON || (BABYLON = {}));
  107904. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  107905. var BABYLON;
  107906. (function (BABYLON) {
  107907. var GLTF2;
  107908. (function (GLTF2) {
  107909. var Extensions;
  107910. (function (Extensions) {
  107911. var NAME = "MSFT_sRGBFactors";
  107912. /** @hidden */
  107913. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  107914. __extends(MSFT_sRGBFactors, _super);
  107915. function MSFT_sRGBFactors() {
  107916. var _this = _super !== null && _super.apply(this, arguments) || this;
  107917. _this.name = NAME;
  107918. return _this;
  107919. }
  107920. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  107921. var _this = this;
  107922. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  107923. if (value) {
  107924. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  107925. if (!babylonMaterial.albedoTexture) {
  107926. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  107927. }
  107928. if (!babylonMaterial.reflectivityTexture) {
  107929. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  107930. }
  107931. assign(babylonMaterial);
  107932. });
  107933. }
  107934. return null;
  107935. });
  107936. };
  107937. return MSFT_sRGBFactors;
  107938. }(GLTF2.GLTFLoaderExtension));
  107939. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  107940. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  107941. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107942. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107943. })(BABYLON || (BABYLON = {}));
  107944. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  107945. var BABYLON;
  107946. (function (BABYLON) {
  107947. var GLTF2;
  107948. (function (GLTF2) {
  107949. var Extensions;
  107950. (function (Extensions) {
  107951. var NAME = "KHR_draco_mesh_compression";
  107952. /**
  107953. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  107954. */
  107955. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  107956. __extends(KHR_draco_mesh_compression, _super);
  107957. function KHR_draco_mesh_compression(loader) {
  107958. var _this = _super.call(this, loader) || this;
  107959. _this.name = NAME;
  107960. _this._dracoCompression = null;
  107961. // Disable extension if decoder is not available.
  107962. if (!BABYLON.DracoCompression.DecoderAvailable) {
  107963. _this.enabled = false;
  107964. }
  107965. return _this;
  107966. }
  107967. KHR_draco_mesh_compression.prototype.dispose = function () {
  107968. if (this._dracoCompression) {
  107969. this._dracoCompression.dispose();
  107970. }
  107971. _super.prototype.dispose.call(this);
  107972. };
  107973. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  107974. var _this = this;
  107975. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  107976. if (primitive.mode != undefined) {
  107977. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  107978. primitive.mode !== 4 /* TRIANGLES */) {
  107979. throw new Error(context + ": Unsupported mode " + primitive.mode);
  107980. }
  107981. // TODO: handle triangle strips
  107982. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  107983. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  107984. }
  107985. }
  107986. var attributes = {};
  107987. var loadAttribute = function (name, kind) {
  107988. var uniqueId = extension.attributes[name];
  107989. if (uniqueId == undefined) {
  107990. return;
  107991. }
  107992. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  107993. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  107994. babylonMesh._delayInfo.push(kind);
  107995. }
  107996. attributes[kind] = uniqueId;
  107997. };
  107998. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  107999. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  108000. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  108001. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  108002. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  108003. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  108004. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  108005. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  108006. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  108007. if (!bufferView._dracoBabylonGeometry) {
  108008. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  108009. if (!_this._dracoCompression) {
  108010. _this._dracoCompression = new BABYLON.DracoCompression();
  108011. }
  108012. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  108013. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  108014. babylonVertexData.applyToGeometry(babylonGeometry);
  108015. return babylonGeometry;
  108016. }).catch(function (error) {
  108017. throw new Error(context + ": " + error.message);
  108018. });
  108019. });
  108020. }
  108021. return bufferView._dracoBabylonGeometry;
  108022. });
  108023. };
  108024. return KHR_draco_mesh_compression;
  108025. }(GLTF2.GLTFLoaderExtension));
  108026. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  108027. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  108028. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108029. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108030. })(BABYLON || (BABYLON = {}));
  108031. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  108032. var BABYLON;
  108033. (function (BABYLON) {
  108034. var GLTF2;
  108035. (function (GLTF2) {
  108036. var Extensions;
  108037. (function (Extensions) {
  108038. var NAME = "KHR_materials_pbrSpecularGlossiness";
  108039. /**
  108040. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  108041. */
  108042. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  108043. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  108044. function KHR_materials_pbrSpecularGlossiness() {
  108045. var _this = _super !== null && _super.apply(this, arguments) || this;
  108046. _this.name = NAME;
  108047. return _this;
  108048. }
  108049. /** @hidden */
  108050. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108051. var _this = this;
  108052. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  108053. material._babylonData = material._babylonData || {};
  108054. var babylonData = material._babylonData[babylonDrawMode];
  108055. if (!babylonData) {
  108056. var promises = new Array();
  108057. var name_1 = material.name || "materialSG_" + material._index;
  108058. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  108059. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  108060. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  108061. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108062. babylonData = {
  108063. material: babylonMaterial,
  108064. meshes: [],
  108065. loaded: Promise.all(promises).then(function () { })
  108066. };
  108067. material._babylonData[babylonDrawMode] = babylonData;
  108068. }
  108069. babylonData.meshes.push(babylonMesh);
  108070. assign(babylonData.material);
  108071. return babylonData.loaded;
  108072. });
  108073. };
  108074. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  108075. var promises = new Array();
  108076. if (properties.diffuseFactor) {
  108077. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  108078. babylonMaterial.alpha = properties.diffuseFactor[3];
  108079. }
  108080. else {
  108081. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108082. }
  108083. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  108084. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  108085. if (properties.diffuseTexture) {
  108086. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  108087. babylonMaterial.albedoTexture = texture;
  108088. }));
  108089. }
  108090. if (properties.specularGlossinessTexture) {
  108091. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  108092. babylonMaterial.reflectivityTexture = texture;
  108093. }));
  108094. babylonMaterial.reflectivityTexture.hasAlpha = true;
  108095. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  108096. }
  108097. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  108098. return Promise.all(promises).then(function () { });
  108099. };
  108100. return KHR_materials_pbrSpecularGlossiness;
  108101. }(GLTF2.GLTFLoaderExtension));
  108102. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  108103. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  108104. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108105. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108106. })(BABYLON || (BABYLON = {}));
  108107. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  108108. var BABYLON;
  108109. (function (BABYLON) {
  108110. var GLTF2;
  108111. (function (GLTF2) {
  108112. var Extensions;
  108113. (function (Extensions) {
  108114. var NAME = "KHR_materials_unlit";
  108115. /**
  108116. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  108117. */
  108118. var KHR_materials_unlit = /** @class */ (function (_super) {
  108119. __extends(KHR_materials_unlit, _super);
  108120. function KHR_materials_unlit() {
  108121. var _this = _super !== null && _super.apply(this, arguments) || this;
  108122. _this.name = NAME;
  108123. return _this;
  108124. }
  108125. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  108126. var _this = this;
  108127. return this._loadExtensionAsync(context, material, function () {
  108128. material._babylonData = material._babylonData || {};
  108129. var babylonData = material._babylonData[babylonDrawMode];
  108130. if (!babylonData) {
  108131. var name_1 = material.name || "materialUnlit_" + material._index;
  108132. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  108133. babylonMaterial.unlit = true;
  108134. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  108135. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  108136. babylonData = {
  108137. material: babylonMaterial,
  108138. meshes: [],
  108139. loaded: promise
  108140. };
  108141. material._babylonData[babylonDrawMode] = babylonData;
  108142. }
  108143. babylonData.meshes.push(babylonMesh);
  108144. assign(babylonData.material);
  108145. return babylonData.loaded;
  108146. });
  108147. };
  108148. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  108149. var promises = new Array();
  108150. // Ensure metallic workflow
  108151. babylonMaterial.metallic = 1;
  108152. babylonMaterial.roughness = 1;
  108153. var properties = material.pbrMetallicRoughness;
  108154. if (properties) {
  108155. if (properties.baseColorFactor) {
  108156. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  108157. babylonMaterial.alpha = properties.baseColorFactor[3];
  108158. }
  108159. else {
  108160. babylonMaterial.albedoColor = BABYLON.Color3.White();
  108161. }
  108162. if (properties.baseColorTexture) {
  108163. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  108164. babylonMaterial.albedoTexture = texture;
  108165. }));
  108166. }
  108167. }
  108168. if (material.doubleSided) {
  108169. babylonMaterial.backFaceCulling = false;
  108170. babylonMaterial.twoSidedLighting = true;
  108171. }
  108172. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  108173. return Promise.all(promises).then(function () { });
  108174. };
  108175. return KHR_materials_unlit;
  108176. }(GLTF2.GLTFLoaderExtension));
  108177. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  108178. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  108179. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108180. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108181. })(BABYLON || (BABYLON = {}));
  108182. //# sourceMappingURL=KHR_materials_unlit.js.map
  108183. var BABYLON;
  108184. (function (BABYLON) {
  108185. var GLTF2;
  108186. (function (GLTF2) {
  108187. var Extensions;
  108188. (function (Extensions) {
  108189. var NAME = "KHR_lights";
  108190. var LightType;
  108191. (function (LightType) {
  108192. LightType["AMBIENT"] = "ambient";
  108193. LightType["DIRECTIONAL"] = "directional";
  108194. LightType["POINT"] = "point";
  108195. LightType["SPOT"] = "spot";
  108196. })(LightType || (LightType = {}));
  108197. /**
  108198. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  108199. */
  108200. var KHR_lights = /** @class */ (function (_super) {
  108201. __extends(KHR_lights, _super);
  108202. function KHR_lights() {
  108203. var _this = _super !== null && _super.apply(this, arguments) || this;
  108204. _this.name = NAME;
  108205. return _this;
  108206. }
  108207. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  108208. var _this = this;
  108209. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  108210. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  108211. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  108212. if (light.type !== LightType.AMBIENT) {
  108213. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  108214. }
  108215. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  108216. return promise;
  108217. });
  108218. };
  108219. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  108220. var _this = this;
  108221. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  108222. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  108223. var babylonLight;
  108224. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  108225. var name = node._babylonMesh.name;
  108226. switch (light.type) {
  108227. case LightType.AMBIENT: {
  108228. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  108229. }
  108230. case LightType.DIRECTIONAL: {
  108231. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  108232. break;
  108233. }
  108234. case LightType.POINT: {
  108235. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  108236. break;
  108237. }
  108238. case LightType.SPOT: {
  108239. var spotLight = light;
  108240. // TODO: support inner and outer cone angles
  108241. //const innerConeAngle = spotLight.innerConeAngle || 0;
  108242. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  108243. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  108244. break;
  108245. }
  108246. default: {
  108247. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  108248. }
  108249. }
  108250. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  108251. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  108252. babylonLight.parent = node._babylonMesh;
  108253. return promise;
  108254. });
  108255. };
  108256. Object.defineProperty(KHR_lights.prototype, "_lights", {
  108257. get: function () {
  108258. var extensions = this._loader._gltf.extensions;
  108259. if (!extensions || !extensions[this.name]) {
  108260. throw new Error("#/extensions: '" + this.name + "' not found");
  108261. }
  108262. var extension = extensions[this.name];
  108263. return extension.lights;
  108264. },
  108265. enumerable: true,
  108266. configurable: true
  108267. });
  108268. return KHR_lights;
  108269. }(GLTF2.GLTFLoaderExtension));
  108270. Extensions.KHR_lights = KHR_lights;
  108271. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  108272. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108273. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108274. })(BABYLON || (BABYLON = {}));
  108275. var BABYLON;
  108276. (function (BABYLON) {
  108277. var GLTF2;
  108278. (function (GLTF2) {
  108279. var Extensions;
  108280. (function (Extensions) {
  108281. var NAME = "KHR_texture_transform";
  108282. /**
  108283. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  108284. */
  108285. var KHR_texture_transform = /** @class */ (function (_super) {
  108286. __extends(KHR_texture_transform, _super);
  108287. function KHR_texture_transform() {
  108288. var _this = _super !== null && _super.apply(this, arguments) || this;
  108289. _this.name = NAME;
  108290. return _this;
  108291. }
  108292. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  108293. var _this = this;
  108294. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  108295. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  108296. if (extension.offset) {
  108297. babylonTexture.uOffset = extension.offset[0];
  108298. babylonTexture.vOffset = extension.offset[1];
  108299. }
  108300. // Always rotate around the origin.
  108301. babylonTexture.uRotationCenter = 0;
  108302. babylonTexture.vRotationCenter = 0;
  108303. if (extension.rotation) {
  108304. babylonTexture.wAng = -extension.rotation;
  108305. }
  108306. if (extension.scale) {
  108307. babylonTexture.uScale = extension.scale[0];
  108308. babylonTexture.vScale = extension.scale[1];
  108309. }
  108310. if (extension.texCoord != undefined) {
  108311. babylonTexture.coordinatesIndex = extension.texCoord;
  108312. }
  108313. assign(babylonTexture);
  108314. });
  108315. });
  108316. };
  108317. return KHR_texture_transform;
  108318. }(GLTF2.GLTFLoaderExtension));
  108319. Extensions.KHR_texture_transform = KHR_texture_transform;
  108320. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  108321. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  108322. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  108323. })(BABYLON || (BABYLON = {}));
  108324. return BABYLON;
  108325. });
  108326. /***/ }),
  108327. /* 24 */
  108328. /***/ (function(module, exports, __webpack_require__) {
  108329. module.exports = __webpack_require__(6);
  108330. /***/ }),
  108331. /* 25 */
  108332. /***/ (function(module, exports) {
  108333. var g;
  108334. // This works in non-strict mode
  108335. g = (function() {
  108336. return this;
  108337. })();
  108338. try {
  108339. // This works if eval is allowed (see CSP)
  108340. g = g || Function("return this")() || (1,eval)("this");
  108341. } catch(e) {
  108342. // This works if the window reference is available
  108343. if(typeof window === "object")
  108344. g = window;
  108345. }
  108346. // g can still be undefined, but nothing to do about it...
  108347. // We return undefined, instead of nothing here, so it's
  108348. // easier to handle this case. if(!global) { ...}
  108349. module.exports = g;
  108350. /***/ }),
  108351. /* 26 */
  108352. /***/ (function(module, exports) {
  108353. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  108354. module.exports = CANNON;
  108355. /***/ }),
  108356. /* 27 */
  108357. /***/ (function(module, exports) {
  108358. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  108359. module.exports = OIMO;
  108360. /***/ }),
  108361. /* 28 */
  108362. /***/ (function(module, exports) {
  108363. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  108364. module.exports = earcut;
  108365. /***/ }),
  108366. /* 29 */
  108367. /***/ (function(module, exports, __webpack_require__) {
  108368. "use strict";
  108369. Object.defineProperty(exports, "__esModule", { value: true });
  108370. var babylonjs_1 = __webpack_require__(0);
  108371. var configuration_1 = __webpack_require__(11);
  108372. var viewerModel_1 = __webpack_require__(4);
  108373. var helper_1 = __webpack_require__(2);
  108374. var viewerLabs_1 = __webpack_require__(31);
  108375. var _1 = __webpack_require__(33);
  108376. var SceneManager = /** @class */ (function () {
  108377. function SceneManager(_viewer) {
  108378. var _this = this;
  108379. this._viewer = _viewer;
  108380. this._animationBlendingEnabled = true;
  108381. this._mainColor = babylonjs_1.Color3.White();
  108382. this._reflectionColor = babylonjs_1.Color3.White();
  108383. this._white = babylonjs_1.Color3.White();
  108384. this._forceShadowUpdate = false;
  108385. this._processShadows = true;
  108386. this._groundEnabled = true;
  108387. this._groundMirrorEnabled = true;
  108388. this._defaultRenderingPipelineEnabled = false;
  108389. this._defaultRenderingPipelineShouldBuild = true;
  108390. // default from rendering pipeline
  108391. this._bloomEnabled = false;
  108392. // default from rendering pipeline
  108393. this._fxaaEnabled = false;
  108394. this._focusOnModel = function (model) {
  108395. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  108396. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  108397. var halfSizeVec = sizeVec.scale(0.5);
  108398. var center = boundingInfo.min.add(halfSizeVec);
  108399. _this.camera.setTarget(center);
  108400. _this.camera.alpha = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.alpha) || _this.camera.alpha;
  108401. _this.camera.beta = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.beta) || _this.camera.beta;
  108402. _this.camera.radius = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.radius) || _this.camera.radius;
  108403. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  108404. // casting ais safe, due to the constraints tested before
  108405. (<ShadowLight>light).setDirectionToTarget(center);
  108406. });*/
  108407. };
  108408. this._cameraBehaviorMapping = {};
  108409. this.models = [];
  108410. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  108411. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  108412. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  108413. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  108414. this.onSceneInitObservable = new babylonjs_1.Observable();
  108415. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  108416. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  108417. this._viewer.onEngineInitObservable.add(function () {
  108418. _this._handleHardwareLimitations();
  108419. });
  108420. this.labs = new viewerLabs_1.ViewerLabs(this);
  108421. this.onSceneInitObservable.add(function (scene) {
  108422. var updateShadows = function () {
  108423. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  108424. var light = _a[_i];
  108425. var generator = light.getShadowGenerator();
  108426. if (generator) {
  108427. // Processing shadows if animates
  108428. var shadowMap = generator.getShadowMap();
  108429. if (shadowMap) {
  108430. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  108431. }
  108432. }
  108433. }
  108434. };
  108435. scene.registerBeforeRender(function () {
  108436. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  108437. // make sure all models are loaded
  108438. updateShadows();
  108439. _this._forceShadowUpdate = false;
  108440. }
  108441. else if (!(_this.models.every(function (model) {
  108442. if (!model.shadowsRenderedAfterLoad) {
  108443. model.shadowsRenderedAfterLoad = true;
  108444. return false;
  108445. }
  108446. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  108447. }))) {
  108448. updateShadows();
  108449. }
  108450. });
  108451. return _this._viewer.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  108452. });
  108453. this._viewer.onModelLoadedObservable.add(function (model) {
  108454. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  108455. var light = _a[_i];
  108456. var generator = light.getShadowGenerator();
  108457. if (generator) {
  108458. // Processing shadows if animates
  108459. var shadowMap = generator.getShadowMap();
  108460. if (shadowMap) {
  108461. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  108462. }
  108463. }
  108464. }
  108465. _this._focusOnModel(model);
  108466. });
  108467. }
  108468. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  108469. get: function () {
  108470. return this._defaultRenderingPipeline;
  108471. },
  108472. enumerable: true,
  108473. configurable: true
  108474. });
  108475. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  108476. /**
  108477. * Returns a boolean representing HDR support
  108478. */
  108479. get: function () {
  108480. return this._hdrSupport;
  108481. },
  108482. enumerable: true,
  108483. configurable: true
  108484. });
  108485. Object.defineProperty(SceneManager.prototype, "mainColor", {
  108486. /**
  108487. * Return the main color defined in the configuration.
  108488. */
  108489. get: function () {
  108490. return this._mainColor;
  108491. },
  108492. enumerable: true,
  108493. configurable: true
  108494. });
  108495. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  108496. get: function () {
  108497. return this._reflectionColor;
  108498. },
  108499. enumerable: true,
  108500. configurable: true
  108501. });
  108502. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  108503. get: function () {
  108504. return this._animationBlendingEnabled;
  108505. },
  108506. set: function (value) {
  108507. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  108508. this.scene.animationPropertiesOverride.enableBlending = value;
  108509. this._animationBlendingEnabled = value;
  108510. },
  108511. enumerable: true,
  108512. configurable: true
  108513. });
  108514. Object.defineProperty(SceneManager.prototype, "processShadows", {
  108515. /**
  108516. * The flag defining whether shadows are rendered constantly or once.
  108517. */
  108518. get: function () {
  108519. return this._processShadows;
  108520. },
  108521. /**
  108522. * Should shadows be rendered every frame, or only once and stop.
  108523. * This can be used to optimize a scene.
  108524. *
  108525. * Not that the shadows will NOT disapear but will remain in place.
  108526. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  108527. */
  108528. set: function (process) {
  108529. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  108530. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  108531. var light = _a[_i];
  108532. var generator = light.getShadowGenerator();
  108533. if (generator) {
  108534. var shadowMap = generator.getShadowMap();
  108535. if (shadowMap) {
  108536. shadowMap.refreshRate = refreshType;
  108537. }
  108538. }
  108539. }
  108540. this._processShadows = process;
  108541. },
  108542. enumerable: true,
  108543. configurable: true
  108544. });
  108545. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  108546. get: function () {
  108547. return this._groundEnabled;
  108548. },
  108549. set: function (newValue) {
  108550. if (newValue === this._groundEnabled)
  108551. return;
  108552. this._groundEnabled = newValue;
  108553. if (this.environmentHelper && this.environmentHelper.ground) {
  108554. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  108555. }
  108556. },
  108557. enumerable: true,
  108558. configurable: true
  108559. });
  108560. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  108561. /**
  108562. * gets wether the reflection is disabled.
  108563. */
  108564. get: function () {
  108565. return this._groundMirrorEnabled;
  108566. },
  108567. /**
  108568. * sets wether the reflection is disabled.
  108569. */
  108570. set: function (value) {
  108571. if (this._groundMirrorEnabled === value) {
  108572. return;
  108573. }
  108574. this._groundMirrorEnabled = value;
  108575. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  108576. if (!value) {
  108577. this.environmentHelper.groundMaterial.reflectionTexture = null;
  108578. }
  108579. else {
  108580. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  108581. }
  108582. }
  108583. },
  108584. enumerable: true,
  108585. configurable: true
  108586. });
  108587. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  108588. get: function () {
  108589. return this._defaultRenderingPipelineEnabled;
  108590. },
  108591. set: function (value) {
  108592. if (value === this._defaultRenderingPipelineEnabled) {
  108593. return;
  108594. }
  108595. this._defaultRenderingPipelineEnabled = value;
  108596. this._rebuildPostprocesses();
  108597. if (this._defaultRenderingPipeline) {
  108598. this._defaultRenderingPipelineShouldBuild = false;
  108599. this._defaultRenderingPipeline.prepare();
  108600. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  108601. }
  108602. },
  108603. enumerable: true,
  108604. configurable: true
  108605. });
  108606. /**
  108607. * Sets the engine flags to unlock all babylon features.
  108608. * Can also be configured using the scene.flags configuration object
  108609. */
  108610. SceneManager.prototype.unlockBabylonFeatures = function () {
  108611. this.scene.shadowsEnabled = true;
  108612. this.scene.particlesEnabled = true;
  108613. this.scene.postProcessesEnabled = true;
  108614. this.scene.collisionsEnabled = true;
  108615. this.scene.lightsEnabled = true;
  108616. this.scene.texturesEnabled = true;
  108617. this.scene.lensFlaresEnabled = true;
  108618. this.scene.proceduralTexturesEnabled = true;
  108619. this.scene.renderTargetsEnabled = true;
  108620. this.scene.spritesEnabled = true;
  108621. this.scene.skeletonsEnabled = true;
  108622. this.scene.audioEnabled = true;
  108623. };
  108624. /**
  108625. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  108626. */
  108627. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  108628. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  108629. // if the scen exists, dispose it.
  108630. if (this.scene) {
  108631. this.scene.dispose();
  108632. }
  108633. // create a new scene
  108634. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  108635. // set a default PBR material
  108636. if (!sceneConfiguration.defaultMaterial) {
  108637. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  108638. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  108639. defaultMaterial.microSurface = 0.6;
  108640. if (this.scene.defaultMaterial) {
  108641. this.scene.defaultMaterial.dispose();
  108642. }
  108643. this.scene.defaultMaterial = defaultMaterial;
  108644. }
  108645. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  108646. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  108647. this._mainColor = babylonjs_1.Color3.White();
  108648. /*if (sceneConfiguration.glow) {
  108649. let options: Partial<IGlowLayerOptions> = {
  108650. mainTextureFixedSize: 512
  108651. };
  108652. if (typeof sceneConfiguration.glow === 'object') {
  108653. options = sceneConfiguration.glow
  108654. }
  108655. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  108656. }*/
  108657. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  108658. };
  108659. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  108660. if (clearModels === void 0) { clearModels = true; }
  108661. if (clearLights === void 0) { clearLights = false; }
  108662. if (clearModels) {
  108663. this.models.forEach(function (m) { return m.dispose(); });
  108664. this.models.length = 0;
  108665. }
  108666. if (clearLights) {
  108667. this.scene.lights.forEach(function (l) { return l.dispose(); });
  108668. }
  108669. };
  108670. /**
  108671. * This will update the scene's configuration, including camera, lights, environment.
  108672. * @param newConfiguration the delta that should be configured. This includes only the changes
  108673. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  108674. */
  108675. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration) {
  108676. var _this = this;
  108677. if (newConfiguration.lab) {
  108678. if (newConfiguration.lab.assetsRootURL) {
  108679. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  108680. }
  108681. }
  108682. // update scene configuration
  108683. if (newConfiguration.scene) {
  108684. this._configureScene(newConfiguration.scene);
  108685. }
  108686. // optimizer
  108687. if (newConfiguration.optimizer !== undefined) {
  108688. this._configureOptimizer(newConfiguration.optimizer);
  108689. }
  108690. // configure model
  108691. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  108692. this._configureModel(newConfiguration.model);
  108693. }*/
  108694. // lights
  108695. this._configureLights(newConfiguration.lights);
  108696. // environment
  108697. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  108698. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  108699. }
  108700. // camera
  108701. this._configureCamera(newConfiguration.camera);
  108702. if (newConfiguration.lab) {
  108703. if (newConfiguration.lab.environmentMap) {
  108704. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  108705. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  108706. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  108707. });
  108708. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  108709. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  108710. }
  108711. }
  108712. // rendering piplines
  108713. if (newConfiguration.lab.defaultRenderingPipelines) {
  108714. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  108715. if (typeof pipelineConfig === 'boolean') {
  108716. this.defaultRenderingPipelineEnabled = pipelineConfig;
  108717. }
  108718. else {
  108719. this.defaultRenderingPipelineEnabled = true;
  108720. }
  108721. }
  108722. if (newConfiguration.lab.environmentMainColor) {
  108723. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  108724. this.environmentHelper.setMainColor(mainColor);
  108725. }
  108726. if (newConfiguration.lab.globalLightRotation !== undefined) {
  108727. // rotate all lights that are shadow lights
  108728. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  108729. // casting and '!' are safe, due to the constraints tested before
  108730. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  108731. });
  108732. this._forceShadowUpdate = true;
  108733. }
  108734. }
  108735. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  108736. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  108737. }
  108738. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  108739. this._defaultRenderingPipelineShouldBuild = false;
  108740. this._defaultRenderingPipeline.prepare();
  108741. }
  108742. };
  108743. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  108744. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  108745. if (this._defaultRenderingPipeline) {
  108746. this._defaultRenderingPipeline.dispose();
  108747. this._defaultRenderingPipeline = null;
  108748. this.scene.autoClearDepthAndStencil = true;
  108749. this.scene.autoClear = true;
  108750. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  108751. }
  108752. return;
  108753. }
  108754. var pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  108755. if (pipelineConfig) {
  108756. if (!this._defaultRenderingPipeline) {
  108757. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  108758. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  108759. }
  108760. this.scene.autoClear = false;
  108761. this.scene.autoClearDepthAndStencil = false;
  108762. this._defaultRenderingPipelineShouldBuild = true;
  108763. var bloomEnabled = this._bloomEnabled;
  108764. if (typeof pipelineConfig !== 'boolean') {
  108765. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  108766. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  108767. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  108768. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  108769. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  108770. }
  108771. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  108772. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  108773. }
  108774. };
  108775. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  108776. get: function () {
  108777. return this._bloomEnabled;
  108778. },
  108779. set: function (value) {
  108780. if (this._bloomEnabled === value) {
  108781. return;
  108782. }
  108783. this._bloomEnabled = value;
  108784. this._rebuildPostprocesses();
  108785. if (this._defaultRenderingPipeline) {
  108786. this._defaultRenderingPipelineShouldBuild = false;
  108787. this._defaultRenderingPipeline.prepare();
  108788. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  108789. }
  108790. },
  108791. enumerable: true,
  108792. configurable: true
  108793. });
  108794. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  108795. get: function () {
  108796. return this._fxaaEnabled;
  108797. },
  108798. set: function (value) {
  108799. if (this._fxaaEnabled === value) {
  108800. return;
  108801. }
  108802. this._fxaaEnabled = value;
  108803. this._rebuildPostprocesses();
  108804. if (this._defaultRenderingPipeline) {
  108805. this._defaultRenderingPipelineShouldBuild = false;
  108806. this._defaultRenderingPipeline.prepare();
  108807. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  108808. }
  108809. },
  108810. enumerable: true,
  108811. configurable: true
  108812. });
  108813. /**
  108814. * internally configure the scene using the provided configuration.
  108815. * The scene will not be recreated, but just updated.
  108816. * @param sceneConfig the (new) scene configuration
  108817. */
  108818. SceneManager.prototype._configureScene = function (sceneConfig) {
  108819. // sanity check!
  108820. if (!this.scene) {
  108821. return;
  108822. }
  108823. var cc = sceneConfig.clearColor;
  108824. var oldcc = this.scene.clearColor;
  108825. if (cc) {
  108826. if (cc.r !== undefined) {
  108827. oldcc.r = cc.r;
  108828. }
  108829. if (cc.g !== undefined) {
  108830. oldcc.g = cc.g;
  108831. }
  108832. if (cc.b !== undefined) {
  108833. oldcc.b = cc.b;
  108834. }
  108835. if (cc.a !== undefined) {
  108836. oldcc.a = cc.a;
  108837. }
  108838. }
  108839. // image processing configuration - optional.
  108840. if (sceneConfig.imageProcessingConfiguration) {
  108841. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  108842. }
  108843. //animation properties override
  108844. if (sceneConfig.animationPropertiesOverride) {
  108845. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  108846. }
  108847. if (sceneConfig.environmentTexture) {
  108848. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  108849. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  108850. this.scene.environmentTexture.dispose();
  108851. }
  108852. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  108853. this.scene.environmentTexture = environmentTexture;
  108854. }
  108855. }
  108856. if (sceneConfig.debug === true) {
  108857. this.scene.debugLayer.show();
  108858. }
  108859. else if (sceneConfig.debug === false) {
  108860. if (this.scene.debugLayer.isVisible()) {
  108861. this.scene.debugLayer.hide();
  108862. }
  108863. }
  108864. if (sceneConfig.disableHdr) {
  108865. this._handleHardwareLimitations(false);
  108866. }
  108867. else {
  108868. this._handleHardwareLimitations(true);
  108869. }
  108870. if (sceneConfig.renderInBackground !== undefined) {
  108871. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  108872. }
  108873. if (this.camera && sceneConfig.disableCameraControl) {
  108874. this.camera.detachControl(this._viewer.canvas);
  108875. }
  108876. else if (this.camera && sceneConfig.disableCameraControl === false) {
  108877. this.camera.attachControl(this._viewer.canvas);
  108878. }
  108879. // process mainColor changes:
  108880. if (sceneConfig.mainColor) {
  108881. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  108882. var mc = sceneConfig.mainColor;
  108883. if (mc.r !== undefined) {
  108884. this._mainColor.r = mc.r;
  108885. }
  108886. if (mc.g !== undefined) {
  108887. this._mainColor.g = mc.g;
  108888. }
  108889. if (mc.b !== undefined) {
  108890. this._mainColor.b = mc.b;
  108891. }
  108892. this._reflectionColor.copyFrom(this.mainColor);
  108893. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  108894. // reflection color
  108895. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  108896. this._reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this._reflectionColor);
  108897. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  108898. this._reflectionColor.copyFrom(tmpColor3);
  108899. //update the environment, if exists
  108900. if (this.environmentHelper) {
  108901. if (this.environmentHelper.groundMaterial) {
  108902. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  108903. }
  108904. if (this.environmentHelper.skyboxMaterial) {
  108905. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  108906. }
  108907. }
  108908. }
  108909. if (sceneConfig.defaultMaterial) {
  108910. var conf = sceneConfig.defaultMaterial;
  108911. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  108912. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  108913. this.scene.defaultMaterial.dispose();
  108914. if (conf.materialType === 'standard') {
  108915. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  108916. }
  108917. else {
  108918. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  108919. }
  108920. }
  108921. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  108922. }
  108923. if (sceneConfig.flags) {
  108924. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  108925. }
  108926. this.onSceneConfiguredObservable.notifyObservers({
  108927. sceneManager: this,
  108928. object: this.scene,
  108929. newConfiguration: sceneConfig
  108930. });
  108931. };
  108932. /**
  108933. * Configure the scene optimizer.
  108934. * The existing scene optimizer will be disposed and a new one will be created.
  108935. * @param optimizerConfig the (new) optimizer configuration
  108936. */
  108937. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  108938. var _this = this;
  108939. if (typeof optimizerConfig === 'boolean') {
  108940. if (this.sceneOptimizer) {
  108941. this.sceneOptimizer.stop();
  108942. this.sceneOptimizer.dispose();
  108943. delete this.sceneOptimizer;
  108944. }
  108945. if (optimizerConfig) {
  108946. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  108947. this.sceneOptimizer.start();
  108948. }
  108949. }
  108950. else {
  108951. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  108952. // check for degradation
  108953. if (optimizerConfig.degradation) {
  108954. switch (optimizerConfig.degradation) {
  108955. case "low":
  108956. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  108957. break;
  108958. case "moderate":
  108959. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  108960. break;
  108961. case "hight":
  108962. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  108963. break;
  108964. }
  108965. }
  108966. if (this.sceneOptimizer) {
  108967. this.sceneOptimizer.stop();
  108968. this.sceneOptimizer.dispose();
  108969. }
  108970. if (optimizerConfig.custom) {
  108971. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  108972. if (customOptimizer_1) {
  108973. optimizerOptions.addCustomOptimization(function () {
  108974. return customOptimizer_1(_this._viewer);
  108975. }, function () {
  108976. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  108977. });
  108978. }
  108979. }
  108980. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  108981. this.sceneOptimizer.start();
  108982. }
  108983. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  108984. sceneManager: this,
  108985. object: this.sceneOptimizer,
  108986. newConfiguration: optimizerConfig
  108987. });
  108988. };
  108989. /**
  108990. * configure all models using the configuration.
  108991. * @param modelConfiguration the configuration to use to reconfigure the models
  108992. */
  108993. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  108994. this.models.forEach(model => {
  108995. model.updateConfiguration(modelConfiguration);
  108996. });
  108997. this.onModelsConfiguredObservable.notifyObservers({
  108998. sceneManager: this,
  108999. object: this.models,
  109000. newConfiguration: modelConfiguration
  109001. });
  109002. }*/
  109003. /**
  109004. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  109005. * @param cameraConfig the new camera configuration
  109006. * @param model optionally use the model to configure the camera.
  109007. */
  109008. SceneManager.prototype._configureCamera = function (cameraConfig) {
  109009. var _this = this;
  109010. if (cameraConfig === void 0) { cameraConfig = {}; }
  109011. if (!this.scene.activeCamera) {
  109012. var attachControl = true;
  109013. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  109014. attachControl = false;
  109015. }
  109016. this.scene.createDefaultCamera(true, true, attachControl);
  109017. this.camera = this.scene.activeCamera;
  109018. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  109019. }
  109020. if (cameraConfig.position) {
  109021. var newPosition = this.camera.position.clone();
  109022. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  109023. this.camera.setPosition(newPosition);
  109024. }
  109025. if (cameraConfig.target) {
  109026. var newTarget = this.camera.target.clone();
  109027. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  109028. this.camera.setTarget(newTarget);
  109029. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  109030. this._focusOnModel(this.models[0]);
  109031. }*/
  109032. if (cameraConfig.rotation) {
  109033. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  109034. }
  109035. if (cameraConfig.behaviors) {
  109036. for (var name_1 in cameraConfig.behaviors) {
  109037. if (cameraConfig.behaviors[name_1] !== undefined) {
  109038. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  109039. }
  109040. }
  109041. }
  109042. ;
  109043. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  109044. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  109045. });
  109046. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  109047. var sceneDiagonalLenght = sceneDiagonal.length();
  109048. if (isFinite(sceneDiagonalLenght))
  109049. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  109050. else {
  109051. this.camera.upperRadiusLimit = 10;
  109052. }
  109053. // sanity check!
  109054. if (this.scene.imageProcessingConfiguration) {
  109055. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  109056. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  109057. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._viewer.configuration);
  109058. }
  109059. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  109060. this.onCameraConfiguredObservable.notifyObservers({
  109061. sceneManager: this,
  109062. object: this.camera,
  109063. newConfiguration: cameraConfig
  109064. });
  109065. };
  109066. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  109067. var _this = this;
  109068. if (!skyboxConifguration && !groundConfiguration) {
  109069. if (this.environmentHelper) {
  109070. this.environmentHelper.dispose();
  109071. delete this.environmentHelper;
  109072. }
  109073. ;
  109074. }
  109075. else {
  109076. var options = {
  109077. createGround: !!groundConfiguration && this._groundEnabled,
  109078. createSkybox: !!skyboxConifguration,
  109079. setupImageProcessing: false,
  109080. };
  109081. // will that cause problems with model ground configuration?
  109082. /*if (model) {
  109083. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  109084. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  109085. const halfSizeVec = sizeVec.scale(0.5);
  109086. const center = boundingInfo.min.add(halfSizeVec);
  109087. options.groundYBias = -center.y;
  109088. }*/
  109089. if (groundConfiguration) {
  109090. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  109091. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  109092. if (groundSize) {
  109093. options.groundSize = groundSize;
  109094. }
  109095. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  109096. if (groundConfig_1.shadowLevel !== undefined) {
  109097. options.groundShadowLevel = groundConfig_1.shadowLevel;
  109098. }
  109099. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  109100. if (groundConfig_1.texture) {
  109101. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  109102. }
  109103. if (groundConfig_1.color) {
  109104. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  109105. }
  109106. if (groundConfig_1.opacity !== undefined) {
  109107. options.groundOpacity = groundConfig_1.opacity;
  109108. }
  109109. if (groundConfig_1.mirror) {
  109110. options.enableGroundMirror = true;
  109111. // to prevent undefines
  109112. if (typeof groundConfig_1.mirror === "object") {
  109113. if (groundConfig_1.mirror.amount !== undefined)
  109114. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  109115. if (groundConfig_1.mirror.sizeRatio !== undefined)
  109116. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  109117. if (groundConfig_1.mirror.blurKernel !== undefined)
  109118. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  109119. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  109120. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  109121. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  109122. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  109123. if (this._defaultPipelineTextureType !== undefined)
  109124. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  109125. }
  109126. }
  109127. }
  109128. var postInitSkyboxMaterial = false;
  109129. if (skyboxConifguration) {
  109130. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  109131. if (conf.material && conf.material.imageProcessingConfiguration) {
  109132. options.setupImageProcessing = false; // will be configured later manually.
  109133. }
  109134. var skyboxSize = conf.scale;
  109135. if (skyboxSize) {
  109136. options.skyboxSize = skyboxSize;
  109137. }
  109138. options.sizeAuto = !options.skyboxSize;
  109139. if (conf.color) {
  109140. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  109141. }
  109142. if (conf.cubeTexture && conf.cubeTexture.url) {
  109143. if (typeof conf.cubeTexture.url === "string") {
  109144. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  109145. }
  109146. else {
  109147. // init later!
  109148. postInitSkyboxMaterial = true;
  109149. }
  109150. }
  109151. if (conf.material) {
  109152. postInitSkyboxMaterial = true;
  109153. }
  109154. }
  109155. options.setupImageProcessing = false; // TMP
  109156. if (!this.environmentHelper) {
  109157. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  109158. }
  109159. else {
  109160. // unlikely, but there might be a new scene! we need to dispose.
  109161. // get the scene used by the envHelper
  109162. var scene = this.environmentHelper.rootMesh.getScene();
  109163. // is it a different scene? Oh no!
  109164. if (scene !== this.scene) {
  109165. this.environmentHelper.dispose();
  109166. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  109167. }
  109168. else {
  109169. this.environmentHelper.updateOptions(options);
  109170. }
  109171. }
  109172. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  109173. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  109174. }
  109175. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  109176. if (this.environmentHelper.groundMaterial && groundConfig) {
  109177. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  109178. if (groundConfig.material) {
  109179. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  109180. }
  109181. if (this.environmentHelper.groundMirror) {
  109182. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  109183. // TODO user camera exposure value to set the mirror clear color
  109184. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  109185. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  109186. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  109187. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  109188. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  109189. this.environmentHelper.groundMirror.clearColor.a = 1;
  109190. if (!this.groundMirrorEnabled) {
  109191. this.environmentHelper.groundMaterial.reflectionTexture = null;
  109192. }
  109193. }
  109194. }
  109195. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  109196. if (skyboxMaterial) {
  109197. skyboxMaterial._perceptualColor = this.mainColor;
  109198. if (postInitSkyboxMaterial) {
  109199. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  109200. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  109201. }
  109202. }
  109203. }
  109204. }
  109205. this._viewer.onModelLoadedObservable.add(function (model) {
  109206. _this._updateGroundMirrorRenderList(model);
  109207. });
  109208. this.onEnvironmentConfiguredObservable.notifyObservers({
  109209. sceneManager: this,
  109210. object: this.environmentHelper,
  109211. newConfiguration: {
  109212. skybox: skyboxConifguration,
  109213. ground: groundConfiguration
  109214. }
  109215. });
  109216. };
  109217. /**
  109218. * configure the lights.
  109219. *
  109220. * @param lightsConfiguration the (new) light(s) configuration
  109221. * @param model optionally use the model to configure the camera.
  109222. */
  109223. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  109224. var _this = this;
  109225. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  109226. // sanity check!
  109227. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  109228. if (!lightKeys.length) {
  109229. if (!this.scene.lights.length)
  109230. this.scene.createDefaultLight(true);
  109231. }
  109232. else {
  109233. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  109234. // compare to the global (!) configuration object and dispose unneeded:
  109235. var lightsToConfigure_1 = Object.keys(this._viewer.configuration.lights || []);
  109236. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  109237. lightsAvailable_1.forEach(function (lName) {
  109238. if (lightsToConfigure_1.indexOf(lName) === -1) {
  109239. _this.scene.getLightByName(lName).dispose();
  109240. }
  109241. });
  109242. }
  109243. lightKeys.forEach(function (name, idx) {
  109244. var lightConfig = { type: 0 };
  109245. if (typeof lightsConfiguration[name] === 'object') {
  109246. lightConfig = lightsConfiguration[name];
  109247. }
  109248. if (typeof lightsConfiguration[name] === 'number') {
  109249. lightConfig.type = lightsConfiguration[name];
  109250. }
  109251. lightConfig.name = name;
  109252. var light;
  109253. // light is not already available
  109254. if (lightsAvailable_1.indexOf(name) === -1) {
  109255. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  109256. if (!constructor)
  109257. return;
  109258. light = constructor();
  109259. }
  109260. else {
  109261. // available? get it from the scene
  109262. light = _this.scene.getLightByName(name);
  109263. if (typeof lightsConfiguration[name] === 'boolean') {
  109264. lightConfig.type = light.getTypeID();
  109265. }
  109266. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  109267. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  109268. light.dispose();
  109269. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  109270. if (!constructor)
  109271. return;
  109272. light = constructor();
  109273. }
  109274. }
  109275. // if config set the light to false, dispose it.
  109276. if (lightsConfiguration[name] === false) {
  109277. light.dispose();
  109278. return;
  109279. }
  109280. //enabled
  109281. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  109282. light.setEnabled(enabled);
  109283. helper_1.extendClassWithConfig(light, lightConfig);
  109284. //position. Some lights don't support shadows
  109285. if (light instanceof babylonjs_1.ShadowLight) {
  109286. // set default values
  109287. light.shadowMinZ = light.shadowMinZ || 0.2;
  109288. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  109289. if (lightConfig.target) {
  109290. if (light.setDirectionToTarget) {
  109291. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  109292. light.setDirectionToTarget(target);
  109293. }
  109294. }
  109295. else if (lightConfig.direction) {
  109296. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  109297. light.direction = direction;
  109298. }
  109299. var isShadowEnabled = false;
  109300. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  109301. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  109302. isShadowEnabled = true;
  109303. }
  109304. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  109305. var spotLight = light;
  109306. if (lightConfig.spotAngle !== undefined) {
  109307. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  109308. }
  109309. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  109310. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  109311. }
  109312. isShadowEnabled = true;
  109313. }
  109314. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  109315. if (lightConfig.shadowFieldOfView) {
  109316. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  109317. }
  109318. isShadowEnabled = true;
  109319. }
  109320. var shadowGenerator_1 = light.getShadowGenerator();
  109321. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  109322. var bufferSize = lightConfig.shadowBufferSize || 256;
  109323. if (!shadowGenerator_1) {
  109324. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  109325. }
  109326. var blurKernel = _this.getBlurKernel(light, bufferSize);
  109327. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  109328. shadowGenerator_1.blurKernel = blurKernel;
  109329. //override defaults
  109330. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  109331. // add the focues meshes to the shadow list
  109332. _this._viewer.onModelLoadedObservable.add(function (model) {
  109333. _this._updateShadowRenderList(shadowGenerator_1, model);
  109334. });
  109335. //if (model) {
  109336. _this._updateShadowRenderList(shadowGenerator_1);
  109337. //}
  109338. }
  109339. else if (shadowGenerator_1) {
  109340. shadowGenerator_1.dispose();
  109341. }
  109342. }
  109343. });
  109344. // render priority
  109345. var globalLightsConfiguration_1 = this._viewer.configuration.lights || {};
  109346. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  109347. var configuration = globalLightsConfiguration_1[name];
  109348. var light = _this.scene.getLightByName(name);
  109349. // sanity check
  109350. if (!light)
  109351. return;
  109352. light.renderPriority = -idx;
  109353. });
  109354. }
  109355. this.onLightsConfiguredObservable.notifyObservers({
  109356. sceneManager: this,
  109357. object: this.scene.lights,
  109358. newConfiguration: lightsConfiguration
  109359. });
  109360. };
  109361. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  109362. var focusMeshes = model ? model.meshes : this.scene.meshes;
  109363. // add the focues meshes to the shadow list
  109364. var shadownMap = shadowGenerator.getShadowMap();
  109365. if (!shadownMap)
  109366. return;
  109367. if (resetList && shadownMap.renderList) {
  109368. shadownMap.renderList.length = 0;
  109369. }
  109370. else {
  109371. shadownMap.renderList = shadownMap.renderList || [];
  109372. }
  109373. for (var index = 0; index < focusMeshes.length; index++) {
  109374. var mesh = focusMeshes[index];
  109375. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  109376. shadownMap.renderList.push(mesh);
  109377. }
  109378. }
  109379. if (!this._shadowGroundPlane) {
  109380. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  109381. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  109382. shadowGroundPlane.useVertexColors = false;
  109383. //material isn't ever used in rendering, just used to set back face culling
  109384. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  109385. shadowGroundPlane.material.backFaceCulling = false;
  109386. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  109387. shadowGroundPlane.freezeWorldMatrix();
  109388. this._shadowGroundPlane = shadowGroundPlane;
  109389. this.scene.removeMesh(shadowGroundPlane);
  109390. }
  109391. }
  109392. else {
  109393. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  109394. this._shadowGroundPlane.dispose();
  109395. this._shadowGroundPlane = null;
  109396. }
  109397. }
  109398. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  109399. shadownMap.renderList.push(this._shadowGroundPlane);
  109400. }
  109401. };
  109402. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  109403. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  109404. var focusMeshes = model ? model.meshes : this.scene.meshes;
  109405. var renderList = this.environmentHelper.groundMirror.renderList;
  109406. if (resetList) {
  109407. renderList.length = 0;
  109408. }
  109409. for (var index = 0; index < focusMeshes.length; index++) {
  109410. var mesh = focusMeshes[index];
  109411. if (renderList.indexOf(mesh) === -1) {
  109412. renderList.push(mesh);
  109413. }
  109414. }
  109415. }
  109416. };
  109417. /**
  109418. * Gets the shadow map blur kernel according to the light configuration.
  109419. * @param light The light used to generate the shadows
  109420. * @param bufferSize The size of the shadow map
  109421. * @return the kernel blur size
  109422. */
  109423. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  109424. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  109425. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  109426. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  109427. }
  109428. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  109429. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  109430. }
  109431. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  109432. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  109433. }
  109434. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  109435. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  109436. return blurKernel;
  109437. };
  109438. /**
  109439. * Alters render settings to reduce features based on hardware feature limitations
  109440. * @param enableHDR Allows the viewer to run in HDR mode.
  109441. */
  109442. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  109443. if (enableHDR === void 0) { enableHDR = true; }
  109444. //flip rendering settings switches based on hardware support
  109445. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  109446. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  109447. //shadows are disabled if there's not enough varyings for a single shadow
  109448. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  109449. this._maxShadows = 0;
  109450. }
  109451. else {
  109452. this._maxShadows = 3;
  109453. }
  109454. //can we render to any >= 16-bit targets (required for HDR)
  109455. var caps = this._viewer.engine.getCaps();
  109456. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  109457. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  109458. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  109459. if (linearHalfFloatTargets) {
  109460. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  109461. this._shadowGeneratorBias = 0.002;
  109462. }
  109463. else if (linearFloatTargets) {
  109464. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  109465. this._shadowGeneratorBias = 0.001;
  109466. }
  109467. else {
  109468. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  109469. this._shadowGeneratorBias = 0.001;
  109470. }
  109471. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  109472. };
  109473. /**
  109474. * Dispoe the entire viewer including the scene and the engine
  109475. */
  109476. SceneManager.prototype.dispose = function () {
  109477. // this.onCameraConfiguredObservable.clear();
  109478. this.onEnvironmentConfiguredObservable.clear();
  109479. this.onLightsConfiguredObservable.clear();
  109480. this.onModelsConfiguredObservable.clear();
  109481. this.onSceneConfiguredObservable.clear();
  109482. this.onSceneInitObservable.clear();
  109483. this.onSceneOptimizerConfiguredObservable.clear();
  109484. if (this.sceneOptimizer) {
  109485. this.sceneOptimizer.stop();
  109486. this.sceneOptimizer.dispose();
  109487. }
  109488. if (this.environmentHelper) {
  109489. this.environmentHelper.dispose();
  109490. }
  109491. this.models.forEach(function (model) {
  109492. model.dispose();
  109493. });
  109494. if (this._defaultRenderingPipeline) {
  109495. this._defaultRenderingPipeline.dispose();
  109496. }
  109497. this.models.length = 0;
  109498. if (this.scene) {
  109499. this.scene.dispose();
  109500. }
  109501. };
  109502. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  109503. var behavior;
  109504. var type;
  109505. if (typeof behaviorConfig === 'object') {
  109506. type = behaviorConfig.type;
  109507. }
  109508. else if (typeof behaviorConfig === 'number') {
  109509. type = behaviorConfig;
  109510. }
  109511. else {
  109512. type = this._cameraBehaviorMapping[name];
  109513. }
  109514. if (type === undefined)
  109515. return;
  109516. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  109517. var enabled = true;
  109518. if (typeof behaviorConfig === 'boolean') {
  109519. enabled = behaviorConfig;
  109520. }
  109521. // constructing behavior
  109522. switch (type) {
  109523. case 0 /* AUTOROTATION */:
  109524. this.camera.useAutoRotationBehavior = enabled;
  109525. behavior = this.camera.autoRotationBehavior;
  109526. break;
  109527. case 1 /* BOUNCING */:
  109528. this.camera.useBouncingBehavior = enabled;
  109529. behavior = this.camera.bouncingBehavior;
  109530. break;
  109531. case 2 /* FRAMING */:
  109532. this.camera.useFramingBehavior = enabled;
  109533. behavior = this.camera.framingBehavior;
  109534. break;
  109535. default:
  109536. behavior = null;
  109537. break;
  109538. }
  109539. if (behavior) {
  109540. this._cameraBehaviorMapping[name] = type;
  109541. if (typeof behaviorConfig === "object") {
  109542. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  109543. }
  109544. }
  109545. // post attach configuration. Some functionalities require the attached camera.
  109546. switch (type) {
  109547. case 0 /* AUTOROTATION */:
  109548. break;
  109549. case 1 /* BOUNCING */:
  109550. break;
  109551. case 2 /* FRAMING */:
  109552. this._viewer.onModelLoadedObservable.add(function (model) {
  109553. if (config.zoomOnBoundingInfo) {
  109554. behavior.zoomOnMeshHierarchy(model.rootMesh);
  109555. }
  109556. });
  109557. break;
  109558. }
  109559. };
  109560. return SceneManager;
  109561. }());
  109562. exports.SceneManager = SceneManager;
  109563. /***/ }),
  109564. /* 30 */
  109565. /***/ (function(module, exports, __webpack_require__) {
  109566. "use strict";
  109567. Object.defineProperty(exports, "__esModule", { value: true });
  109568. /**
  109569. * Animation play mode enum - is the animation looping or playing once
  109570. */
  109571. var AnimationPlayMode;
  109572. (function (AnimationPlayMode) {
  109573. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  109574. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  109575. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  109576. /**
  109577. * An enum representing the current state of an animation object
  109578. */
  109579. var AnimationState;
  109580. (function (AnimationState) {
  109581. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  109582. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  109583. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  109584. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  109585. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  109586. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  109587. /**
  109588. * The different type of easing functions available
  109589. */
  109590. var EasingFunction;
  109591. (function (EasingFunction) {
  109592. EasingFunction[EasingFunction["Linear"] = 0] = "Linear";
  109593. EasingFunction[EasingFunction["CircleEase"] = 1] = "CircleEase";
  109594. EasingFunction[EasingFunction["BackEase"] = 2] = "BackEase";
  109595. EasingFunction[EasingFunction["BounceEase"] = 3] = "BounceEase";
  109596. EasingFunction[EasingFunction["CubicEase"] = 4] = "CubicEase";
  109597. EasingFunction[EasingFunction["ElasticEase"] = 5] = "ElasticEase";
  109598. EasingFunction[EasingFunction["ExponentialEase"] = 6] = "ExponentialEase";
  109599. EasingFunction[EasingFunction["PowerEase"] = 7] = "PowerEase";
  109600. EasingFunction[EasingFunction["QuadraticEase"] = 8] = "QuadraticEase";
  109601. EasingFunction[EasingFunction["QuarticEase"] = 9] = "QuarticEase";
  109602. EasingFunction[EasingFunction["QuinticEase"] = 10] = "QuinticEase";
  109603. EasingFunction[EasingFunction["SineEase"] = 11] = "SineEase";
  109604. })(EasingFunction = exports.EasingFunction || (exports.EasingFunction = {}));
  109605. /**
  109606. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  109607. * native GroupAnimation class.
  109608. */
  109609. var GroupModelAnimation = /** @class */ (function () {
  109610. /**
  109611. * Create a new GroupModelAnimation object using an AnimationGroup object
  109612. * @param _animationGroup The aniamtion group to base the class on
  109613. */
  109614. function GroupModelAnimation(_animationGroup) {
  109615. var _this = this;
  109616. this._animationGroup = _animationGroup;
  109617. this._state = 0 /* INIT */;
  109618. this._playMode = 1 /* LOOP */;
  109619. this._animationGroup.onAnimationEndObservable.add(function () {
  109620. _this.stop();
  109621. _this._state = 4 /* ENDED */;
  109622. });
  109623. }
  109624. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  109625. /**
  109626. * Get the animation's name
  109627. */
  109628. get: function () {
  109629. return this._animationGroup.name;
  109630. },
  109631. enumerable: true,
  109632. configurable: true
  109633. });
  109634. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  109635. /**
  109636. * Get the current animation's state
  109637. */
  109638. get: function () {
  109639. return this._state;
  109640. },
  109641. enumerable: true,
  109642. configurable: true
  109643. });
  109644. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  109645. /**
  109646. * Gets the speed ratio to use for all animations
  109647. */
  109648. get: function () {
  109649. return this._animationGroup.speedRatio;
  109650. },
  109651. /**
  109652. * Sets the speed ratio to use for all animations
  109653. */
  109654. set: function (value) {
  109655. this._animationGroup.speedRatio = value;
  109656. },
  109657. enumerable: true,
  109658. configurable: true
  109659. });
  109660. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  109661. /**
  109662. * Get the max numbers of frame available in the animation group
  109663. *
  109664. * In correlation to an arry, this would be ".length"
  109665. */
  109666. get: function () {
  109667. return this._animationGroup.to - this._animationGroup.from;
  109668. },
  109669. enumerable: true,
  109670. configurable: true
  109671. });
  109672. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  109673. /**
  109674. * Get the current frame playing right now.
  109675. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  109676. *
  109677. * In correlation to an array, this would be the current index
  109678. */
  109679. get: function () {
  109680. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  109681. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  109682. }
  109683. else {
  109684. return 0;
  109685. }
  109686. },
  109687. enumerable: true,
  109688. configurable: true
  109689. });
  109690. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  109691. /**
  109692. * Get the FPS value of this animation
  109693. */
  109694. get: function () {
  109695. // get the first currentFrame found
  109696. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  109697. var animatable = this._animationGroup.animatables[i];
  109698. var animations = animatable.getAnimations();
  109699. if (!animations || !animations.length) {
  109700. continue;
  109701. }
  109702. for (var idx = 0; idx < animations.length; ++idx) {
  109703. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  109704. return animations[idx].animation.framePerSecond;
  109705. }
  109706. }
  109707. }
  109708. return 0;
  109709. },
  109710. enumerable: true,
  109711. configurable: true
  109712. });
  109713. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  109714. /**
  109715. * What is the animation'S play mode (looping or played once)
  109716. */
  109717. get: function () {
  109718. return this._playMode;
  109719. },
  109720. /**
  109721. * Set the play mode.
  109722. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  109723. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  109724. */
  109725. set: function (value) {
  109726. if (value === this._playMode) {
  109727. return;
  109728. }
  109729. this._playMode = value;
  109730. if (this.state === 1 /* PLAYING */) {
  109731. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  109732. }
  109733. else {
  109734. this._animationGroup.reset();
  109735. this._state = 0 /* INIT */;
  109736. }
  109737. },
  109738. enumerable: true,
  109739. configurable: true
  109740. });
  109741. /**
  109742. * Reset the animation group
  109743. */
  109744. GroupModelAnimation.prototype.reset = function () {
  109745. this._animationGroup.reset();
  109746. };
  109747. /**
  109748. * Restart the animation group
  109749. */
  109750. GroupModelAnimation.prototype.restart = function () {
  109751. if (this.state === 2 /* PAUSED */)
  109752. this._animationGroup.restart();
  109753. else
  109754. this.start();
  109755. };
  109756. /**
  109757. *
  109758. * @param frameNumber Go to a specific frame in the animation
  109759. */
  109760. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  109761. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  109762. };
  109763. /**
  109764. * Start playing the animation.
  109765. */
  109766. GroupModelAnimation.prototype.start = function () {
  109767. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  109768. if (this._animationGroup.isStarted) {
  109769. this._state = 1 /* PLAYING */;
  109770. }
  109771. };
  109772. /**
  109773. * Pause the animation
  109774. */
  109775. GroupModelAnimation.prototype.pause = function () {
  109776. this._animationGroup.pause();
  109777. this._state = 2 /* PAUSED */;
  109778. };
  109779. /**
  109780. * Stop the animation.
  109781. * This will fail silently if the animation group is already stopped.
  109782. */
  109783. GroupModelAnimation.prototype.stop = function () {
  109784. this._animationGroup.stop();
  109785. if (!this._animationGroup.isStarted) {
  109786. this._state = 3 /* STOPPED */;
  109787. }
  109788. };
  109789. /**
  109790. * Dispose this animation object.
  109791. */
  109792. GroupModelAnimation.prototype.dispose = function () {
  109793. this._animationGroup.dispose();
  109794. };
  109795. return GroupModelAnimation;
  109796. }());
  109797. exports.GroupModelAnimation = GroupModelAnimation;
  109798. /***/ }),
  109799. /* 31 */
  109800. /***/ (function(module, exports, __webpack_require__) {
  109801. "use strict";
  109802. Object.defineProperty(exports, "__esModule", { value: true });
  109803. var environmentSerializer_1 = __webpack_require__(32);
  109804. var babylonjs_1 = __webpack_require__(0);
  109805. var texture_1 = __webpack_require__(12);
  109806. /**
  109807. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  109808. * The APIs in all labs-related classes and configuration might change.
  109809. * Once stable, lab features will be moved to the publis API and configuration object.
  109810. */
  109811. var ViewerLabs = /** @class */ (function () {
  109812. function ViewerLabs(_sceneManager) {
  109813. this._sceneManager = _sceneManager;
  109814. this.environment = {
  109815. //irradiance
  109816. irradiancePolynomialCoefficients: {
  109817. x: new babylonjs_1.Vector3(0, 0, 0),
  109818. y: new babylonjs_1.Vector3(0, 0, 0),
  109819. z: new babylonjs_1.Vector3(0, 0, 0),
  109820. xx: new babylonjs_1.Vector3(0, 0, 0),
  109821. yy: new babylonjs_1.Vector3(0, 0, 0),
  109822. zz: new babylonjs_1.Vector3(0, 0, 0),
  109823. yz: new babylonjs_1.Vector3(0, 0, 0),
  109824. zx: new babylonjs_1.Vector3(0, 0, 0),
  109825. xy: new babylonjs_1.Vector3(0, 0, 0)
  109826. },
  109827. textureIntensityScale: 1.0
  109828. };
  109829. }
  109830. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  109831. var _this = this;
  109832. //@! todo: should loadEnvironment cancel any currently loading environments?
  109833. if (data instanceof ArrayBuffer) {
  109834. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  109835. if (onSuccess)
  109836. onSuccess(this.environment);
  109837. }
  109838. else if (typeof data === 'string') {
  109839. var url = this.getAssetUrl(data);
  109840. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  109841. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  109842. if (onSuccess)
  109843. onSuccess(_this.environment);
  109844. }, function (progressEvent) { if (onProgress)
  109845. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  109846. if (onError) {
  109847. onError(e);
  109848. }
  109849. });
  109850. }
  109851. else {
  109852. //data assumed to be PBREnvironment object
  109853. this.environment = data;
  109854. if (onSuccess)
  109855. onSuccess(data);
  109856. }
  109857. };
  109858. /**
  109859. * Applies an `EnvironmentMapConfiguration` to the scene
  109860. * @param environmentMapConfiguration Environment map configuration to apply
  109861. */
  109862. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  109863. if (!this.environment)
  109864. return;
  109865. //set orientation
  109866. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  109867. // Add env texture to the scene.
  109868. if (this.environment.specularTexture) {
  109869. // IE crashes when disposing the old texture and setting a new one
  109870. if (!this._sceneManager.scene.environmentTexture) {
  109871. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  109872. }
  109873. if (this._sceneManager.scene.environmentTexture) {
  109874. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  109875. this._sceneManager.scene.environmentTexture.invertZ = true;
  109876. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  109877. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  109878. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  109879. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  109880. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  109881. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  109882. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  109883. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  109884. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  109885. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  109886. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  109887. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  109888. //set orientation
  109889. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  109890. }
  109891. }
  109892. };
  109893. /**
  109894. * Get an environment asset url by using the configuration if the path is not absolute.
  109895. * @param url Asset url
  109896. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  109897. */
  109898. ViewerLabs.prototype.getAssetUrl = function (url) {
  109899. var returnUrl = url;
  109900. if (url && url.toLowerCase().indexOf("//") === -1) {
  109901. if (!this.assetsRootURL) {
  109902. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  109903. return url;
  109904. }
  109905. returnUrl = this.assetsRootURL + returnUrl;
  109906. }
  109907. return returnUrl;
  109908. };
  109909. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  109910. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  109911. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  109912. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  109913. axis.normalize();
  109914. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  109915. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  109916. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  109917. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  109918. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  109919. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  109920. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  109921. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  109922. shadowLight.setDirectionToTarget(target);
  109923. };
  109924. return ViewerLabs;
  109925. }());
  109926. exports.ViewerLabs = ViewerLabs;
  109927. /***/ }),
  109928. /* 32 */
  109929. /***/ (function(module, exports, __webpack_require__) {
  109930. "use strict";
  109931. Object.defineProperty(exports, "__esModule", { value: true });
  109932. var babylonjs_1 = __webpack_require__(0);
  109933. var texture_1 = __webpack_require__(12);
  109934. /**
  109935. * A static class proving methods to aid parsing Spectre environment files
  109936. */
  109937. var EnvironmentDeserializer = /** @class */ (function () {
  109938. function EnvironmentDeserializer() {
  109939. }
  109940. /**
  109941. * Parses an arraybuffer into a new PBREnvironment object
  109942. * @param arrayBuffer The arraybuffer of the Spectre environment file
  109943. * @return a PBREnvironment object
  109944. */
  109945. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  109946. var environment = {
  109947. //irradiance
  109948. irradiancePolynomialCoefficients: {
  109949. x: new babylonjs_1.Vector3(0, 0, 0),
  109950. y: new babylonjs_1.Vector3(0, 0, 0),
  109951. z: new babylonjs_1.Vector3(0, 0, 0),
  109952. xx: new babylonjs_1.Vector3(0, 0, 0),
  109953. yy: new babylonjs_1.Vector3(0, 0, 0),
  109954. zz: new babylonjs_1.Vector3(0, 0, 0),
  109955. yz: new babylonjs_1.Vector3(0, 0, 0),
  109956. zx: new babylonjs_1.Vector3(0, 0, 0),
  109957. xy: new babylonjs_1.Vector3(0, 0, 0)
  109958. },
  109959. //specular
  109960. textureIntensityScale: 1.0,
  109961. };
  109962. //read .env
  109963. var littleEndian = false;
  109964. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  109965. var dataView = new DataView(arrayBuffer);
  109966. var pos = 0;
  109967. for (var i = 0; i < magicBytes.length; i++) {
  109968. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  109969. babylonjs_1.Tools.Error('Not a Spectre environment map');
  109970. }
  109971. }
  109972. var version = dataView.getUint16(pos, littleEndian);
  109973. pos += 2;
  109974. if (version !== 1) {
  109975. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  109976. }
  109977. //read json descriptor - collect characters up to null terminator
  109978. var descriptorString = '';
  109979. var charCode = 0x00;
  109980. while ((charCode = dataView.getUint8(pos++))) {
  109981. descriptorString += String.fromCharCode(charCode);
  109982. }
  109983. var descriptor = JSON.parse(descriptorString);
  109984. var payloadPos = pos;
  109985. //irradiance
  109986. switch (descriptor.irradiance.type) {
  109987. case 'irradiance_sh_coefficients_9':
  109988. //irradiance
  109989. var harmonics = descriptor.irradiance;
  109990. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  109991. //harmonics now represent radiance
  109992. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  109993. break;
  109994. default:
  109995. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  109996. }
  109997. //specular
  109998. switch (descriptor.specular.type) {
  109999. case 'cubemap_faces':
  110000. var specularDescriptor = descriptor.specular;
  110001. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  110002. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  110003. var mipmaps = specularDescriptor.mipmaps;
  110004. var imageType = specularDescriptor.imageType;
  110005. for (var l = 0; l < mipmaps.length; l++) {
  110006. var faceRanges = mipmaps[l];
  110007. specularTexture.source[l] = [];
  110008. for (var i = 0; i < 6; i++) {
  110009. var range = faceRanges[i];
  110010. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  110011. switch (imageType) {
  110012. case 'png':
  110013. //construct image element from bytes
  110014. var image = new Image();
  110015. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  110016. image.src = src;
  110017. specularTexture.source[l][i] = image;
  110018. break;
  110019. default:
  110020. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  110021. }
  110022. }
  110023. }
  110024. break;
  110025. default:
  110026. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  110027. }
  110028. return environment;
  110029. };
  110030. /**
  110031. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  110032. * L = (1/pi) * E * rho
  110033. *
  110034. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  110035. * @param harmonics Spherical harmonic coefficients (9)
  110036. */
  110037. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  110038. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  110039. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  110040. // (The pixel shader must apply albedo after texture fetches, etc).
  110041. };
  110042. /**
  110043. * Convert spherical harmonics to spherical polynomial coefficients
  110044. * @param harmonics Spherical harmonic coefficients (9)
  110045. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  110046. */
  110047. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  110048. var rPi = 1 / Math.PI;
  110049. //x
  110050. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  110051. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  110052. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  110053. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  110054. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  110055. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  110056. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  110057. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  110058. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  110059. //xx
  110060. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  110061. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  110062. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  110063. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  110064. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  110065. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  110066. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  110067. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  110068. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  110069. //yz
  110070. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  110071. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  110072. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  110073. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  110074. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  110075. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  110076. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  110077. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  110078. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  110079. };
  110080. /**
  110081. * Multiplies harmonic coefficients in place
  110082. * @param harmonics Spherical harmonic coefficients (9)
  110083. * @param scaleFactor Value to multiply by
  110084. */
  110085. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  110086. harmonics.l00[0] *= scaleFactor;
  110087. harmonics.l00[1] *= scaleFactor;
  110088. harmonics.l00[2] *= scaleFactor;
  110089. harmonics.l1_1[0] *= scaleFactor;
  110090. harmonics.l1_1[1] *= scaleFactor;
  110091. harmonics.l1_1[2] *= scaleFactor;
  110092. harmonics.l10[0] *= scaleFactor;
  110093. harmonics.l10[1] *= scaleFactor;
  110094. harmonics.l10[2] *= scaleFactor;
  110095. harmonics.l11[0] *= scaleFactor;
  110096. harmonics.l11[1] *= scaleFactor;
  110097. harmonics.l11[2] *= scaleFactor;
  110098. harmonics.l2_2[0] *= scaleFactor;
  110099. harmonics.l2_2[1] *= scaleFactor;
  110100. harmonics.l2_2[2] *= scaleFactor;
  110101. harmonics.l2_1[0] *= scaleFactor;
  110102. harmonics.l2_1[1] *= scaleFactor;
  110103. harmonics.l2_1[2] *= scaleFactor;
  110104. harmonics.l20[0] *= scaleFactor;
  110105. harmonics.l20[1] *= scaleFactor;
  110106. harmonics.l20[2] *= scaleFactor;
  110107. harmonics.l21[0] *= scaleFactor;
  110108. harmonics.l21[1] *= scaleFactor;
  110109. harmonics.l21[2] *= scaleFactor;
  110110. harmonics.l22[0] *= scaleFactor;
  110111. harmonics.l22[1] *= scaleFactor;
  110112. harmonics.l22[2] *= scaleFactor;
  110113. };
  110114. return EnvironmentDeserializer;
  110115. }());
  110116. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  110117. /***/ }),
  110118. /* 33 */
  110119. /***/ (function(module, exports, __webpack_require__) {
  110120. "use strict";
  110121. Object.defineProperty(exports, "__esModule", { value: true });
  110122. var extended_1 = __webpack_require__(34);
  110123. var cache = {};
  110124. /**
  110125. *
  110126. * @param name the name of the custom optimizer configuration
  110127. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  110128. */
  110129. function getCustomOptimizerByName(name, upgrade) {
  110130. if (!cache[name]) {
  110131. switch (name) {
  110132. case 'extended':
  110133. if (upgrade) {
  110134. return extended_1.extendedUpgrade;
  110135. }
  110136. else {
  110137. return extended_1.extendedDegrade;
  110138. }
  110139. }
  110140. }
  110141. return cache[name];
  110142. }
  110143. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  110144. /***/ }),
  110145. /* 34 */
  110146. /***/ (function(module, exports, __webpack_require__) {
  110147. "use strict";
  110148. Object.defineProperty(exports, "__esModule", { value: true });
  110149. var babylonjs_1 = __webpack_require__(0);
  110150. /**
  110151. * A custom upgrade-oriented function configuration for the scene optimizer.
  110152. *
  110153. * @param viewer the viewer to optimize
  110154. */
  110155. function extendedUpgrade(viewer) {
  110156. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  110157. // if (!this.Scene.BackgroundHelper) {
  110158. // this.Scene.EngineScene.autoClear = false;
  110159. // this.Scene.BackgroundHelper = true;
  110160. // Would require a dedicated clear color;
  110161. // return false;
  110162. // }
  110163. if (viewer.engine.getHardwareScalingLevel() > 1) {
  110164. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, 1);
  110165. viewer.engine.setHardwareScalingLevel(scaling);
  110166. return false;
  110167. }
  110168. if (!viewer.sceneManager.scene.postProcessesEnabled) {
  110169. viewer.sceneManager.scene.postProcessesEnabled = true;
  110170. return false;
  110171. }
  110172. if (!viewer.sceneManager.groundEnabled) {
  110173. viewer.sceneManager.groundEnabled = true;
  110174. return false;
  110175. }
  110176. if (defaultPipeline && !viewer.sceneManager.fxaaEnabled) {
  110177. viewer.sceneManager.fxaaEnabled = true;
  110178. return false;
  110179. }
  110180. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  110181. if (viewer.engine.getHardwareScalingLevel() > hardwareScalingLevel) {
  110182. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  110183. viewer.engine.setHardwareScalingLevel(scaling);
  110184. return false;
  110185. }
  110186. if (!viewer.sceneManager.processShadows) {
  110187. viewer.sceneManager.processShadows = true;
  110188. return false;
  110189. }
  110190. if (defaultPipeline && !viewer.sceneManager.bloomEnabled) {
  110191. viewer.sceneManager.bloomEnabled = true;
  110192. return false;
  110193. }
  110194. if (!viewer.sceneManager.groundMirrorEnabled) {
  110195. viewer.sceneManager.groundMirrorEnabled = true;
  110196. return false;
  110197. }
  110198. return true;
  110199. }
  110200. exports.extendedUpgrade = extendedUpgrade;
  110201. /**
  110202. * A custom degrade-oriented function configuration for the scene optimizer.
  110203. *
  110204. * @param viewer the viewer to optimize
  110205. */
  110206. function extendedDegrade(viewer) {
  110207. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  110208. if (viewer.sceneManager.groundMirrorEnabled) {
  110209. viewer.sceneManager.groundMirrorEnabled = false;
  110210. return false;
  110211. }
  110212. if (defaultPipeline && viewer.sceneManager.bloomEnabled) {
  110213. viewer.sceneManager.bloomEnabled = false;
  110214. return false;
  110215. }
  110216. if (viewer.sceneManager.processShadows) {
  110217. viewer.sceneManager.processShadows = false;
  110218. return false;
  110219. }
  110220. if (viewer.engine.getHardwareScalingLevel() < 1) {
  110221. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1);
  110222. viewer.engine.setHardwareScalingLevel(scaling);
  110223. return false;
  110224. }
  110225. if (defaultPipeline && viewer.sceneManager.fxaaEnabled) {
  110226. viewer.sceneManager.fxaaEnabled = false;
  110227. return false;
  110228. }
  110229. if (viewer.sceneManager.groundEnabled) {
  110230. viewer.sceneManager.groundEnabled = false;
  110231. return false;
  110232. }
  110233. if (viewer.sceneManager.scene.postProcessesEnabled) {
  110234. viewer.sceneManager.scene.postProcessesEnabled = false;
  110235. return false;
  110236. }
  110237. if (viewer.engine.getHardwareScalingLevel() < 1.25) {
  110238. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1.25);
  110239. viewer.engine.setHardwareScalingLevel(scaling);
  110240. return false;
  110241. }
  110242. // if (this.Scene.BackgroundHelper) {
  110243. // this.Scene.EngineScene.autoClear = true;
  110244. // this.Scene.BackgroundHelper = false;
  110245. // Would require a dedicated clear color;
  110246. // return false;
  110247. // }
  110248. return true;
  110249. }
  110250. exports.extendedDegrade = extendedDegrade;
  110251. /***/ }),
  110252. /* 35 */
  110253. /***/ (function(module, exports, __webpack_require__) {
  110254. "use strict";
  110255. Object.defineProperty(exports, "__esModule", { value: true });
  110256. var babylonjs_1 = __webpack_require__(0);
  110257. var helper_1 = __webpack_require__(2);
  110258. var deepmerge = __webpack_require__(1);
  110259. /**
  110260. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  110261. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  110262. */
  110263. var TemplateManager = /** @class */ (function () {
  110264. function TemplateManager(containerElement) {
  110265. this.containerElement = containerElement;
  110266. this.templates = {};
  110267. this.onTemplateInit = new babylonjs_1.Observable();
  110268. this.onTemplateLoaded = new babylonjs_1.Observable();
  110269. this.onTemplateStateChange = new babylonjs_1.Observable();
  110270. this.onAllLoaded = new babylonjs_1.Observable();
  110271. this.onEventTriggered = new babylonjs_1.Observable();
  110272. this.eventManager = new eventManager_1.EventManager(this);
  110273. }
  110274. /**
  110275. * Initialize the template(s) for the viewer. Called bay the Viewer class
  110276. * @param templates the templates to be used to initialize the main template
  110277. */
  110278. TemplateManager.prototype.initTemplate = function (templates) {
  110279. var _this = this;
  110280. var internalInit = function (dependencyMap, name, parentTemplate) {
  110281. //init template
  110282. var template = _this.templates[name];
  110283. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  110284. return internalInit(dependencyMap[childName], childName, template);
  110285. });
  110286. // register the observers
  110287. //template.onLoaded.add(() => {
  110288. var addToParent = function () {
  110289. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  110290. template.appendTo(containingElement);
  110291. _this._checkLoadedState();
  110292. };
  110293. if (parentTemplate && !parentTemplate.parent) {
  110294. parentTemplate.onAppended.add(function () {
  110295. addToParent();
  110296. });
  110297. }
  110298. else {
  110299. addToParent();
  110300. }
  110301. //});
  110302. return template;
  110303. };
  110304. //build the html tree
  110305. return this._buildHTMLTree(templates).then(function (htmlTree) {
  110306. if (_this.templates['main']) {
  110307. internalInit(htmlTree, 'main');
  110308. }
  110309. else {
  110310. _this._checkLoadedState();
  110311. }
  110312. return;
  110313. });
  110314. };
  110315. /**
  110316. *
  110317. * This function will create a simple map with child-dependencies of the template html tree.
  110318. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  110319. * It is expected that the main template will be called main!
  110320. *
  110321. * @param templates
  110322. */
  110323. TemplateManager.prototype._buildHTMLTree = function (templates) {
  110324. var _this = this;
  110325. var promises = Object.keys(templates).map(function (name) {
  110326. // if the template was overridden
  110327. if (!templates[name])
  110328. return Promise.resolve(false);
  110329. // else - we have a template, let's do our job!
  110330. var template = new Template(name, templates[name]);
  110331. template.onLoaded.add(function () {
  110332. _this.onTemplateLoaded.notifyObservers(template);
  110333. });
  110334. template.onStateChange.add(function () {
  110335. _this.onTemplateStateChange.notifyObservers(template);
  110336. });
  110337. _this.onTemplateInit.notifyObservers(template);
  110338. // make sure the global onEventTriggered is called as well
  110339. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  110340. _this.templates[name] = template;
  110341. return template.initPromise;
  110342. });
  110343. return Promise.all(promises).then(function () {
  110344. var templateStructure = {};
  110345. // now iterate through all templates and check for children:
  110346. var buildTree = function (parentObject, name) {
  110347. _this.templates[name].isInHtmlTree = true;
  110348. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  110349. childNodes.forEach(function (element) {
  110350. parentObject[element] = {};
  110351. buildTree(parentObject[element], element);
  110352. });
  110353. };
  110354. if (_this.templates['main']) {
  110355. buildTree(templateStructure, "main");
  110356. }
  110357. return templateStructure;
  110358. });
  110359. };
  110360. /**
  110361. * Get the canvas in the template tree.
  110362. * There must be one and only one canvas inthe template.
  110363. */
  110364. TemplateManager.prototype.getCanvas = function () {
  110365. return this.containerElement.querySelector('canvas');
  110366. };
  110367. /**
  110368. * Get a specific template from the template tree
  110369. * @param name the name of the template to load
  110370. */
  110371. TemplateManager.prototype.getTemplate = function (name) {
  110372. return this.templates[name];
  110373. };
  110374. TemplateManager.prototype._checkLoadedState = function () {
  110375. var _this = this;
  110376. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  110377. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  110378. });
  110379. if (done) {
  110380. this.onAllLoaded.notifyObservers(this);
  110381. }
  110382. };
  110383. /**
  110384. * Dispose the template manager
  110385. */
  110386. TemplateManager.prototype.dispose = function () {
  110387. var _this = this;
  110388. // dispose all templates
  110389. Object.keys(this.templates).forEach(function (template) {
  110390. _this.templates[template].dispose();
  110391. });
  110392. this.templates = {};
  110393. this.eventManager.dispose();
  110394. this.onTemplateInit.clear();
  110395. this.onAllLoaded.clear();
  110396. this.onEventTriggered.clear();
  110397. this.onTemplateLoaded.clear();
  110398. this.onTemplateStateChange.clear();
  110399. };
  110400. return TemplateManager;
  110401. }());
  110402. exports.TemplateManager = TemplateManager;
  110403. var Handlebars = __webpack_require__(36);
  110404. var eventManager_1 = __webpack_require__(37);
  110405. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  110406. Handlebars.registerHelper('eachInMap', function (map, block) {
  110407. var out = '';
  110408. Object.keys(map).map(function (prop) {
  110409. var data = map[prop];
  110410. if (typeof data === 'object') {
  110411. data.id = data.id || prop;
  110412. out += block.fn(data);
  110413. }
  110414. else {
  110415. out += block.fn({ id: prop, value: data });
  110416. }
  110417. });
  110418. return out;
  110419. });
  110420. Handlebars.registerHelper('add', function (a, b) {
  110421. var out = a + b;
  110422. return out;
  110423. });
  110424. Handlebars.registerHelper('eq', function (a, b) {
  110425. var out = (a == b);
  110426. return out;
  110427. });
  110428. Handlebars.registerHelper('or', function (a, b) {
  110429. var out = a || b;
  110430. return out;
  110431. });
  110432. Handlebars.registerHelper('not', function (a) {
  110433. var out = !a;
  110434. return out;
  110435. });
  110436. Handlebars.registerHelper('count', function (map) {
  110437. return map.length;
  110438. });
  110439. Handlebars.registerHelper('gt', function (a, b) {
  110440. var out = a > b;
  110441. return out;
  110442. });
  110443. /**
  110444. * This class represents a single template in the viewer's template tree.
  110445. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  110446. * A template is injected using the template manager in the correct position.
  110447. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  110448. *
  110449. * For further information please refer to the documentation page, https://doc.babylonjs.com
  110450. */
  110451. var Template = /** @class */ (function () {
  110452. function Template(name, _configuration) {
  110453. var _this = this;
  110454. this.name = name;
  110455. this._configuration = _configuration;
  110456. this.onLoaded = new babylonjs_1.Observable();
  110457. this.onAppended = new babylonjs_1.Observable();
  110458. this.onStateChange = new babylonjs_1.Observable();
  110459. this.onEventTriggered = new babylonjs_1.Observable();
  110460. this.loadRequests = [];
  110461. this.isLoaded = false;
  110462. this.isShown = false;
  110463. this.isInHtmlTree = false;
  110464. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  110465. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  110466. if (htmlTemplate) {
  110467. _this._htmlTemplate = htmlTemplate;
  110468. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && _this._configuration.params.noEscape) });
  110469. var config = _this._configuration.params || {};
  110470. _this._rawHtml = compiledTemplate(config);
  110471. try {
  110472. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  110473. }
  110474. catch (e) {
  110475. var test = document.createElement(_this.name);
  110476. test.innerHTML = _this._rawHtml;
  110477. _this._fragment = test;
  110478. }
  110479. _this.isLoaded = true;
  110480. _this.isShown = true;
  110481. _this.onLoaded.notifyObservers(_this);
  110482. }
  110483. return _this;
  110484. });
  110485. }
  110486. /**
  110487. * Some templates have parameters (like background color for example).
  110488. * The parameters are provided to Handlebars which in turn generates the template.
  110489. * This function will update the template with the new parameters
  110490. *
  110491. * Note that when updating parameters the events will be registered again (after being cleared).
  110492. *
  110493. * @param params the new template parameters
  110494. */
  110495. Template.prototype.updateParams = function (params, append) {
  110496. if (append === void 0) { append = true; }
  110497. if (append) {
  110498. this._configuration.params = deepmerge(this._configuration.params, params);
  110499. }
  110500. else {
  110501. this._configuration.params = params;
  110502. }
  110503. // update the template
  110504. if (this.isLoaded) {
  110505. // this.dispose();
  110506. }
  110507. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  110508. var config = this._configuration.params || {};
  110509. this._rawHtml = compiledTemplate(config);
  110510. try {
  110511. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  110512. }
  110513. catch (e) {
  110514. var test = document.createElement(this.name);
  110515. test.innerHTML = this._rawHtml;
  110516. this._fragment = test;
  110517. }
  110518. if (this.parent) {
  110519. this.appendTo(this.parent, true);
  110520. }
  110521. };
  110522. Object.defineProperty(Template.prototype, "configuration", {
  110523. /**
  110524. * Get the template'S configuration
  110525. */
  110526. get: function () {
  110527. return this._configuration;
  110528. },
  110529. enumerable: true,
  110530. configurable: true
  110531. });
  110532. /**
  110533. * A template can be a parent element for other templates or HTML elements.
  110534. * This function will deliver all child HTML elements of this template.
  110535. */
  110536. Template.prototype.getChildElements = function () {
  110537. var childrenArray = [];
  110538. //Edge and IE don't support frage,ent.children
  110539. var children = this._fragment && this._fragment.children;
  110540. if (!this._fragment) {
  110541. var fragment = this.parent.querySelector(this.name);
  110542. if (fragment) {
  110543. children = fragment.querySelectorAll('*');
  110544. }
  110545. }
  110546. if (!children) {
  110547. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  110548. children = this._fragment.querySelectorAll('*');
  110549. }
  110550. for (var i = 0; i < children.length; ++i) {
  110551. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  110552. }
  110553. return childrenArray;
  110554. };
  110555. /**
  110556. * Appending the template to a parent HTML element.
  110557. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  110558. * @param parent the parent to which the template is added
  110559. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  110560. */
  110561. Template.prototype.appendTo = function (parent, forceRemove) {
  110562. var _this = this;
  110563. if (this.parent) {
  110564. if (forceRemove && this._addedFragment) {
  110565. /*let fragement = this.parent.querySelector(this.name)
  110566. if (fragement)
  110567. this.parent.removeChild(fragement);*/
  110568. this.parent.innerHTML = '';
  110569. }
  110570. else {
  110571. return;
  110572. }
  110573. }
  110574. this.parent = parent;
  110575. if (this._configuration.id) {
  110576. this.parent.id = this._configuration.id;
  110577. }
  110578. if (this._fragment) {
  110579. this.parent.appendChild(this._fragment);
  110580. this._addedFragment = this._fragment;
  110581. }
  110582. else {
  110583. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  110584. }
  110585. // appended only one frame after.
  110586. setTimeout(function () {
  110587. _this._registerEvents();
  110588. _this.onAppended.notifyObservers(_this);
  110589. });
  110590. };
  110591. /**
  110592. * Show the template using the provided visibilityFunction, or natively using display: flex.
  110593. * The provided function returns a promise that should be fullfilled when the element is shown.
  110594. * Since it is a promise async operations are more than possible.
  110595. * See the default viewer for an opacity example.
  110596. * @param visibilityFunction The function to execute to show the template.
  110597. */
  110598. Template.prototype.show = function (visibilityFunction) {
  110599. var _this = this;
  110600. if (this._isHiding)
  110601. return Promise.resolve(this);
  110602. return Promise.resolve().then(function () {
  110603. _this._isShowing = true;
  110604. if (visibilityFunction) {
  110605. return visibilityFunction(_this);
  110606. }
  110607. else {
  110608. // flex? box? should this be configurable easier than the visibilityFunction?
  110609. _this.parent.style.display = 'flex';
  110610. // support old browsers with no flex:
  110611. if (_this.parent.style.display !== 'flex') {
  110612. _this.parent.style.display = '';
  110613. }
  110614. return _this;
  110615. }
  110616. }).then(function () {
  110617. _this.isShown = true;
  110618. _this._isShowing = false;
  110619. _this.onStateChange.notifyObservers(_this);
  110620. return _this;
  110621. });
  110622. };
  110623. /**
  110624. * Hide the template using the provided visibilityFunction, or natively using display: none.
  110625. * The provided function returns a promise that should be fullfilled when the element is hidden.
  110626. * Since it is a promise async operations are more than possible.
  110627. * See the default viewer for an opacity example.
  110628. * @param visibilityFunction The function to execute to show the template.
  110629. */
  110630. Template.prototype.hide = function (visibilityFunction) {
  110631. var _this = this;
  110632. if (this._isShowing)
  110633. return Promise.resolve(this);
  110634. return Promise.resolve().then(function () {
  110635. _this._isHiding = true;
  110636. if (visibilityFunction) {
  110637. return visibilityFunction(_this);
  110638. }
  110639. else {
  110640. // flex? box? should this be configurable easier than the visibilityFunction?
  110641. _this.parent.style.display = 'none';
  110642. return _this;
  110643. }
  110644. }).then(function () {
  110645. _this.isShown = false;
  110646. _this._isHiding = false;
  110647. _this.onStateChange.notifyObservers(_this);
  110648. return _this;
  110649. });
  110650. };
  110651. /**
  110652. * Dispose this template
  110653. */
  110654. Template.prototype.dispose = function () {
  110655. this.onAppended.clear();
  110656. this.onEventTriggered.clear();
  110657. this.onLoaded.clear();
  110658. this.onStateChange.clear();
  110659. this.isLoaded = false;
  110660. // remove from parent
  110661. try {
  110662. this.parent.removeChild(this._fragment);
  110663. }
  110664. catch (e) {
  110665. //noop
  110666. }
  110667. this.loadRequests.forEach(function (request) {
  110668. request.abort();
  110669. });
  110670. if (this._registeredEvents) {
  110671. this._registeredEvents.forEach(function (evt) {
  110672. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  110673. });
  110674. }
  110675. delete this._fragment;
  110676. };
  110677. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  110678. var _this = this;
  110679. if (!templateConfig) {
  110680. return Promise.reject('No templateConfig provided');
  110681. }
  110682. else if (templateConfig.html !== undefined) {
  110683. return Promise.resolve(templateConfig.html);
  110684. }
  110685. else {
  110686. var location_1 = this._getTemplateLocation(templateConfig);
  110687. if (helper_1.isUrl(location_1)) {
  110688. return new Promise(function (resolve, reject) {
  110689. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  110690. resolve(data);
  110691. }, undefined, undefined, false, function (request, error) {
  110692. reject(error);
  110693. });
  110694. _this.loadRequests.push(fileRequest);
  110695. });
  110696. }
  110697. else {
  110698. location_1 = location_1.replace('#', '');
  110699. var element = document.getElementById(location_1);
  110700. if (element) {
  110701. return Promise.resolve(element.innerHTML);
  110702. }
  110703. else {
  110704. return Promise.reject('Template ID not found');
  110705. }
  110706. }
  110707. }
  110708. };
  110709. Template.prototype._registerEvents = function () {
  110710. var _this = this;
  110711. this._registeredEvents = this._registeredEvents || [];
  110712. if (this._registeredEvents.length) {
  110713. // first remove the registered events
  110714. this._registeredEvents.forEach(function (evt) {
  110715. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  110716. });
  110717. }
  110718. if (this._configuration.events) {
  110719. var _loop_1 = function (eventName) {
  110720. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  110721. var functionToFire_1 = function (selector, event) {
  110722. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  110723. };
  110724. // if boolean, set the parent as the event listener
  110725. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  110726. var selector = this_1.parent.id;
  110727. if (selector) {
  110728. selector = '#' + selector;
  110729. }
  110730. else {
  110731. selector = this_1.parent.tagName;
  110732. }
  110733. var binding = functionToFire_1.bind(this_1, selector);
  110734. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  110735. this_1._registeredEvents.push({
  110736. htmlElement: this_1.parent,
  110737. eventName: eventName,
  110738. function: binding
  110739. });
  110740. }
  110741. else if (typeof this_1._configuration.events[eventName] === 'object') {
  110742. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  110743. // strict null checl is working incorrectly, must override:
  110744. var event_1 = this_1._configuration.events[eventName] || {};
  110745. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  110746. if (selector && selector.indexOf('#') !== 0) {
  110747. selector = '#' + selector;
  110748. }
  110749. var htmlElement = _this.parent.querySelector(selector);
  110750. if (htmlElement) {
  110751. var binding = functionToFire_1.bind(_this, selector);
  110752. htmlElement.addEventListener(eventName, binding, false);
  110753. _this._registeredEvents.push({
  110754. htmlElement: htmlElement,
  110755. eventName: eventName,
  110756. function: binding
  110757. });
  110758. }
  110759. });
  110760. }
  110761. }
  110762. };
  110763. var this_1 = this;
  110764. for (var eventName in this._configuration.events) {
  110765. _loop_1(eventName);
  110766. }
  110767. }
  110768. };
  110769. Template.prototype._getTemplateLocation = function (templateConfig) {
  110770. if (!templateConfig || typeof templateConfig === 'string') {
  110771. return templateConfig;
  110772. }
  110773. else {
  110774. return templateConfig.location;
  110775. }
  110776. };
  110777. return Template;
  110778. }());
  110779. exports.Template = Template;
  110780. /***/ }),
  110781. /* 36 */
  110782. /***/ (function(module, exports, __webpack_require__) {
  110783. /**!
  110784. @license
  110785. handlebars v4.0.11
  110786. Copyright (C) 2011-2017 by Yehuda Katz
  110787. Permission is hereby granted, free of charge, to any person obtaining a copy
  110788. of this software and associated documentation files (the "Software"), to deal
  110789. in the Software without restriction, including without limitation the rights
  110790. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  110791. copies of the Software, and to permit persons to whom the Software is
  110792. furnished to do so, subject to the following conditions:
  110793. The above copyright notice and this permission notice shall be included in
  110794. all copies or substantial portions of the Software.
  110795. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  110796. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  110797. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  110798. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  110799. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  110800. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  110801. THE SOFTWARE.
  110802. */
  110803. !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],
  110804. 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){
  110805. 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"]}])});
  110806. /***/ }),
  110807. /* 37 */
  110808. /***/ (function(module, exports, __webpack_require__) {
  110809. "use strict";
  110810. Object.defineProperty(exports, "__esModule", { value: true });
  110811. /**
  110812. * The EventManager is in charge of registering user interctions with the viewer.
  110813. * It is used in the TemplateManager
  110814. */
  110815. var EventManager = /** @class */ (function () {
  110816. function EventManager(_templateManager) {
  110817. var _this = this;
  110818. this._templateManager = _templateManager;
  110819. this._callbacksContainer = {};
  110820. this._templateManager.onEventTriggered.add(function (eventData) {
  110821. _this._eventTriggered(eventData);
  110822. });
  110823. }
  110824. /**
  110825. * Register a new callback to a specific template.
  110826. * The best example for the usage can be found in the DefaultViewer
  110827. *
  110828. * @param templateName the templateName to register the event to
  110829. * @param callback The callback to be executed
  110830. * @param eventType the type of event to register
  110831. * @param selector an optional selector. if not defined the parent object in the template will be selected
  110832. */
  110833. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  110834. if (!this._callbacksContainer[templateName]) {
  110835. this._callbacksContainer[templateName] = [];
  110836. }
  110837. this._callbacksContainer[templateName].push({
  110838. eventType: eventType,
  110839. callback: callback,
  110840. selector: selector
  110841. });
  110842. };
  110843. /**
  110844. * This will remove a registered event from the defined template.
  110845. * Each one of the variables apart from the template name are optional, but one must be provided.
  110846. *
  110847. * @param templateName the templateName
  110848. * @param callback the callback to remove (optional)
  110849. * @param eventType the event type to remove (optional)
  110850. * @param selector the selector from which to remove the event (optional)
  110851. */
  110852. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  110853. var callbackDefs = this._callbacksContainer[templateName] || [];
  110854. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  110855. };
  110856. EventManager.prototype._eventTriggered = function (data) {
  110857. var templateName = data.template.name;
  110858. var eventType = data.event.type;
  110859. var selector = data.selector;
  110860. var callbackDefs = this._callbacksContainer[templateName] || [];
  110861. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  110862. callbackDef.callback(data);
  110863. });
  110864. };
  110865. /**
  110866. * Dispose the event manager
  110867. */
  110868. EventManager.prototype.dispose = function () {
  110869. this._callbacksContainer = {};
  110870. };
  110871. return EventManager;
  110872. }());
  110873. exports.EventManager = EventManager;
  110874. /***/ }),
  110875. /* 38 */
  110876. /***/ (function(module, exports, __webpack_require__) {
  110877. "use strict";
  110878. Object.defineProperty(exports, "__esModule", { value: true });
  110879. var mappers_1 = __webpack_require__(3);
  110880. var types_1 = __webpack_require__(39);
  110881. var configurationCompatibility_1 = __webpack_require__(50);
  110882. var deepmerge = __webpack_require__(1);
  110883. var babylonjs_1 = __webpack_require__(0);
  110884. /**
  110885. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  110886. * parse the object and return a conform ViewerConfiguration.
  110887. * It is a private member of the scene.
  110888. */
  110889. var ConfigurationLoader = /** @class */ (function () {
  110890. function ConfigurationLoader(_enableCache) {
  110891. if (_enableCache === void 0) { _enableCache = false; }
  110892. this._enableCache = _enableCache;
  110893. this._configurationCache = {};
  110894. this._loadRequests = [];
  110895. }
  110896. /**
  110897. * load a configuration object that is defined in the initial configuration provided.
  110898. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  110899. *
  110900. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  110901. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  110902. * @returns A promise that delivers the extended viewer configuration, when done.
  110903. */
  110904. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  110905. var _this = this;
  110906. if (initConfig === void 0) { initConfig = {}; }
  110907. var loadedConfig = deepmerge({}, initConfig);
  110908. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  110909. if (loadedConfig.configuration) {
  110910. var mapperType_1 = "json";
  110911. return Promise.resolve().then(function () {
  110912. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  110913. // a file to load
  110914. var url = '';
  110915. if (typeof loadedConfig.configuration === "string") {
  110916. url = loadedConfig.configuration;
  110917. }
  110918. // if configuration is an object
  110919. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  110920. url = loadedConfig.configuration.url;
  110921. var type = loadedConfig.configuration.mapper;
  110922. // empty string?
  110923. if (!type) {
  110924. // load mapper type from filename / url
  110925. type = loadedConfig.configuration.url.split('.').pop();
  110926. }
  110927. mapperType_1 = type || mapperType_1;
  110928. }
  110929. return _this._loadFile(url);
  110930. }
  110931. else {
  110932. if (typeof loadedConfig.configuration === "object") {
  110933. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  110934. return loadedConfig.configuration.payload || {};
  110935. }
  110936. return {};
  110937. }
  110938. }).then(function (data) {
  110939. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  110940. var parsed = deepmerge(mapper.map(data), loadedConfig);
  110941. var merged = deepmerge(extendedConfiguration, parsed);
  110942. configurationCompatibility_1.processConfigurationCompatibility(merged);
  110943. if (callback)
  110944. callback(merged);
  110945. return merged;
  110946. });
  110947. }
  110948. else {
  110949. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  110950. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  110951. if (callback)
  110952. callback(loadedConfig);
  110953. return Promise.resolve(loadedConfig);
  110954. }
  110955. };
  110956. /**
  110957. * Dispose the configuration loader. This will cancel file requests, if active.
  110958. */
  110959. ConfigurationLoader.prototype.dispose = function () {
  110960. this._loadRequests.forEach(function (request) {
  110961. request.abort();
  110962. });
  110963. this._loadRequests.length = 0;
  110964. };
  110965. ConfigurationLoader.prototype._loadFile = function (url) {
  110966. var _this = this;
  110967. var cacheReference = this._configurationCache;
  110968. if (this._enableCache && cacheReference[url]) {
  110969. return Promise.resolve(cacheReference[url]);
  110970. }
  110971. return new Promise(function (resolve, reject) {
  110972. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  110973. var idx = _this._loadRequests.indexOf(fileRequest);
  110974. if (idx !== -1)
  110975. _this._loadRequests.splice(idx, 1);
  110976. if (_this._enableCache)
  110977. cacheReference[url] = result;
  110978. resolve(result);
  110979. }, undefined, undefined, false, function (request, error) {
  110980. var idx = _this._loadRequests.indexOf(fileRequest);
  110981. if (idx !== -1)
  110982. _this._loadRequests.splice(idx, 1);
  110983. reject(error);
  110984. });
  110985. _this._loadRequests.push(fileRequest);
  110986. });
  110987. };
  110988. return ConfigurationLoader;
  110989. }());
  110990. exports.ConfigurationLoader = ConfigurationLoader;
  110991. /***/ }),
  110992. /* 39 */
  110993. /***/ (function(module, exports, __webpack_require__) {
  110994. "use strict";
  110995. Object.defineProperty(exports, "__esModule", { value: true });
  110996. var minimal_1 = __webpack_require__(40);
  110997. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  110998. var default_1 = __webpack_require__(41);
  110999. exports.defaultConfiguration = default_1.defaultConfiguration;
  111000. var extended_1 = __webpack_require__(47);
  111001. var shadowLight_1 = __webpack_require__(48);
  111002. var environmentMap_1 = __webpack_require__(49);
  111003. var deepmerge = __webpack_require__(1);
  111004. /**
  111005. * Get the configuration type you need to use as the base for your viewer.
  111006. * The types can either be a single string, or comma separated types that will extend each other. for example:
  111007. *
  111008. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  111009. *
  111010. * @param types a comma-separated string of the type(s) or configuration to load.
  111011. */
  111012. var getConfigurationType = function (types) {
  111013. var config = {};
  111014. var typesSeparated = types.split(",");
  111015. typesSeparated.forEach(function (type) {
  111016. switch (type.trim()) {
  111017. case 'environmentMap':
  111018. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  111019. break;
  111020. case 'shadowDirectionalLight':
  111021. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  111022. break;
  111023. case 'shadowSpotLight':
  111024. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  111025. break;
  111026. case 'extended':
  111027. config = deepmerge(config, extended_1.extendedConfiguration);
  111028. break;
  111029. case 'minimal':
  111030. config = deepmerge(config, minimal_1.minimalConfiguration);
  111031. break;
  111032. case 'none':
  111033. break;
  111034. case 'default':
  111035. default:
  111036. config = deepmerge(config, default_1.defaultConfiguration);
  111037. break;
  111038. }
  111039. if (config.extends) {
  111040. config = deepmerge(config, getConfigurationType(config.extends));
  111041. }
  111042. });
  111043. return config;
  111044. };
  111045. exports.getConfigurationType = getConfigurationType;
  111046. /***/ }),
  111047. /* 40 */
  111048. /***/ (function(module, exports, __webpack_require__) {
  111049. "use strict";
  111050. Object.defineProperty(exports, "__esModule", { value: true });
  111051. /**
  111052. * The minimal configuration needed to make the viewer work.
  111053. * Some functionalities might not work correctly (like fill-screen)
  111054. */
  111055. exports.minimalConfiguration = {
  111056. version: "0.1",
  111057. templates: {
  111058. main: {
  111059. html: __webpack_require__(13)
  111060. },
  111061. fillContainer: {
  111062. html: __webpack_require__(14),
  111063. params: {
  111064. disable: false
  111065. }
  111066. },
  111067. loadingScreen: {
  111068. html: __webpack_require__(15),
  111069. params: {
  111070. backgroundColor: "#000000",
  111071. loadingImage: __webpack_require__(16)
  111072. }
  111073. },
  111074. viewer: {
  111075. html: __webpack_require__(17),
  111076. },
  111077. overlay: {
  111078. html: __webpack_require__(18),
  111079. params: {
  111080. closeImage: __webpack_require__(19),
  111081. closeText: 'Close'
  111082. }
  111083. },
  111084. error: {
  111085. html: __webpack_require__(20)
  111086. }
  111087. },
  111088. engine: {
  111089. antialiasing: true
  111090. }
  111091. };
  111092. /***/ }),
  111093. /* 41 */
  111094. /***/ (function(module, exports, __webpack_require__) {
  111095. "use strict";
  111096. Object.defineProperty(exports, "__esModule", { value: true });
  111097. /**
  111098. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  111099. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  111100. */
  111101. exports.defaultConfiguration = {
  111102. version: "3.2.0-alpha4",
  111103. templates: {
  111104. main: {
  111105. html: __webpack_require__(13),
  111106. params: {
  111107. babylonFont: __webpack_require__(42),
  111108. noEscape: true
  111109. }
  111110. },
  111111. fillContainer: {
  111112. html: __webpack_require__(14),
  111113. params: {
  111114. disable: false
  111115. }
  111116. },
  111117. loadingScreen: {
  111118. html: __webpack_require__(15),
  111119. params: {
  111120. backgroundColor: "#000000",
  111121. loadingImage: __webpack_require__(16)
  111122. }
  111123. },
  111124. viewer: {
  111125. html: __webpack_require__(17),
  111126. params: {
  111127. enableDragAndDrop: false
  111128. }
  111129. },
  111130. navBar: {
  111131. html: __webpack_require__(43),
  111132. params: {
  111133. speedList: {
  111134. "0.5x": "0.5",
  111135. "1.0x": "1.0",
  111136. "1.5x": "1.5",
  111137. "2.0x": "2.0",
  111138. },
  111139. logoImage: __webpack_require__(44),
  111140. logoText: 'BabylonJS',
  111141. logoLink: 'https://babylonjs.com',
  111142. hideHelp: true,
  111143. disableOnFullscreen: false,
  111144. },
  111145. events: {
  111146. pointerdown: {
  111147. 'navbar-control': true,
  111148. 'help-button': true
  111149. },
  111150. input: {
  111151. 'progress-wrapper': true
  111152. },
  111153. pointerup: {
  111154. 'progress-wrapper': true
  111155. }
  111156. }
  111157. },
  111158. overlay: {
  111159. html: __webpack_require__(18),
  111160. params: {
  111161. closeImage: __webpack_require__(19),
  111162. closeText: 'Close'
  111163. }
  111164. },
  111165. help: {
  111166. html: __webpack_require__(45)
  111167. },
  111168. share: {
  111169. html: __webpack_require__(46)
  111170. },
  111171. error: {
  111172. html: __webpack_require__(20)
  111173. }
  111174. },
  111175. camera: {
  111176. behaviors: {
  111177. autoRotate: {
  111178. type: 0
  111179. },
  111180. framing: {
  111181. type: 2,
  111182. zoomOnBoundingInfo: true,
  111183. zoomStopsAnimation: false
  111184. },
  111185. bouncing: {
  111186. type: 1
  111187. }
  111188. },
  111189. wheelPrecision: 200,
  111190. },
  111191. skybox: {},
  111192. ground: {
  111193. receiveShadows: true
  111194. },
  111195. engine: {
  111196. antialiasing: true
  111197. },
  111198. scene: {}
  111199. };
  111200. /***/ }),
  111201. /* 42 */
  111202. /***/ (function(module, exports) {
  111203. 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="
  111204. /***/ }),
  111205. /* 43 */
  111206. /***/ (function(module, exports) {
  111207. 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>";
  111208. /***/ }),
  111209. /* 44 */
  111210. /***/ (function(module, exports) {
  111211. 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="
  111212. /***/ }),
  111213. /* 45 */
  111214. /***/ (function(module, exports) {
  111215. module.exports = "HELP";
  111216. /***/ }),
  111217. /* 46 */
  111218. /***/ (function(module, exports) {
  111219. module.exports = "SHARE";
  111220. /***/ }),
  111221. /* 47 */
  111222. /***/ (function(module, exports, __webpack_require__) {
  111223. "use strict";
  111224. Object.defineProperty(exports, "__esModule", { value: true });
  111225. var babylonjs_1 = __webpack_require__(0);
  111226. /**
  111227. * The viewer's "extended" configuration.
  111228. * This configuration defines specific obejcts and parameters that we think make any model look good.
  111229. */
  111230. exports.extendedConfiguration = {
  111231. version: "3.2.0",
  111232. extends: "default",
  111233. camera: {
  111234. exposure: 3.034578,
  111235. fov: 0.7853981633974483,
  111236. contrast: 1.6,
  111237. toneMappingEnabled: true,
  111238. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  111239. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  111240. behaviors: {
  111241. framing: {
  111242. type: 2,
  111243. mode: 0,
  111244. positionScale: 0.5,
  111245. defaultElevation: 0.2617993877991494,
  111246. elevationReturnWaitTime: 3000,
  111247. elevationReturnTime: 2000,
  111248. framingTime: 500,
  111249. zoomStopsAnimation: false,
  111250. radiusScale: 0.866
  111251. },
  111252. autoRotate: {
  111253. type: 0,
  111254. idleRotationWaitTime: 4000,
  111255. idleRotationSpeed: 0.17453292519943295,
  111256. idleRotationSpinupTime: 2500,
  111257. zoomStopsAnimation: false
  111258. },
  111259. bouncing: {
  111260. type: 1,
  111261. lowerRadiusTransitionRange: 0.05,
  111262. upperRadiusTransitionRange: -0.2
  111263. }
  111264. },
  111265. upperRadiusLimit: 5,
  111266. lowerRadiusLimit: 0.5,
  111267. frameOnModelLoad: true,
  111268. framingElevation: 0.2617993877991494,
  111269. framingRotation: 1.5707963267948966,
  111270. radius: 2,
  111271. alpha: 1.5708,
  111272. beta: Math.PI * 0.5 - 0.2618,
  111273. wheelPrecision: 300,
  111274. minZ: 0.1,
  111275. maxZ: 50,
  111276. fovMode: 0,
  111277. pinchPrecision: 1500,
  111278. panningSensibility: 3000
  111279. },
  111280. lights: {
  111281. light0: {
  111282. type: 0,
  111283. frustumEdgeFalloff: 0,
  111284. intensity: 7,
  111285. intensityMode: 0,
  111286. radius: 0.6,
  111287. range: 0.6,
  111288. spotAngle: 60,
  111289. diffuse: {
  111290. r: 1,
  111291. g: 1,
  111292. b: 1
  111293. },
  111294. position: {
  111295. x: -2,
  111296. y: 2.5,
  111297. z: 2
  111298. },
  111299. target: {
  111300. x: 0,
  111301. y: 0,
  111302. z: 0
  111303. },
  111304. enabled: true,
  111305. shadowEnabled: true,
  111306. shadowBufferSize: 512,
  111307. shadowMinZ: 1,
  111308. shadowMaxZ: 10,
  111309. shadowFieldOfView: 60,
  111310. shadowFrustumSize: 2,
  111311. shadowConfig: {
  111312. useBlurCloseExponentialShadowMap: true,
  111313. useKernelBlur: true,
  111314. blurScale: 1.0,
  111315. bias: 0.001,
  111316. depthScale: 50 * (10 - 1),
  111317. frustumEdgeFalloff: 0
  111318. }
  111319. },
  111320. light1: {
  111321. type: 0,
  111322. frustumEdgeFalloff: 0,
  111323. intensity: 7,
  111324. intensityMode: 0,
  111325. radius: 0.4,
  111326. range: 0.4,
  111327. spotAngle: 57,
  111328. diffuse: {
  111329. r: 1,
  111330. g: 1,
  111331. b: 1
  111332. },
  111333. position: {
  111334. x: 4,
  111335. y: 3,
  111336. z: -0.5
  111337. },
  111338. target: {
  111339. x: 0,
  111340. y: 0,
  111341. z: 0
  111342. },
  111343. enabled: true,
  111344. shadowEnabled: false,
  111345. shadowBufferSize: 512,
  111346. shadowMinZ: 0.2,
  111347. shadowMaxZ: 10,
  111348. shadowFieldOfView: 28,
  111349. shadowFrustumSize: 2
  111350. },
  111351. light2: {
  111352. type: 0,
  111353. frustumEdgeFalloff: 0,
  111354. intensity: 1,
  111355. intensityMode: 0,
  111356. radius: 0.5,
  111357. range: 0.5,
  111358. spotAngle: 42.85,
  111359. diffuse: {
  111360. r: 0.8,
  111361. g: 0.8,
  111362. b: 0.8
  111363. },
  111364. position: {
  111365. x: -1,
  111366. y: 3,
  111367. z: -3
  111368. },
  111369. target: {
  111370. x: 0,
  111371. y: 0,
  111372. z: 0
  111373. },
  111374. enabled: true,
  111375. shadowEnabled: false,
  111376. shadowBufferSize: 512,
  111377. shadowMinZ: 0.2,
  111378. shadowMaxZ: 10,
  111379. shadowFieldOfView: 45,
  111380. shadowFrustumSize: 2
  111381. }
  111382. },
  111383. ground: {
  111384. shadowLevel: 0.9,
  111385. texture: "Ground_2.0-1024.png",
  111386. material: {
  111387. primaryColorHighlightLevel: 0.035,
  111388. primaryColorShadowLevel: 0,
  111389. enableNoise: true,
  111390. useRGBColor: false,
  111391. maxSimultaneousLights: 1,
  111392. diffuseTexture: {
  111393. gammaSpace: true
  111394. }
  111395. },
  111396. opacity: 1,
  111397. mirror: false,
  111398. receiveShadows: true,
  111399. size: 5
  111400. },
  111401. skybox: {
  111402. scale: 11,
  111403. cubeTexture: {
  111404. url: "Skybox_2.0-256.dds"
  111405. },
  111406. material: {
  111407. primaryColorHighlightLevel: 0.03,
  111408. primaryColorShadowLevel: 0.03,
  111409. enableNoise: true,
  111410. useRGBColor: false,
  111411. reflectionTexture: {
  111412. gammaSpace: true
  111413. }
  111414. }
  111415. },
  111416. engine: {
  111417. renderInBackground: true
  111418. },
  111419. scene: {
  111420. flags: {
  111421. shadowsEnabled: true,
  111422. particlesEnabled: false,
  111423. collisionsEnabled: false,
  111424. lightsEnabled: true,
  111425. texturesEnabled: true,
  111426. lensFlaresEnabled: false,
  111427. proceduralTexturesEnabled: false,
  111428. renderTargetsEnabled: true,
  111429. spritesEnabled: false,
  111430. skeletonsEnabled: true,
  111431. audioEnabled: false,
  111432. },
  111433. defaultMaterial: {
  111434. materialType: 'pbr',
  111435. reflectivityColor: {
  111436. r: 0.1,
  111437. g: 0.1,
  111438. b: 0.1
  111439. },
  111440. microSurface: 0.6
  111441. },
  111442. clearColor: {
  111443. r: 0.9,
  111444. g: 0.9,
  111445. b: 0.9,
  111446. a: 1.0
  111447. },
  111448. imageProcessingConfiguration: {
  111449. vignetteCentreX: 0,
  111450. vignetteCentreY: 0,
  111451. vignetteColor: {
  111452. r: 0.086,
  111453. g: 0.184,
  111454. b: 0.259,
  111455. a: 1
  111456. },
  111457. vignetteWeight: 0.855,
  111458. vignetteStretch: 0.5,
  111459. vignetteBlendMode: 0,
  111460. vignetteCameraFov: 0.7853981633974483,
  111461. isEnabled: true,
  111462. colorCurves: {
  111463. shadowsHue: 0,
  111464. shadowsDensity: 0,
  111465. shadowsSaturation: 0,
  111466. shadowsExposure: 0,
  111467. midtonesHue: 0,
  111468. midtonesDensity: 0,
  111469. midtonesExposure: 0,
  111470. midtonesSaturation: 0,
  111471. highlightsHue: 0,
  111472. highlightsDensity: 0,
  111473. highlightsExposure: 0,
  111474. highlightsSaturation: 0
  111475. }
  111476. },
  111477. mainColor: {
  111478. r: 0.8823529411764706,
  111479. g: 0.8823529411764706,
  111480. b: 0.8823529411764706
  111481. }
  111482. },
  111483. loaderPlugins: {
  111484. extendedMaterial: true,
  111485. applyMaterialConfig: true,
  111486. msftLod: true,
  111487. telemetry: true
  111488. },
  111489. model: {
  111490. rotationOffsetAxis: {
  111491. x: 0,
  111492. y: -1,
  111493. z: 0
  111494. },
  111495. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  111496. material: {
  111497. directEnabled: true,
  111498. directIntensity: 0.884,
  111499. emissiveIntensity: 1.04,
  111500. environmentIntensity: 0.6
  111501. },
  111502. entryAnimation: {
  111503. scaling: {
  111504. x: 0,
  111505. y: 0,
  111506. z: 0
  111507. },
  111508. time: 0.5,
  111509. easingFunction: 4,
  111510. easingMode: 1
  111511. },
  111512. exitAnimation: {
  111513. scaling: {
  111514. x: 0,
  111515. y: 0,
  111516. z: 0
  111517. },
  111518. time: 0.5,
  111519. easingFunction: 4,
  111520. easingMode: 1
  111521. },
  111522. normalize: true,
  111523. castShadow: true,
  111524. receiveShadows: true
  111525. },
  111526. lab: {
  111527. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  111528. environmentMap: {
  111529. texture: "EnvMap_2.0-256.env",
  111530. rotationY: 3,
  111531. tintLevel: 0.4
  111532. },
  111533. defaultRenderingPipelines: {
  111534. bloomEnabled: true,
  111535. bloomThreshold: 1.0,
  111536. fxaaEnabled: true,
  111537. bloomWeight: 0.05
  111538. }
  111539. }
  111540. };
  111541. /***/ }),
  111542. /* 48 */
  111543. /***/ (function(module, exports, __webpack_require__) {
  111544. "use strict";
  111545. Object.defineProperty(exports, "__esModule", { value: true });
  111546. /**
  111547. * Defines a default directional shadow light for normalized objects (!)
  111548. */
  111549. exports.shadowDirectionalLightConfiguration = {
  111550. model: {
  111551. receiveShadows: true,
  111552. castShadow: true
  111553. },
  111554. ground: {
  111555. receiveShadows: true
  111556. },
  111557. lights: {
  111558. shadowDirectionalLight: {
  111559. type: 1,
  111560. shadowEnabled: true,
  111561. target: { x: 0, y: 0, z: 0.5 },
  111562. position: { x: 1.49, y: 2.39, z: -1.33 },
  111563. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  111564. intensity: 4.887,
  111565. intensityMode: 0,
  111566. shadowBufferSize: 1024,
  111567. shadowFrustumSize: 6.0,
  111568. shadowFieldOfView: 50.977,
  111569. shadowMinZ: 0.1,
  111570. shadowMaxZ: 10.0,
  111571. shadowConfig: {
  111572. blurKernel: 32,
  111573. useBlurCloseExponentialShadowMap: true
  111574. }
  111575. }
  111576. }
  111577. };
  111578. /**
  111579. * Defines a default shadow-enabled spot light for normalized objects.
  111580. */
  111581. exports.shadowSpotlLightConfiguration = {
  111582. model: {
  111583. receiveShadows: true,
  111584. castShadow: true
  111585. },
  111586. ground: {
  111587. receiveShadows: true
  111588. },
  111589. lights: {
  111590. shadowSpotLight: {
  111591. type: 2,
  111592. intensity: 2,
  111593. shadowEnabled: true,
  111594. target: { x: 0, y: 0, z: 0.5 },
  111595. position: { x: 0, y: 3.5, z: 3.7 },
  111596. angle: 1,
  111597. shadowOrthoScale: 0.5,
  111598. shadowBufferSize: 1024,
  111599. shadowMinZ: 0.1,
  111600. shadowMaxZ: 50.0,
  111601. shadowConfig: {
  111602. frustumEdgeFalloff: 0.5,
  111603. blurKernel: 32,
  111604. useBlurExponentialShadowMap: true
  111605. }
  111606. }
  111607. }
  111608. };
  111609. /***/ }),
  111610. /* 49 */
  111611. /***/ (function(module, exports, __webpack_require__) {
  111612. "use strict";
  111613. Object.defineProperty(exports, "__esModule", { value: true });
  111614. /**
  111615. * Lab-oriented default .env support
  111616. */
  111617. exports.environmentMapConfiguration = {
  111618. lab: {
  111619. assetsRootURL: '/assets/environment/',
  111620. environmentMap: {
  111621. texture: 'EnvMap_2.0-256.env',
  111622. rotationY: 0,
  111623. tintLevel: 0.4
  111624. }
  111625. }
  111626. };
  111627. /***/ }),
  111628. /* 50 */
  111629. /***/ (function(module, exports, __webpack_require__) {
  111630. "use strict";
  111631. Object.defineProperty(exports, "__esModule", { value: true });
  111632. var _1 = __webpack_require__(21);
  111633. /**
  111634. * This function will make sure the configuration file is taking deprecated fields into account
  111635. * and is setting them to the correct keys and values.
  111636. *
  111637. * @param configuration The configuration to process. Mutable!
  111638. */
  111639. function processConfigurationCompatibility(configuration) {
  111640. if (configuration.camera) {
  111641. // camera contrast -> image processing contrast
  111642. if (configuration.camera.contrast !== undefined) {
  111643. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  111644. }
  111645. // camera exposure -> image processing exposure
  111646. if (configuration.camera.exposure !== undefined) {
  111647. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  111648. }
  111649. }
  111650. if (configuration.scene) {
  111651. //glow
  111652. if (configuration.scene.glow) {
  111653. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  111654. var enabledProcessing = _1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  111655. if (enabledProcessing !== false) {
  111656. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  111657. }
  111658. }
  111659. }
  111660. }
  111661. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  111662. function setKeyInObject(object, keys, value, shouldOverwrite) {
  111663. var keySplit = keys.split(".");
  111664. if (keySplit.length === 0)
  111665. return;
  111666. var lastKey = keySplit.pop();
  111667. if (!lastKey)
  111668. return;
  111669. var curObj = object;
  111670. keySplit.forEach(function (key) {
  111671. curObj[key] = curObj[key] || {};
  111672. curObj = curObj[key];
  111673. });
  111674. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  111675. return;
  111676. curObj[lastKey] = value;
  111677. }
  111678. /***/ }),
  111679. /* 51 */
  111680. /***/ (function(module, exports, __webpack_require__) {
  111681. "use strict";
  111682. Object.defineProperty(exports, "__esModule", { value: true });
  111683. var telemetryLoaderPlugin_1 = __webpack_require__(52);
  111684. var msftLodLoaderPlugin_1 = __webpack_require__(53);
  111685. var applyMaterialConfig_1 = __webpack_require__(54);
  111686. var extendedMaterialLoaderPlugin_1 = __webpack_require__(55);
  111687. var pluginCache = {};
  111688. /**
  111689. * Get a loader plugin according to its name.
  111690. * The plugin will be cached and will be reused if called for again.
  111691. *
  111692. * @param name the name of the plugin
  111693. */
  111694. function getLoaderPluginByName(name) {
  111695. if (!pluginCache[name]) {
  111696. switch (name) {
  111697. case 'telemetry':
  111698. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  111699. break;
  111700. case 'msftLod':
  111701. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  111702. break;
  111703. case 'applyMaterialConfig':
  111704. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  111705. break;
  111706. case 'extendedMaterial':
  111707. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  111708. break;
  111709. }
  111710. }
  111711. return pluginCache[name];
  111712. }
  111713. exports.getLoaderPluginByName = getLoaderPluginByName;
  111714. /***/ }),
  111715. /* 52 */
  111716. /***/ (function(module, exports, __webpack_require__) {
  111717. "use strict";
  111718. Object.defineProperty(exports, "__esModule", { value: true });
  111719. var telemetryManager_1 = __webpack_require__(5);
  111720. var babylonjs_1 = __webpack_require__(0);
  111721. var TelemetryLoaderPlugin = /** @class */ (function () {
  111722. function TelemetryLoaderPlugin() {
  111723. }
  111724. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  111725. this._model = model;
  111726. this._loadStart = babylonjs_1.Tools.Now;
  111727. };
  111728. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  111729. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewer(), {
  111730. model: model,
  111731. loadTime: babylonjs_1.Tools.Now - this._loadStart
  111732. });
  111733. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  111734. };
  111735. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  111736. this._loadEnd = babylonjs_1.Tools.Now;
  111737. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  111738. model: this._model,
  111739. loadTime: this._loadEnd - this._loadStart
  111740. });
  111741. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  111742. };
  111743. TelemetryLoaderPlugin.prototype.onComplete = function () {
  111744. this._loadEnd = babylonjs_1.Tools.Now;
  111745. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  111746. model: this._model,
  111747. loadTime: this._loadEnd - this._loadStart
  111748. });
  111749. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  111750. };
  111751. return TelemetryLoaderPlugin;
  111752. }());
  111753. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  111754. /***/ }),
  111755. /* 53 */
  111756. /***/ (function(module, exports, __webpack_require__) {
  111757. "use strict";
  111758. Object.defineProperty(exports, "__esModule", { value: true });
  111759. /**
  111760. * A loder plugin to use MSFT_lod extension correctly (glTF)
  111761. */
  111762. var MSFTLodLoaderPlugin = /** @class */ (function () {
  111763. function MSFTLodLoaderPlugin() {
  111764. }
  111765. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  111766. this._model = model;
  111767. };
  111768. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  111769. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  111770. var MSFT_lod = extension;
  111771. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  111772. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  111773. }
  111774. };
  111775. return MSFTLodLoaderPlugin;
  111776. }());
  111777. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  111778. /***/ }),
  111779. /* 54 */
  111780. /***/ (function(module, exports, __webpack_require__) {
  111781. "use strict";
  111782. Object.defineProperty(exports, "__esModule", { value: true });
  111783. /**
  111784. * Force-apply material configuration right after a material was loaded.
  111785. */
  111786. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  111787. function ApplyMaterialConfigPlugin() {
  111788. }
  111789. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  111790. this._model = model;
  111791. };
  111792. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  111793. this._model && this._model._applyModelMaterialConfiguration(material);
  111794. };
  111795. return ApplyMaterialConfigPlugin;
  111796. }());
  111797. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  111798. /***/ }),
  111799. /* 55 */
  111800. /***/ (function(module, exports, __webpack_require__) {
  111801. "use strict";
  111802. Object.defineProperty(exports, "__esModule", { value: true });
  111803. var babylonjs_1 = __webpack_require__(0);
  111804. /**
  111805. * A (PBR) material will be extended using this function.
  111806. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  111807. */
  111808. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  111809. function ExtendedMaterialLoaderPlugin() {
  111810. }
  111811. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  111812. var material = baseMaterial;
  111813. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  111814. };
  111815. return ExtendedMaterialLoaderPlugin;
  111816. }());
  111817. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  111818. /***/ }),
  111819. /* 56 */
  111820. /***/ (function(module, exports, __webpack_require__) {
  111821. /*!
  111822. * PEP v0.4.3 | https://github.com/jquery/PEP
  111823. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  111824. */
  111825. !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);
  111826. // define inherited MouseEvent properties
  111827. // skip bubbles and cancelable since they're set above in initEvent()
  111828. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  111829. // Spec requires that pointers without pressure specified use 0.5 for down
  111830. // state and 0 for up state.
  111831. var f=0;
  111832. // add x/y properties aliased to clientX/Y
  111833. // define the properties of the PointerEvent interface
  111834. 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(){
  111835. // only activate if this platform does not have pointer events
  111836. 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}})}/**
  111837. * This is the constructor for new PointerEvents.
  111838. *
  111839. * New Pointer Events must be given a type, and an optional dictionary of
  111840. * initialization properties.
  111841. *
  111842. * Due to certain platform requirements, events returned from the constructor
  111843. * identify as MouseEvents.
  111844. *
  111845. * @constructor
  111846. * @param {String} inType The type of the event to create.
  111847. * @param {Object} [inDict] An optional dictionary of initial event properties.
  111848. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  111849. */
  111850. 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},
  111851. // return value, key, map
  111852. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  111853. // MouseEvent
  111854. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  111855. // DOM Level 3
  111856. "buttons",
  111857. // PointerEvent
  111858. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  111859. // event instance
  111860. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  111861. // MouseEvent
  111862. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  111863. // DOM Level 3
  111864. 0,
  111865. // PointerEvent
  111866. 0,0,0,0,0,0,"",0,!1,
  111867. // event instance
  111868. "",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),
  111869. // Scope objects for native events.
  111870. // This exists for ease of testing.
  111871. eventSources:Object.create(null),eventSourceList:[],/**
  111872. * Add a new event source that will generate pointer events.
  111873. *
  111874. * `inSource` must contain an array of event names named `events`, and
  111875. * functions with the names specified in the `events` array.
  111876. * @param {string} name A name for the event source
  111877. * @param {Object} source A new source of platform events.
  111878. */
  111879. 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++)
  111880. // call eventsource register
  111881. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  111882. // call eventsource register
  111883. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  111884. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  111885. return!1}},
  111886. // EVENTS
  111887. 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)},
  111888. // LISTENER LOGIC
  111889. eventHandler:function(a){
  111890. // This is used to prevent multiple dispatch of pointerevents from
  111891. // platform events. This can happen when two elements in different scopes
  111892. // are set up to create pointer events, which is relevant to Shadow DOM.
  111893. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  111894. // set up event listeners
  111895. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  111896. // remove event listeners
  111897. 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)},
  111898. // EVENT CREATION AND TRACKING
  111899. /**
  111900. * Creates a new Event of type `inType`, based on the information in
  111901. * `inEvent`.
  111902. *
  111903. * @param {string} inType A string representing the type of event to create
  111904. * @param {Event} inEvent A platform event with a target
  111905. * @return {Event} A PointerEvent of type `inType`
  111906. */
  111907. makeEvent:function(b,c){
  111908. // relatedTarget must be null if pointer is captured
  111909. 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},
  111910. // make and dispatch an event in one call
  111911. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  111912. * Returns a snapshot of inEvent, with writable properties.
  111913. *
  111914. * @param {Event} inEvent An event that contains properties to copy.
  111915. * @return {Object} An object containing shallow copies of `inEvent`'s
  111916. * properties.
  111917. */
  111918. 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],
  111919. // Work around SVGInstanceElement shadow tree
  111920. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  111921. // This is the behavior implemented by Firefox.
  111922. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  111923. // keep the semantics of preventDefault
  111924. 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){
  111925. // Order of conditions due to document.contains() missing in IE.
  111926. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  111927. // Touch: Do not propagate if node is detached.
  111928. 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)}},/**
  111929. * Dispatches the event to its target.
  111930. *
  111931. * @param {Event} inEvent The event to be dispatched.
  111932. * @return {Boolean} True if an event handler returns true, false otherwise.
  111933. */
  111934. 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(
  111935. // is element a shadow host?
  111936. e=this.targetingShadow(f);e;){if(
  111937. // find the the element inside the shadow root
  111938. d=e.elementFromPoint(b,c)){
  111939. // shadowed element may contain a shadow root
  111940. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  111941. // check for older shadows
  111942. e=this.olderShadow(e)}
  111943. // light dom element is the target
  111944. return f}},owner:function(a){
  111945. // walk up until you hit the shadow root or document
  111946. for(var b=a;b.parentNode;)b=b.parentNode;
  111947. // the owner element is expected to be a Document or ShadowRoot
  111948. 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);
  111949. // if x, y is not in this root, fall back to document search
  111950. 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){
  111951. // Only watch scopes that can target find, as these are top-level.
  111952. // Otherwise we can see duplicate additions and removals that add noise.
  111953. //
  111954. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  111955. // a removal without an insertion when a node is redistributed among
  111956. // shadows. Since it all ends up correct in the document, watching only
  111957. // the document will yield the correct mutations to watch.
  111958. 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))},
  111959. // register all touch-action = none nodes on document load
  111960. 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){
  111961. // find children with touch-action
  111962. var b=x(a,this.findElements,this);
  111963. // flatten the list
  111964. // make sure the added nodes are accounted for
  111965. 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){}
  111966. // handler block for native mouse events
  111967. 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:[],
  111968. // collide with the global mouse listener
  111969. 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++){
  111970. // simulated mouse events will be swallowed near a primary touchend
  111971. 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);
  111972. // Update buttons state after possible out-of-document mouseup.
  111973. 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];
  111974. // Produces wrong state of buttons in Browsers without `buttons` support
  111975. // when a mouse button that was pressed outside the document is released
  111976. // inside and other buttons are still pressed down.
  111977. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  111978. // Support: Firefox <=44 only
  111979. // FF Ubuntu includes the lifted button in the `buttons` property on
  111980. // mouseup.
  111981. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  111982. 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),
  111983. // set touch-action on shadows as well
  111984. 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),
  111985. // remove touch-action from shadow
  111986. 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);
  111987. // simply update scrollType if listeners are already established
  111988. 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){
  111989. // set primary touch if there no pointers, or the only pointer is the mouse
  111990. (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,
  111991. // forward modifier keys
  111992. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  111993. // forward touch preventDefaults
  111994. 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))},
  111995. // For single axis scrollers, determines whether the element should emit
  111996. // pointer events or behave as a scroller
  111997. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  111998. // this element is a touch-action: none, should never scroll
  111999. b=!1;else if("XY"===c)
  112000. // this element should always scroll
  112001. 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]);
  112002. // if delta in the scroll axis > delta other axis, scroll instead of
  112003. // making events
  112004. 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},
  112005. // In some instances, a touchstart can happen without a touchend. This
  112006. // leaves the pointermap in a broken state.
  112007. // Therefore, on every touchstart, we remove the touches that did not fire a
  112008. // touchend event.
  112009. // To keep state globally consistent, we fire a
  112010. // pointercancel for this "abandoned" touch
  112011. vacuumTouches:function(a){var b=a.touches;
  112012. // pointermap.size should be < tl.length here, as the touchstart has not
  112013. // been processed yet.
  112014. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  112015. // Never remove pointerId == 1, which is mouse.
  112016. // Touch identifiers are 2 smaller than their pointerId, which is the
  112017. // index in pointermap.
  112018. 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);
  112019. // a finger drifted off the screen, ignore it
  112020. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  112021. // recover from retargeting by shadow
  112022. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  112023. // clean up case when finger leaves the screen
  112024. 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)},
  112025. // prevent synth mouse events from creating pointer events
  112026. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  112027. // only the primary finger will synth mouse events
  112028. if(this.isPrimaryTouch(c)){
  112029. // remember x/y of last touch
  112030. 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});
  112031. /***/ }),
  112032. /* 57 */
  112033. /***/ (function(module, exports, __webpack_require__) {
  112034. "use strict";
  112035. Object.defineProperty(exports, "__esModule", { value: true });
  112036. var defaultViewer_1 = __webpack_require__(9);
  112037. var mappers_1 = __webpack_require__(3);
  112038. var _1 = __webpack_require__(6);
  112039. /**
  112040. * Will attach an init function the the DOMContentLoaded event.
  112041. * The init function will be removed automatically after the event was triggered.
  112042. */
  112043. function initListeners() {
  112044. document.addEventListener("DOMContentLoaded", init);
  112045. function init(event) {
  112046. document.removeEventListener("DOMContentLoaded", init);
  112047. if (_1.viewerGlobals.disableInit || _1.disableInit)
  112048. return;
  112049. InitTags();
  112050. }
  112051. }
  112052. exports.initListeners = initListeners;
  112053. /**
  112054. * Select all HTML tags on the page that match the selector and initialize a viewer
  112055. *
  112056. * @param selector the selector to initialize the viewer on (default is 'babylon')
  112057. */
  112058. function InitTags(selector) {
  112059. if (selector === void 0) { selector = 'babylon'; }
  112060. var elements = document.querySelectorAll(selector);
  112061. for (var i = 0; i < elements.length; ++i) {
  112062. var element = elements.item(i);
  112063. // get the html configuration
  112064. var configMapper = mappers_1.mapperManager.getMapper('dom');
  112065. var config = configMapper.map(element);
  112066. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  112067. }
  112068. }
  112069. exports.InitTags = InitTags;
  112070. /***/ })
  112071. /******/ ]);
  112072. return BabylonViewer;
  112073. });